The headless browser for AI agents and web scraping
fix(js): implement context-owned IndexedDB transactions
SGavrl3dea54899794
diff --git a/crates/obscura-browser/src/context.rs b/crates/obscura-browser/src/context.rsindex 7e36e3cb..fb68a9cc 100644--- a/crates/obscura-browser/src/context.rs+++ b/crates/obscura-browser/src/context.rs@@ -11,6 +11,7 @@ pub struct BrowserContext {/// rather than by a V8 realm, so an entry written in one document is still/// there in the next (issue #678).pub local_storage: Arc<OriginStorage>,+ pub indexed_db: Arc<obscura_js::indexed_db::IndexedDbStorage>,pub http_client: Arc<ObscuraHttpClient>,pub user_agent: String,pub platform: String,@@ -200,6 +201,7 @@ impl BrowserContext {id,cookie_jar,local_storage,+ indexed_db: Arc::new(obscura_js::indexed_db::IndexedDbStorage::default()),http_client,user_agent: resolved_ua,platform,@@ -265,6 +267,8 @@ impl BrowserContext {} else {Arc::new(OriginStorage::default())},+ indexed_db: if persistent { self.indexed_db.clone() }+ else { Arc::new(obscura_js::indexed_db::IndexedDbStorage::default()) },http_client: Arc::new(client),user_agent: self.user_agent.clone(),platform: self.platform.clone(),diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rsindex fbff0ca6..34a76408 100644--- a/crates/obscura-browser/src/page.rs+++ b/crates/obscura-browser/src/page.rs@@ -1853,6 +1853,7 @@ impl Page {rt.set_cookie_jar(self.context.cookie_jar.clone());// Web Storage lives outside the realm so a navigation cannot drop it.rt.set_local_storage(self.context.local_storage.clone());+ rt.set_indexed_db(self.context.indexed_db.clone());rt.set_session_storage(self.session_storage.clone());rt.set_http_client(self.http_client.clone());rt.set_callbacks(self.callbacks.clone());@@ -4758,6 +4759,10 @@ impl Page {self.js.is_some()}+ pub fn has_pending_indexed_db_notifications(&self) -> bool {+ self.context.indexed_db.has_pending_notifications()+ }+pub fn release_object_group(&mut self) {if let Some(js) = &mut self.js {js.release_object_group();@@ -6788,6 +6793,55 @@ mod tests {assert_eq!(page.evaluate("sessionStorage.getItem('s1')").as_str(), Some("session-value"));}+ #[tokio::test]+ async fn indexeddb_records_survive_navigation_and_share_only_their_context_and_origin() {+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");+ let (origin_a, _) = spawn_storage_server().await;+ let (origin_b, _) = spawn_storage_server().await;+ let context = std::sync::Arc::new(crate::BrowserContext::new("idb-shared".into()));+ let mut first = storage_page("idb-first", context.clone());+ first.navigate(&origin_a).await.unwrap();+ first.evaluate(r#"(() => {+ globalThis.idbSaved = false;+ const r = indexedDB.open('shared',1);+ r.onupgradeneeded = () => r.result.createObjectStore('items');+ r.onsuccess = () => {+ const tx = r.result.transaction('items','readwrite');+ tx.objectStore('items').put({value:'kept'},1);+ tx.oncomplete = () => idbSaved = true;+ };+ })()"#);+ first.js.as_mut().unwrap().run_event_loop_bounded(500).await.unwrap();+ assert_eq!(first.evaluate("idbSaved"), serde_json::json!(true));+ let read = r#"(() => {+ globalThis.idbRead = 'pending';+ const r = indexedDB.open('shared',1);+ r.onupgradeneeded = () => r.result.createObjectStore('items');+ r.onsuccess = () => {+ const q = r.result.transaction('items').objectStore('items').get(1);+ q.onsuccess = () => idbRead = q.result?.value ?? null;+ };+ })()"#;+ first.navigate(&origin_b).await.unwrap();+ first.evaluate(read);+ first.js.as_mut().unwrap().run_event_loop_bounded(500).await.unwrap();+ assert_eq!(first.evaluate("idbRead"), serde_json::Value::Null);+ first.navigate(&origin_a).await.unwrap();+ first.evaluate(read);+ first.js.as_mut().unwrap().run_event_loop_bounded(500).await.unwrap();+ assert_eq!(first.evaluate("idbRead"), serde_json::json!("kept"));+ let mut second = storage_page("idb-second", context);+ second.navigate(&origin_a).await.unwrap();+ second.evaluate(read);+ second.js.as_mut().unwrap().run_event_loop_bounded(500).await.unwrap();+ assert_eq!(second.evaluate("idbRead"), serde_json::json!("kept"));+ let mut isolated = storage_page("idb-isolated", std::sync::Arc::new(crate::BrowserContext::new("idb-private".into())));+ isolated.navigate(&origin_a).await.unwrap();+ isolated.evaluate(read);+ isolated.js.as_mut().unwrap().run_event_loop_bounded(500).await.unwrap();+ assert_eq!(isolated.evaluate("idbRead"), serde_json::Value::Null);+ }+#[tokio::test]async fn session_storage_stays_inside_the_tab_and_local_storage_is_shared() {std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");diff --git a/crates/obscura-cdp/src/domains/runtime.rs b/crates/obscura-cdp/src/domains/runtime.rsindex 00a8dca0..960a595f 100644--- a/crates/obscura-cdp/src/domains/runtime.rs+++ b/crates/obscura-cdp/src/domains/runtime.rs@@ -5,6 +5,50 @@ use serde_json::{json, Value};use crate::dispatch::CdpContext;+async fn with_live_peers<'a, F, Fut>(+ ctx: &'a mut CdpContext,+ session_id: &Option<String>,+ command: F,+) -> Result<RemoteObjectInfo, String>+where+ F: FnOnce(&'a mut obscura_browser::Page) -> Fut,+ Fut: std::future::Future<Output = Result<RemoteObjectInfo, String>>,+{+ if ctx.pages.len() == 1 {+ return command(ctx.get_session_page_mut(session_id).ok_or("No page")?).await;+ }+ let id = ctx.get_session_page_mut(session_id).ok_or("No page")?.id.clone();+ let index = ctx.pages.iter().position(|page| page.id == id).ok_or("No page")?;+ let (before, remaining) = ctx.pages.split_at_mut(index);+ let (page, after) = remaining.split_first_mut().ok_or("No page")?;+ let command = command(page);+ let peers = async {+ let mut idle = std::collections::HashSet::new();+ loop {+ let all_idle = match crate::server::pump_page_event_loops(before.iter_mut().chain(after.iter_mut()), &mut idle).await {+ Ok(idle) => idle,+ Err(error) => return error,+ };+ if all_idle {+ // Foreground and peer futures share this task's waker. Park+ // idle peers until it wakes again, without a polling timer.+ let mut parked = false;+ std::future::poll_fn(|_| {+ if parked { std::task::Poll::Ready(()) }+ else { parked = true; std::task::Poll::Pending }+ }).await;+ } else {+ tokio::task::yield_now().await;+ }+ }+ };+ tokio::select! {+ biased;+ result = command => result,+ error = peers => Err(error),+ }+}+pub(crate) fn execution_context_created_event(context: &crate::dispatch::ExecutionContextRecord,session_id: Option<String>,@@ -176,17 +220,14 @@ pub async fn handle(.and_then(|v| v.as_u64()).unwrap_or(30_000);- let page = ctx- .get_session_page_mut(session_id)- .ok_or("No page")?;let info = match tokio::time::timeout(std::time::Duration::from_millis(timeout_ms),- page.evaluate_for_cdp_with_timeout(+ with_live_peers(ctx, session_id, |page| page.evaluate_for_cdp_with_timeout(expression,return_by_value,await_promise,timeout_ms,- ),+ )),).await{@@ -238,19 +279,16 @@ pub async fn handle(.and_then(|v| v.as_u64()).unwrap_or(30_000);- let page = ctx- .get_session_page_mut(session_id)- .ok_or("No page")?;let info = match tokio::time::timeout(std::time::Duration::from_millis(timeout_ms),- page.call_function_on_for_cdp_with_timeout(+ with_live_peers(ctx, session_id, |page| page.call_function_on_for_cdp_with_timeout(function_declaration,object_id,&arguments,return_by_value,await_promise,timeout_ms,- ),+ )),).await{@@ -589,6 +627,35 @@ mod tests {use super::*;use crate::dispatch::CdpContext;+ #[tokio::test(flavor = "current_thread")]+ async fn indexeddb_awaited_commands_deliver_peer_versionchange_and_delayed_close() {+ for method in ["evaluate", "callFunctionOn"] {+ let mut ctx = CdpContext::new();+ let mut sessions = Vec::new();+ for _ in 0..2 {+ let id = ctx.create_page();+ let session = Some(format!("{id}-session"));+ ctx.sessions.insert(session.clone().unwrap(),id);+ crate::domains::page::handle("navigate",&json!({"url":"data:text/html,<body>idb</body>"}),&mut ctx,&session).await.unwrap();+ ctx.get_session_page_mut(&session).unwrap().js.as_mut().unwrap().set_url("https://idb.test/");+ sessions.push(session);+ }+ let first = ctx.get_session_page_mut(&sessions[0]).unwrap();+ first.evaluate(r#"(() => {+ const r = indexedDB.open('awaited-peer',1);+ r.onsuccess = () => {globalThis.peer = r.result;+ peer.onversionchange = () => setTimeout(() => peer.close(),10);};+ })()"#);+ first.js.as_mut().unwrap().run_event_loop_bounded(100).await.unwrap();+ let body = "return new Promise((resolve,reject)=>{const r=indexedDB.open('awaited-peer',2);r.onsuccess=()=>{r.result.close();resolve(r.result.version)};r.onerror=()=>reject(r.error)})";+ let mut params = json!({"awaitPromise":true,"returnByValue":true,"timeout":1000});+ if method == "evaluate" { params["expression"] = json!(format!("(()=>{{{body}}})()")); }+ else { params["functionDeclaration"] = json!(format!("function(){{{body}}}")); }+ let result = handle(method,¶ms,&mut ctx,&sessions[1]).await.unwrap();+ assert_eq!(result["result"]["value"].as_f64(),Some(2.0),"{method}: {result}");+ }+ }+#[tokio::test(flavor = "current_thread")]async fn heap_usage_reports_live_v8_allocations_without_running_page_tasks() {let mut ctx = CdpContext::new();diff --git a/crates/obscura-cdp/src/server.rs b/crates/obscura-cdp/src/server.rsindex 57f22c53..1241ec2b 100644--- a/crates/obscura-cdp/src/server.rs+++ b/crates/obscura-cdp/src/server.rs@@ -1533,6 +1533,13 @@ fn emit_routed_intercepted_request(async fn pump_live_page_event_loop(ctx: &mut CdpContext,idle_pages: &mut HashSet<String>,+) -> Result<bool, String> {+ pump_page_event_loops(ctx.pages.iter_mut(), idle_pages).await+}++pub(crate) async fn pump_page_event_loops<'a>(+ pages: impl Iterator<Item = &'a mut obscura_browser::Page>,+ idle_pages: &mut HashSet<String>,) -> Result<bool, String> {use std::future::Future;use std::task::Poll;@@ -1542,9 +1549,11 @@ async fn pump_live_page_event_loop(// A completed turn can emit events even when it leaves its page idle.// Publish it now, then omit idle pages until a command schedules new work;// otherwise an idle peer would keep a waiting connection spinning.- let mut turns: Vec<_> = ctx.pages.iter_mut()- .filter(|page| page.has_js() && !idle_pages.contains(&page.id))- .map(|page| (page.id.clone(), Box::pin(page.run_autonomous_event_loop_turn())))+ let mut turns: Vec<_> = pages.filter_map(|page| {+ if page.has_pending_indexed_db_notifications() { idle_pages.remove(&page.id); }+ if !page.has_js() || idle_pages.contains(&page.id) { return None; }+ Some((page.id.clone(), Box::pin(page.run_autonomous_event_loop_turn())))+ }).collect();std::future::poll_fn(|cx| {let mut all_idle = true;@@ -3717,6 +3726,44 @@ mod tests {assert!(reply_rx.try_recv().is_err(), "abort emits one failure and one response");}+ #[tokio::test(flavor = "current_thread")]+ async fn indexeddb_versionchange_rearms_an_idle_page_until_its_delayed_close() {+ let mut ctx = crate::dispatch::CdpContext::new();+ let mut ids = Vec::new();+ for _ in 0..2 {+ let id = ctx.create_page();+ let session = Some(format!("{id}-session"));+ ctx.sessions.insert(session.clone().unwrap(),id.clone());+ crate::domains::page::handle("navigate", &json!({"url":"data:text/html,<body>idb</body>"}), &mut ctx, &session).await.unwrap();+ ctx.get_page_mut(&id).unwrap().js.as_mut().unwrap().set_url("https://idb.test/");+ ids.push(id);+ }+ let mut idle = Default::default();+ ctx.get_page_mut(&ids[0]).unwrap().evaluate(r#"(() => {+ const r = indexedDB.open('idle-upgrade',1);+ globalThis.opened = false;+ r.onsuccess = () => {globalThis.opened = true;+ r.result.onversionchange = () => setTimeout(() => r.result.close(),10);};+ })()"#);+ tokio::time::timeout(std::time::Duration::from_secs(1), async {+ while !pump_live_page_event_loop(&mut ctx,&mut idle).await.unwrap() {}+ }).await.unwrap();+ assert!(idle.contains(&ids[0]));+ assert_eq!(ctx.get_page_mut(&ids[0]).unwrap().evaluate("opened"),json!(true));+ ctx.get_page_mut(&ids[1]).unwrap().evaluate(r#"(() => {+ globalThis.upgraded = false;+ setTimeout(() => {const r = indexedDB.open('idle-upgrade',2);+ r.onsuccess = () => globalThis.upgraded = r.result.version === 2;},10);+ })()"#);+ idle.remove(&ids[1]);+ tokio::time::timeout(std::time::Duration::from_secs(1), async {+ loop {+ pump_live_page_event_loop(&mut ctx,&mut idle).await.unwrap();+ if ctx.get_page_mut(&ids[1]).unwrap().evaluate("upgraded") == json!(true) {break;}+ }+ }).await.expect("versionchange must wake the idle page and retain its delayed-close work");+ }+#[tokio::test(flavor = "current_thread")]async fn autonomous_pages_do_not_wait_for_another_pages_distant_timer() {let mut ctx = crate::dispatch::CdpContext::new();diff --git a/crates/obscura-js/build.rs b/crates/obscura-js/build.rsindex 50965f80..3b5b4e5d 100644--- a/crates/obscura-js/build.rs+++ b/crates/obscura-js/build.rs@@ -3,6 +3,7 @@ use std::process::Command;fn main() {println!("cargo:rerun-if-changed=js/bootstrap.js");+ println!("cargo:rerun-if-changed=js/indexed_db.js");println!("cargo:rerun-if-changed=build.rs");let out_dir = PathBuf::from(std::env::var("OUT_DIR").unwrap());@@ -13,7 +14,9 @@ fn main() {let host = std::env::var("HOST").unwrap_or_default();let is_cross = target != host;- let bootstrap_js = include_str!("js/bootstrap.js");+ let bootstrap_source = include_str!("js/bootstrap.js")+ .replace("/* INDEXED_DB */", include_str!("js/indexed_db.js"));+ let bootstrap_js = bootstrap_source.as_str();if is_cross {// Cross-compilation: the host V8 (linked into this build script) produces@@ -63,6 +66,7 @@ fn main() {// The sidecar contains only fixed-size types (i32, u32, String, Vec) so it// is architecture-independent and can be reused with the target blob.eprintln!("[obscura-js build.rs] Extracting deno_core sidecar from host snapshot...");+ let host_bootstrap = bootstrap_js.to_string();let host_output = deno_core::snapshot::create_snapshot(deno_core::snapshot::CreateSnapshotOptions {cargo_manifest_dir: env!("CARGO_MANIFEST_DIR"),@@ -72,7 +76,7 @@ fn main() {extension_transpiler: None,with_runtime_cb: Some(Box::new(move |runtime| {runtime- .execute_script("<obscura:bootstrap>", bootstrap_js.to_string())+ .execute_script("<obscura:bootstrap>", host_bootstrap.clone()).expect("bootstrap.js should not fail during snapshot creation");})),},diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex 9ca15e1c..dfbd1d76 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -15373,126 +15373,7 @@ globalThis.RTCPeerConnection = class RTCPeerConnection {globalThis.RTCSessionDescription = class RTCSessionDescription { constructor(d){this.type=d?.type;this.sdp=d?.sdp;} };globalThis.RTCIceCandidate = class RTCIceCandidate { constructor(d){this.candidate=d?.candidate||'';} };-// Minimal but spec-shape-correct IndexedDB shim. We don't persist anything,-// but authentication libraries (Firebase, Supabase, dexie) hang forever on-// the first `get` because their request's `onsuccess` is never called. Fire-// `onsuccess` asynchronously with `null` so reads complete-but-empty, which-// most libraries treat as a cache miss and fall back to the network.-function _idbRequest(produceResult) {- const req = {- result: undefined,- error: null,- source: null,- transaction: null,- readyState: 'pending',- onsuccess: null,- onerror: null,- addEventListener(type, fn) { req['on' + type] = fn; },- removeEventListener(type, fn) { if (req['on' + type] === fn) req['on' + type] = null; },- };- Promise.resolve().then(() => {- try {- req.result = produceResult();- req.readyState = 'done';- if (typeof req.onsuccess === 'function') {- try { req.onsuccess({ target: req, type: 'success' }); } catch (e) {}- }- } catch (e) {- req.error = e; req.readyState = 'done';- if (typeof req.onerror === 'function') {- try { req.onerror({ target: req, type: 'error' }); } catch (e2) {}- }- }- });- return req;-}--function _idbObjectStore(name) {- const data = new Map();- return {- name,- keyPath: null,- autoIncrement: false,- indexNames: { contains() { return false; }, length: 0, item() { return null; } },- transaction: null,- add(value, key) { const k = key ?? Date.now(); data.set(k, value); return _idbRequest(() => k); },- put(value, key) { const k = key ?? Date.now(); data.set(k, value); return _idbRequest(() => k); },- get(key) { return _idbRequest(() => data.get(key) ?? undefined); },- getAll() { return _idbRequest(() => Array.from(data.values())); },- getAllKeys() { return _idbRequest(() => Array.from(data.keys())); },- getKey(key) { return _idbRequest(() => (data.has(key) ? key : undefined)); },- delete(key) { return _idbRequest(() => { data.delete(key); return undefined; }); },- clear() { return _idbRequest(() => { data.clear(); return undefined; }); },- count() { return _idbRequest(() => data.size); },- openCursor() { return _idbRequest(() => null); },- openKeyCursor() { return _idbRequest(() => null); },- createIndex() { return { name: '', keyPath: '', unique: false, multiEntry: false, get() { return _idbRequest(() => undefined); } }; },- index() { return { get() { return _idbRequest(() => undefined); }, getAll() { return _idbRequest(() => []); }, count() { return _idbRequest(() => 0); }, openCursor() { return _idbRequest(() => null); } }; },- deleteIndex() {},- };-}--function _idbTransaction(storeNames) {- const stores = new Map();- const names = Array.isArray(storeNames) ? storeNames : [storeNames];- for (const n of names) stores.set(String(n), _idbObjectStore(String(n)));- const tx = {- db: null,- mode: 'readonly',- objectStoreNames: { contains: (n) => stores.has(String(n)), length: stores.size },- onabort: null, oncomplete: null, onerror: null,- error: null,- objectStore(name) {- let s = stores.get(name);- if (!s) { s = _idbObjectStore(name); stores.set(name, s); }- s.transaction = tx;- return s;- },- abort() {},- commit() {},- addEventListener(type, fn) { tx['on' + type] = fn; },- removeEventListener(type, fn) { if (tx['on' + type] === fn) tx['on' + type] = null; },- };- Promise.resolve().then(() => {- if (typeof tx.oncomplete === 'function') {- try { tx.oncomplete({ target: tx, type: 'complete' }); } catch (e) {}- }- });- return tx;-}--function _idbDatabase(name, version) {- return {- name,- version,- objectStoreNames: { contains() { return false; }, length: 0, item() { return null; } },- createObjectStore(n) { return _idbObjectStore(n); },- deleteObjectStore() {},- transaction(storeNames, mode) {- const tx = _idbTransaction(storeNames);- tx.mode = mode || 'readonly';- return tx;- },- close() {},- onversionchange: null, onabort: null, onerror: null, onclose: null,- addEventListener() {}, removeEventListener() {},- };-}--globalThis.indexedDB = {- open(name, version) {- return _idbRequest(() => _idbDatabase(name, version || 1));- },- deleteDatabase(_name) { return _idbRequest(() => undefined); },- databases() { return Promise.resolve([]); },- cmp(a, b) { return a < b ? -1 : a > b ? 1 : 0; },-};-globalThis.IDBKeyRange = {- only(v) { return { lower: v, upper: v, lowerOpen: false, upperOpen: false, includes(x) { return x === v; } }; },- lowerBound(v, open) { return { lower: v, upper: null, lowerOpen: !!open, upperOpen: false, includes(x) { return open ? x > v : x >= v; } }; },- upperBound(v, open) { return { lower: null, upper: v, lowerOpen: false, upperOpen: !!open, includes(x) { return open ? x < v : x <= v; } }; },- bound(l, u, lo, uo) { return { lower: l, upper: u, lowerOpen: !!lo, upperOpen: !!uo, includes(x) { return (lo ? x > l : x >= l) && (uo ? x < u : x <= u); } }; },-};+/* INDEXED_DB */// Do not advertise CacheStorage until it can retain responses. A successful// no-op cache selects broken persistence paths instead of normal fetch fallbacks.@@ -16083,6 +15964,11 @@ if (!globalThis.crypto.subtle) {}return keyMaterial.get(key);}+ _idbPlatformCodecs.push({+ name:"CryptoKey", test:key => keyMaterial.has(key),+ encode:key => ({type:key.type,extractable:key.extractable,algorithm:key.algorithm,usages:key.usages,bytes:keyBytes(key)}),+ decode:data => makeKey(data.type,data.extractable,data.algorithm,data.usages,data.bytes),+ });// A CryptoKey cloned via structuredClone or postMessage is a different// object, so the WeakMap lookup above misses and crypto.subtle throws// "Argument is not a valid CryptoKey". Re-register the (cloned) key'sdiff --git a/crates/obscura-js/js/indexed_db.js b/crates/obscura-js/js/indexed_db.jsnew file mode 100644index 00000000..37c3e9dd--- /dev/null+++ b/crates/obscura-js/js/indexed_db.js@@ -0,0 +1,790 @@+// Included inside bootstrap's private closure when generating the startup snapshot.+const _idbToken = {};+const _idbSlots = new WeakMap();+const _idbConnections = new Map();+const _idbOpenQueues = new Map();+function _idbError(name) { return new DOMException(name, name); }+function _idbOp(action, data) {+ const result = JSON.parse(__obscuraCore.ops.op_indexed_db(action, JSON.stringify(data)));+ if (result && result.error) throw _idbError(result.error);+ return result;+}+function _idbTask(fn) { _browserPostedTaskEnqueue(fn, _schedulerPriorityRank['user-visible'] * 2); }+function _idbSlot(value) {+ const slot = _idbSlots.get(value);+ if (!slot) throw new TypeError('Illegal invocation');+ return slot;+}+function _idbNames(names) {+ const values = names().slice().sort();+ values.item = i => values[Number(i) >>> 0] ?? null;+ values.contains = name => values.includes(String(name));+ return values;+}+function _idbDispatch(target, type, init = {}) {+ const event = globalThis.__obscura_markTrusted(new IDBVersionChangeEvent(type, {+ bubbles: type === 'error' || type === 'abort', cancelable: type === 'error', ...init,+ }));+ event.target = target;+ event._dispatching = true;+ let threw = false, current = target;+ while (current) {+ event.currentTarget = current;+ event.eventPhase = current === target ? 2 : 3;+ const listeners = (_eventTargetListeners.get(current)?.get(type) || []).slice();+ const invoke = callback => {+ try {+ if (typeof callback === 'function') callback.call(current, event);+ else callback?.handleEvent(event);+ } catch (error) { threw = true; globalThis.reportError(error); }+ };+ for (const listener of listeners) {+ if (event._immediatePropagationStopped) break;+ if (!(_eventTargetListeners.get(current)?.get(type) || []).includes(listener)) continue;+ if (listener.once) _eventTargetRemove(current, type, listener.callback, listener.capture);+ invoke(listener.callback);+ }+ if (!event.bubbles || event._propagationStopped) break;+ const slot = _idbSlot(current);+ current = slot.transaction || slot.db || null;+ }+ event.currentTarget = null; event.eventPhase = 0;+ event._dispatching = false;+ return { canceled:event.defaultPrevented, threw };+}+function _idbInitialize(target, token, state) {+ if (token !== _idbToken) throw new TypeError('Illegal constructor');+ _idbSlots.set(target, {handlers:{},handlerListeners:{}, ...state});+}+class IDBVersionChangeEvent extends Event {+ constructor(type, init = {}) {+ super(type, init);+ this.oldVersion = Number(init.oldVersion || 0);+ this.newVersion = init.newVersion == null ? null : Number(init.newVersion);+ }+}+class IDBRequest {+ constructor(token, state = {}) { _idbInitialize(this,token,{result:undefined,error:null,source:null,transaction:null,readyState:'pending',...state}); }+ get result() { const s = _idbSlot(this); if (s.readyState !== 'done') throw _idbError('InvalidStateError'); return s.result; }+ get error() { const s = _idbSlot(this); if (s.readyState !== 'done') throw _idbError('InvalidStateError'); return s.error; }+ get source() { return _idbSlot(this).source; }+ get transaction() { return _idbSlot(this).transaction; }+ get readyState() { return _idbSlot(this).readyState; }+}+class IDBOpenDBRequest extends IDBRequest {}+function _idbSettle(request, result, error = null) {+ Object.assign(_idbSlot(request), {result,error,readyState:'done'});+ return _idbDispatch(request, error ? 'error' : 'success');+}+function _idbKey(value, seen = new Set()) {+ if (typeof value === 'number' && !Number.isNaN(value)) return [0,String(value === 0 ? 0 : value)];+ if (value instanceof Date && !Number.isNaN(value.getTime())) return [1,String(value.getTime())];+ if (typeof value === 'string') return [2,value];+ if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {+ const bytes = value instanceof ArrayBuffer ? new Uint8Array(value)+ : new Uint8Array(value.buffer, value.byteOffset, value.byteLength);+ return [3,Array.from(bytes)];+ }+ if (Array.isArray(value) && !seen.has(value)) {+ seen.add(value);+ const keys = [];+ for (let i = 0; i < value.length; i++) {+ if (!(i in value)) throw _idbError('DataError');+ keys.push(_idbKey(value[i], seen));+ }+ seen.delete(value);+ return [4,keys];+ }+ throw _idbError('DataError');+}+function _idbCompare(a, b) {+ if (a[0] !== b[0]) return a[0] < b[0] ? -1 : 1;+ if (a[0] <= 1) return Math.sign(Number(a[1]) - Number(b[1])) || (a[1] === b[1] ? 0 : Number(a[1]) < Number(b[1]) ? -1 : 1);+ if (a[0] === 2) return a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0;+ const x = a[1], y = b[1];+ for (let i = 0; i < Math.min(x.length, y.length); i++) {+ const cmp = a[0] === 4 ? _idbCompare(x[i], y[i]) : Math.sign(x[i] - y[i]);+ if (cmp) return cmp;+ }+ return Math.sign(x.length - y.length);+}+function _idbKeyValue(key) {+ switch (key[0]) {+ case 0: return Number(key[1]);+ case 1: return new Date(Number(key[1]));+ case 2: return key[1];+ case 3: return new Uint8Array(key[1]).buffer;+ default: return key[1].map(_idbKeyValue);+ }+}+class IDBKeyRange {+ constructor(token, lower, upper, lowerOpen, upperOpen) {+ if (token !== _idbToken) throw new TypeError('Illegal constructor');+ _idbSlots.set(this, {lower,upper,lowerOpen,upperOpen});+ }+ get lower() { const k = _idbSlot(this).lower; return k ? _idbKeyValue(k) : undefined; }+ get upper() { const k = _idbSlot(this).upper; return k ? _idbKeyValue(k) : undefined; }+ get lowerOpen() { return _idbSlot(this).lowerOpen; }+ get upperOpen() { return _idbSlot(this).upperOpen; }+ includes(value) { return _idbInRange(_idbKey(value), this); }+ static only(value) { const key = _idbKey(value); return new IDBKeyRange(_idbToken,key,key,false,false); }+ static lowerBound(value, open = false) { return new IDBKeyRange(_idbToken,_idbKey(value),null,!!open,true); }+ static upperBound(value, open = false) { return new IDBKeyRange(_idbToken,null,_idbKey(value),true,!!open); }+ static bound(lower, upper, lowerOpen = false, upperOpen = false) {+ const a = _idbKey(lower), b = _idbKey(upper), cmp = _idbCompare(a,b);+ if (cmp > 0 || cmp === 0 && (lowerOpen || upperOpen)) throw _idbError('DataError');+ return new IDBKeyRange(_idbToken,a,b,!!lowerOpen,!!upperOpen);+ }+}+function _idbRange(value, required = false) {+ if (value instanceof IDBKeyRange) return value;+ if (value === undefined || value === null) { if (required) throw _idbError('DataError'); return null; }+ return IDBKeyRange.only(value);+}+function _idbInRange(key, range) {+ if (!range) return true;+ const r = _idbSlot(range);+ const low = r.lower ? _idbCompare(key,r.lower) : 1;+ const high = r.upper ? _idbCompare(key,r.upper) : -1;+ return (low > 0 || low === 0 && !r.lowerOpen) && (high < 0 || high === 0 && !r.upperOpen);+}+// Keep platform payloads private, particularly non-extractable CryptoKey material.+const _idbPlatformCodecs = [{+ name:'Blob', test:value => value instanceof Blob,+ encode:value => ({bytes:value._bytes,type:value.type,file:value instanceof File,name:value.name,lastModified:value.lastModified}),+ decode:data => data.file ? new File([data.bytes],data.name,data) : new Blob([data.bytes],data),+}];+function _idbPrepare(value, seen, platform) {+ if (value === null || typeof value !== 'object') return value;+ if (seen.has(value)) return seen.get(value);+ if (__obscuraCore.isProxy(value)) throw _idbError('DataCloneError');+ for (const codec of _idbPlatformCodecs) {+ if (!codec.test(value)) continue;+ const marker = {};+ seen.set(value,marker);+ platform.push([marker,codec.name,codec.encode(value)]);+ return marker;+ }+ if (value instanceof Node || typeof WeakRef === 'function' && value instanceof WeakRef) throw _idbError('DataCloneError');+ if (__obscuraCore.isAnyArrayBuffer(value) || __obscuraCore.isArrayBufferView(value)+ || __obscuraCore.isDate(value) || __obscuraCore.isRegExp(value) || __obscuraCore.isBoxedPrimitive(value)+ || __obscuraCore.isPromise(value) || __obscuraCore.isWeakMap(value) || __obscuraCore.isWeakSet(value)+ || __obscuraCore.isModuleNamespaceObject(value)) return value;+ let copy;+ if (__obscuraCore.isMap(value)) {+ copy = new Map(); seen.set(value,copy);+ Map.prototype.forEach.call(value,(v,k) => copy.set(_idbPrepare(k,seen,platform),_idbPrepare(v,seen,platform)));+ } else if (__obscuraCore.isSet(value)) {+ copy = new Set(); seen.set(value,copy);+ Set.prototype.forEach.call(value,v => copy.add(_idbPrepare(v,seen,platform)));+ } else if (__obscuraCore.isNativeError(value)) {+ const type = ['EvalError','RangeError','ReferenceError','SyntaxError','TypeError','URIError'].includes(value.name) ? globalThis[value.name] : Error;+ copy = new type(value.message); seen.set(value,copy);+ copy.stack = value.stack;+ if (Object.hasOwn(value,'cause')) copy.cause = _idbPrepare(value.cause,seen,platform);+ } else {+ copy = Array.isArray(value) ? new Array(value.length) : {}; seen.set(value,copy);+ for (const key of Object.keys(value)) Object.defineProperty(copy,key,{+ value:_idbPrepare(value[key],seen,platform),writable:true,enumerable:true,configurable:true,+ });+ }+ return copy;+}+function _idbRevive(value, replacements, seen = new Set()) {+ if (value === null || typeof value !== 'object') return value;+ if (replacements.has(value)) return replacements.get(value);+ if (seen.has(value)) return value;+ seen.add(value);+ if (__obscuraCore.isMap(value)) {+ const entries = Array.from(value); value.clear();+ for (const [k,v] of entries) value.set(_idbRevive(k,replacements,seen),_idbRevive(v,replacements,seen));+ } else if (__obscuraCore.isSet(value)) {+ const entries = Array.from(value); value.clear();+ for (const v of entries) value.add(_idbRevive(v,replacements,seen));+ } else {+ for (const key of Object.keys(value)) value[key] = _idbRevive(value[key],replacements,seen);+ if (__obscuraCore.isNativeError(value) && Object.hasOwn(value,'cause')) value.cause = _idbRevive(value.cause,replacements,seen);+ }+ return value;+}+function _idbSerialize(value) {+ try {+ const platform = [];+ const prepared = _idbPrepare(value,new Map(),platform);+ const bytes = __obscuraCore.serialize({value:prepared,platform}, {forStorage:true}, () => {throw _idbError('DataCloneError');});+ return btoa(_bytesToBinaryString(bytes));+ } catch (_) { throw _idbError('DataCloneError'); }+}+function _idbDeserialize(value) {+ const decoded = __obscuraCore.deserialize(_base64ToUint8Array(value), {forStorage:true});+ if (!decoded.platform.length) return decoded.value;+ const replacements = new Map(decoded.platform.map(([marker,name,data]) =>+ [marker,_idbPlatformCodecs.find(codec => codec.name === name).decode(data)]));+ return _idbRevive(decoded.value,replacements);+}+function _idbPath(value, path) {+ if (Array.isArray(path)) {+ const result = path.map(p => _idbPath(value,p));+ return result.includes(undefined) ? undefined : result;+ }+ if (path === '') return value;+ for (const name of path.split('.')) {+ if (value == null || !(name in Object(value))) return undefined;+ value = value[name];+ }+ return value;+}+function _idbInject(value, path, key) {+ const names = path.split('.');+ for (const name of names.slice(0,-1)) {+ if (value === null || typeof value !== 'object') throw _idbError('DataError');+ if (!Object.hasOwn(value,name)) Object.defineProperty(value,name,{value:{},writable:true,enumerable:true,configurable:true});+ value = value[name];+ }+ if (value === null || typeof value !== 'object') throw _idbError('DataError');+ Object.defineProperty(value,names.at(-1),{value:key,writable:true,enumerable:true,configurable:true});+}+function _idbValidatePath(path) {+ if (Array.isArray(path)) {+ if (!path.length) throw _idbError('SyntaxError');+ return path.map(_idbValidatePath);+ }+ path = String(path);+ if (path && !path.split('.').every(name => /^[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u.test(name))) throw _idbError('SyntaxError');+ return path;+}++function _idbActive(state) {+ return state.state === 'active' && state.task === __obscuraCore.ops.op_indexed_db_task();+}+class IDBTransaction {+ constructor(token, db, names, mode, id = null, schema = null) {+ const d = _idbSlot(db);+ _idbInitialize(this,token,{db, names, mode, error:null, state:'active', task:__obscuraCore.ops.op_indexed_db_task(), started:!!schema, schema,+ requests:[], stores:new Map(), scheduled:false, autoCommit:false, committing:false,+ id:id ?? _idbOp('begin',{name:d.name,connection:d.connection,stores:names,mode})});+ d.transactions.add(this);+ _idbTask(() => { const s = _idbSlot(this); s.autoCommit = true; _idbRun(this); });+ }+ get db() { return _idbSlot(this).db; }+ get mode() { return _idbSlot(this).mode; }+ get error() { return _idbSlot(this).error; }+ get durability() { return 'default'; }+ get objectStoreNames() { const s = _idbSlot(this); return _idbNames(() => s.mode === 'versionchange' ? s.schema.map(x => x.name) : s.names); }+ objectStore(name) {+ const s = _idbSlot(this); name = String(name);+ if (s.state === 'finished') throw _idbError('InvalidStateError');+ const schemas = s.schema || _idbSlot(s.db).schema;+ if (!(s.mode === 'versionchange' || s.names.includes(name)) || !schemas.some(x => x.name === name)) throw _idbError('NotFoundError');+ if (!s.stores.has(name)) s.stores.set(name, new IDBObjectStore(_idbToken,this,name));+ return s.stores.get(name);+ }+ abort() { const s = _idbSlot(this); if (s.state === 'finished' || s.committing) throw _idbError('InvalidStateError'); _idbAbort(this,null); }+ commit() {+ const s = _idbSlot(this);+ if (!_idbActive(s) || s.committing) throw _idbError('InvalidStateError');+ s.committing = true; _idbSchedule(this);+ }+}+function _idbSchedule(tx) {+ const s = _idbSlot(tx);+ if (!s.scheduled && s.state !== 'finished') { s.scheduled = true; _idbTask(() => {s.scheduled = false; _idbRun(tx);}); }+}+function _idbRequestFor(source, operation) {+ const tx = source instanceof IDBTransaction ? source : _idbSlot(source).transaction;+ const s = _idbSlot(tx);+ if (!_idbActive(s) || s.committing) throw _idbError('TransactionInactiveError');+ const request = new IDBRequest(_idbToken,{source,transaction:tx});+ s.requests.push({request,operation});+ _idbSchedule(tx);+ return request;+}+function _idbRun(tx) {+ const s = _idbSlot(tx);+ if (s.state === 'finished') return;+ s.state = 'inactive';+ try {+ if (!s.started) {+ const info = _idbOp('ready',{id:s.id});+ if (!info) { setTimeout(() => _idbSchedule(tx), 1); return; }+ s.schema = info.schema;+ s.started = true;+ }+ const pending = s.requests.shift();+ if (pending) {+ s.task = __obscuraCore.ops.op_indexed_db_task();+ s.state = s.committing ? 'committing' : 'active';+ let result, error = null;+ try { result = pending.operation(); } catch (e) { error = e; }+ s.state = s.committing ? 'committing' : 'active';+ const event = _idbSettle(pending.request, result, error);+ if (s.state === 'finished') return;+ if (event.threw || error && !event.canceled) { _idbAbort(tx,error || _idbError('AbortError')); return; }+ // Promise reactions from a request are still in its active task.+ queueMicrotask(() => _idbSchedule(tx));+ return;+ }+ if (!s.autoCommit) return;+ _idbOp('commit',{id:s.id,schema:s.schema,version:_idbSlot(s.db).version});+ s.state = 'finished';+ const d = _idbSlot(s.db);+ d.schema = s.schema;+ d.transactions.delete(tx);+ if (d.upgrade === tx) d.upgrade = null;+ _idbDispatch(tx,'complete');+ if (s.onCommit) s.onCommit();+ if (d.closePending && !d.transactions.size) _idbClose(s.db);+ } catch (error) { _idbAbort(tx,error); }+}+function _idbAbort(tx, error) {+ const s = _idbSlot(tx);+ if (s.state === 'finished') return;+ s.state = 'finished'; s.error = error;+ _idbOp('abort',{id:s.id});+ const pending = s.requests.splice(0);+ const d = _idbSlot(s.db);+ d.transactions.delete(tx);+ if (d.upgrade === tx) { d.upgrade = null; d.schema = s.originalSchema || []; d.version = s.oldVersion; }+ _idbTask(() => {+ for (const entry of pending) _idbSettle(entry.request,undefined,_idbError('AbortError'));+ _idbDispatch(tx,'abort');+ if (s.onAbort) s.onAbort();+ if (d.closePending && !d.transactions.size) _idbClose(s.db);+ });+}+function _idbStoreSchema(store, write = false) {+ const h = _idbSlot(store), t = _idbSlot(h.transaction);+ if (!_idbActive(t) || t.committing) throw _idbError('TransactionInactiveError');+ const schema = (t.schema || _idbSlot(t.db).schema).find(x => x.name === h.name);+ if (!schema) throw _idbError('InvalidStateError');+ if (write && t.mode === 'readonly') throw _idbError('ReadOnlyError');+ return schema;+}+function _idbRecords(store, range = null) {+ const h = _idbSlot(store), t = _idbSlot(h.transaction);+ return _idbOp('entries',{id:t.id,store:h.name}).map(([key,value]) => [JSON.parse(key),value])+ .filter(([key]) => _idbInRange(key,range)).sort((a,b) => _idbCompare(a[0],b[0]));+}+class IDBObjectStore {+ constructor(token, transaction, name) {+ if (token !== _idbToken) throw new TypeError('Illegal constructor');+ _idbSlots.set(this,{transaction,name,indexes:new Map()});+ }+ get name() { return _idbSlot(this).name; }+ get transaction() { return _idbSlot(this).transaction; }+ get keyPath() { const t = _idbSlot(this.transaction); return (t.schema || _idbSlot(t.db).schema).find(s => s.name === this.name)?.keyPath; }+ get autoIncrement() { const t = _idbSlot(this.transaction); return !!(t.schema || _idbSlot(t.db).schema).find(s => s.name === this.name)?.autoIncrement; }+ get indexNames() { const t = _idbSlot(this.transaction); return _idbNames(() => ((t.schema || _idbSlot(t.db).schema).find(s => s.name === this.name)?.indexes || []).map(i => i.name)); }+ put(value, key) { return _idbWrite(this,value,key,false); }+ add(value, key) { return _idbWrite(this,value,key,true); }+ get(query) { return _idbRead(this,query,false,false,true); }+ getKey(query) { return _idbRead(this,query,true,false,true); }+ getAll(query, count) { return _idbRead(this,query,false,true,false,count); }+ getAllKeys(query, count) { return _idbRead(this,query,true,true,false,count); }+ count(query) {+ _idbStoreSchema(this);+ const range = _idbRange(query);+ return _idbRequestFor(this,() => _idbRecords(this,range).length);+ }+ delete(query) {+ _idbStoreSchema(this,true);+ const range = _idbRange(query,true);+ return _idbRequestFor(this,() => {+ const t = _idbSlot(this.transaction);+ for (const [key] of _idbRecords(this,range)) _idbOp('remove',{id:t.id,store:this.name,key:JSON.stringify(key)});+ });+ }+ clear() {+ _idbStoreSchema(this,true);+ return _idbRequestFor(this,() => { _idbOp('clear',{id:_idbSlot(this.transaction).id,store:this.name}); });+ }+ index(name) {+ const schema = _idbStoreSchema(this), h = _idbSlot(this); name = String(name);+ if (!schema.indexes.some(i => i.name === name)) throw _idbError('NotFoundError');+ if (!h.indexes.has(name)) h.indexes.set(name,new IDBIndex(_idbToken,this,name));+ return h.indexes.get(name);+ }+ createIndex(name, keyPath, options = {}) {+ const schema = _idbStoreSchema(this,true); name = String(name);+ if (this.transaction.mode !== 'versionchange') throw _idbError('InvalidStateError');+ if (schema.indexes.some(i => i.name === name)) throw _idbError('ConstraintError');+ keyPath = _idbValidatePath(keyPath);+ if (options.multiEntry && Array.isArray(keyPath)) throw _idbError('InvalidAccessError');+ schema.indexes.push({name,keyPath,unique:!!options.unique,multiEntry:!!options.multiEntry});+ const index = this.index(name);+ _idbRequestFor(this,() => { _idbIndexRows(index,null,true); });+ return index;+ }+ deleteIndex(name) {+ const schema = _idbStoreSchema(this,true); name = String(name);+ if (this.transaction.mode !== 'versionchange') throw _idbError('InvalidStateError');+ const at = schema.indexes.findIndex(i => i.name === name);+ if (at < 0) throw _idbError('NotFoundError');+ schema.indexes.splice(at,1);+ }+ openCursor(query, direction = 'next') { return _idbCursor(this,query,direction,false); }+ openKeyCursor(query, direction = 'next') { return _idbCursor(this,query,direction,true); }+}+function _idbWrite(store, value, key, add) {+ const schema = _idbStoreSchema(store,true);+ const serialized = _idbSerialize(value);+ const clone = _idbDeserialize(serialized);+ if (schema.keyPath !== null) {+ if (key !== undefined) throw _idbError('DataError');+ key = _idbPath(clone,schema.keyPath);+ if (key === undefined && !schema.autoIncrement) throw _idbError('DataError');+ }+ let encoded = key === undefined ? null : _idbKey(key);+ if (!encoded && !schema.autoIncrement) throw _idbError('DataError');+ return _idbRequestFor(store,() => {+ const t = _idbSlot(store.transaction), live = t.schema.find(x => x.name === store.name);+ let payload = serialized;+ let nextKey = live.nextKey;+ if (!encoded) {+ if (live.nextKey > Number.MAX_SAFE_INTEGER) throw _idbError('ConstraintError');+ key = live.nextKey; nextKey++; encoded = _idbKey(key);+ if (live.keyPath !== null) { _idbInject(clone,live.keyPath,key); payload = _idbSerialize(clone); }+ } else if (live.autoIncrement && encoded[0] === 0 && Number(encoded[1]) >= live.nextKey) {+ nextKey = Math.floor(Number(encoded[1])) + 1;+ }+ const rawKey = JSON.stringify(encoded);+ if (add && _idbOp('get',{id:t.id,store:store.name,key:rawKey}) !== null) throw _idbError('ConstraintError');+ for (const index of live.indexes.filter(i => i.unique)) {+ const wanted = _idbIndexKeys(index,clone);+ if (!wanted.length) continue;+ for (const [other, data] of _idbRecords(store)) {+ if (_idbCompare(other,encoded) === 0) continue;+ if (_idbIndexKeys(index,_idbDeserialize(data)).some(k => wanted.some(w => _idbCompare(k,w) === 0))) throw _idbError('ConstraintError');+ }+ }+ _idbOp('put',{id:t.id,store:store.name,key:rawKey,value:payload});+ live.nextKey = nextKey;+ return _idbKeyValue(encoded);+ });+}+function _idbCountLimit(count) {+ if (count === undefined) return Infinity;+ count = Number(count);+ if (!Number.isFinite(count) || count < 0 || count > 0xffffffff) throw new TypeError('Invalid count');+ return Math.trunc(count) || Infinity;+}+function _idbRead(source, query, keys, all, required, count) {+ const store = source instanceof IDBIndex ? source.objectStore : source;+ _idbStoreSchema(store);+ const range = _idbRange(query,required), limit = _idbCountLimit(count);+ return _idbRequestFor(source,() => {+ let records;+ if (source instanceof IDBIndex) records = _idbIndexRows(source,range).map(row => [row[1],row[2]]);+ else if (range && _idbSlot(range).lower && _idbSlot(range).upper+ && _idbCompare(_idbSlot(range).lower,_idbSlot(range).upper) === 0) {+ const key = _idbSlot(range).lower;+ const value = _idbOp('get',{id:_idbSlot(store.transaction).id,store:store.name,key:JSON.stringify(key)});+ records = value === null ? [] : [[key,value]];+ } else records = _idbRecords(store,range);+ const values = records.slice(0,all ? limit : 1).map(([key,value]) => keys ? _idbKeyValue(key) : _idbDeserialize(value));+ return all ? values : values[0];+ });+}+function _idbIndexSchema(index) {+ const store = _idbSlot(index.objectStore), tx = _idbSlot(store.transaction);+ const schema = (tx.schema || _idbSlot(tx.db).schema).find(s => s.name === store.name);+ const definition = schema?.indexes.find(i => i.name === _idbSlot(index).name);+ if (!definition) throw _idbError('InvalidStateError');+ return definition;+}+function _idbIndexKeys(definition, value) {+ const key = _idbPath(value,definition.keyPath);+ const values = definition.multiEntry && Array.isArray(key) ? key : [key];+ const result = [];+ for (const value of values) {+ try { const encoded = _idbKey(value); if (!result.some(k => !_idbCompare(k,encoded))) result.push(encoded); } catch (_) {}+ }+ return result;+}+function _idbIndexRows(index, range, validate = false) {+ const definition = _idbIndexSchema(index), rows = [];+ for (const [primary,value] of _idbRecords(index.objectStore)) {+ for (const key of _idbIndexKeys(definition,_idbDeserialize(value))) if (_idbInRange(key,range)) rows.push([key,primary,value]);+ }+ rows.sort((a,b) => _idbCompare(a[0],b[0]) || _idbCompare(a[1],b[1]));+ if (validate && definition.unique && rows.some((r,i) => i && _idbCompare(rows[i-1][0],r[0]) === 0)) throw _idbError('ConstraintError');+ return rows;+}+class IDBIndex {+ constructor(token, objectStore, name) {+ if (token !== _idbToken) throw new TypeError('Illegal constructor');+ _idbSlots.set(this,{objectStore,name,transaction:objectStore.transaction});+ }+ get name() { return _idbSlot(this).name; }+ get objectStore() { return _idbSlot(this).objectStore; }+ get keyPath() { return _idbIndexSchema(this).keyPath; }+ get unique() { return _idbIndexSchema(this).unique; }+ get multiEntry() { return _idbIndexSchema(this).multiEntry; }+ get(query) { return _idbRead(this,query,false,false,true); }+ getKey(query) { return _idbRead(this,query,true,false,true); }+ getAll(query, count) { return _idbRead(this,query,false,true,false,count); }+ getAllKeys(query, count) { return _idbRead(this,query,true,true,false,count); }+ count(query) { _idbIndexSchema(this); const range = _idbRange(query); return _idbRequestFor(this,() => _idbIndexRows(this,range).length); }+ openCursor(query, direction = 'next') { return _idbCursor(this,query,direction,false); }+ openKeyCursor(query, direction = 'next') { return _idbCursor(this,query,direction,true); }+}+class IDBCursor {+ constructor(token, state) { if (token !== _idbToken) throw new TypeError('Illegal constructor'); _idbSlots.set(this,state); }+ get source() { return _idbSlot(this).source; }+ get direction() { return _idbSlot(this).direction; }+ get key() { return _idbKeyValue(_idbSlot(this).row[0]); }+ get primaryKey() { return _idbKeyValue(_idbSlot(this).row[1]); }+ get request() { return _idbSlot(this).request; }+ continue(key) { _idbContinue(this,key); }+ advance(count) {+ count = Number(count);+ if (!Number.isInteger(count) || count <= 0 || count > 0xffffffff) throw new TypeError('Invalid count');+ _idbContinue(this,undefined,count);+ }+ update(value) {+ const s = _idbSlot(this);+ if (!s.positioned || s.keysOnly) throw _idbError('InvalidStateError');+ const store = s.source instanceof IDBIndex ? s.source.objectStore : s.source;+ if (store.keyPath !== null) {+ const key = _idbPath(value,store.keyPath);+ if (key === undefined || _idbCompare(_idbKey(key),s.row[1])) throw _idbError('DataError');+ return store.put(value);+ }+ return store.put(value,this.primaryKey);+ }+ delete() {+ const s = _idbSlot(this);+ if (!s.positioned || s.keysOnly) throw _idbError('InvalidStateError');+ return (s.source instanceof IDBIndex ? s.source.objectStore : s.source).delete(this.primaryKey);+ }+}+class IDBCursorWithValue extends IDBCursor {+ get value() { return _idbSlot(this).value; }+}+function _idbCursor(source, query, direction, keysOnly) {+ const store = source instanceof IDBIndex ? source.objectStore : source;+ _idbStoreSchema(store);+ direction = String(direction);+ if (!['next','nextunique','prev','prevunique'].includes(direction)) throw new TypeError('Invalid cursor direction');+ const state = {source,range:_idbRange(query),direction,keysOnly,positioned:false,row:null,value:undefined,request:null};+ const cursor = new (keysOnly ? IDBCursor : IDBCursorWithValue)(_idbToken,state);+ const request = _idbRequestFor(source,() => _idbCursorNext(cursor,undefined,1));+ state.request = request;+ return request;+}+function _idbCursorNext(cursor, sought, count) {+ const s = _idbSlot(cursor), reverse = s.direction.startsWith('prev');+ let rows = s.source instanceof IDBIndex ? _idbIndexRows(s.source,s.range)+ : _idbRecords(s.source,s.range).map(([key,value]) => [key,key,value]);+ if (reverse) rows.reverse();+ if (s.direction.endsWith('unique')) rows = rows.filter((row,i) => !i || _idbCompare(row[0],rows[i-1][0]));+ rows = rows.filter(row => {+ if (s.row) {+ const cmp = _idbCompare(row[0],s.row[0]) || (s.direction.endsWith('unique') ? 0 : _idbCompare(row[1],s.row[1]));+ if (reverse ? cmp >= 0 : cmp <= 0) return false;+ }+ return !sought || (reverse ? _idbCompare(row[0],sought) <= 0 : _idbCompare(row[0],sought) >= 0);+ });+ const next = rows[count-1];+ s.positioned = !!next;+ if (!next) return null;+ s.row = next;+ if (!s.keysOnly) s.value = _idbDeserialize(next[2]);+ return cursor;+}+function _idbContinue(cursor, key, count = 1) {+ const s = _idbSlot(cursor), tx = _idbSlot(_idbSlot(s.request).transaction);+ if (!_idbActive(tx) || tx.committing) throw _idbError('TransactionInactiveError');+ if (!s.positioned) throw _idbError('InvalidStateError');+ const sought = key === undefined ? null : _idbKey(key);+ if (sought) {+ const cmp = _idbCompare(sought,s.row[0]);+ if (s.direction.startsWith('prev') ? cmp >= 0 : cmp <= 0) throw _idbError('DataError');+ }+ s.positioned = false;+ Object.assign(_idbSlot(s.request),{readyState:'pending',result:undefined,error:null});+ tx.requests.push({request:s.request,operation:() => _idbCursorNext(cursor,sought,count)});+ _idbSchedule(_idbSlot(s.request).transaction);+}++class IDBDatabase {+ constructor(token, name, version, schema, connection) {+ _idbInitialize(this,token,{name,version,schema,connection,transactions:new Set(),upgrade:null,closePending:false,closed:false});+ if (connection) _idbConnections.set(connection,this);+ }+ get name() { return _idbSlot(this).name; }+ get version() { return _idbSlot(this).version; }+ get objectStoreNames() { return _idbNames(() => (_idbSlot(this).upgrade ? _idbSlot(_idbSlot(this).upgrade).schema : _idbSlot(this).schema).map(s => s.name)); }+ createObjectStore(name, options = {}) {+ const d = _idbSlot(this); name = String(name);+ if (!d.upgrade) throw _idbError('InvalidStateError');+ const t = _idbSlot(d.upgrade);+ if (!_idbActive(t)) throw _idbError('TransactionInactiveError');+ if (t.schema.some(s => s.name === name)) throw _idbError('ConstraintError');+ const keyPath = options.keyPath == null ? null : _idbValidatePath(options.keyPath);+ if (options.autoIncrement && (keyPath === '' || Array.isArray(keyPath))) throw _idbError('InvalidAccessError');+ t.schema.push({name,keyPath,autoIncrement:!!options.autoIncrement,nextKey:1,indexes:[]});+ return d.upgrade.objectStore(name);+ }+ deleteObjectStore(name) {+ const d = _idbSlot(this); name = String(name);+ if (!d.upgrade) throw _idbError('InvalidStateError');+ const t = _idbSlot(d.upgrade);+ if (!_idbActive(t)) throw _idbError('TransactionInactiveError');+ const at = t.schema.findIndex(s => s.name === name);+ if (at < 0) throw _idbError('NotFoundError');+ _idbOp('clear',{id:t.id,store:name});+ t.schema.splice(at,1); t.stores.delete(name);+ }+ transaction(storeNames, mode = 'readonly', options = {}) {+ const d = _idbSlot(this);+ if (d.closed || d.closePending || d.upgrade) throw _idbError('InvalidStateError');+ mode = String(mode);+ if (mode !== 'readonly' && mode !== 'readwrite') throw new TypeError('Invalid transaction mode');+ if (options.durability !== undefined && !['default','strict','relaxed'].includes(options.durability)) throw new TypeError('Invalid durability');+ const names = [...new Set(typeof storeNames === 'string' ? [storeNames] : Array.from(storeNames,String))].sort();+ if (!names.length) throw _idbError('InvalidAccessError');+ for (const name of names) if (!d.schema.some(s => s.name === name)) throw _idbError('NotFoundError');+ return new IDBTransaction(_idbToken,this,names,mode);+ }+ close() { const d = _idbSlot(this); d.closePending = true; if (!d.transactions.size) _idbClose(this); }+}+function _idbClose(db) {+ const d = _idbSlot(db);+ if (d.closed) return;+ if (d.connection) _idbOp('close',{name:d.name,connection:d.connection});+ _idbConnections.delete(d.connection);+ d.closed = true;+}+function _idbPollNotices(notices = _idbOp('notices',{})) {+ for (const notice of notices) {+ const db = _idbConnections.get(notice.connection);+ if (db && !_idbSlot(db).closePending) _idbDispatch(db,'versionchange',{oldVersion:db.version,newVersion:notice.version});+ }+}+function _idbOpen(name, requestedVersion, deleting) {+ if (!__obscuraCore.ops.op_storage_access()) throw _idbError('SecurityError');+ const request = new IDBOpenDBRequest(_idbToken);+ let queue = _idbOpenQueues.get(name);+ if (!queue) _idbOpenQueues.set(name,queue = []);+ let blocked = false, notified = false, id = null, opening = null;+ const finish = () => {+ if (opening !== null) _idbOp('release_open',{name,opening});+ queue.shift(); if (queue.length) _idbTask(queue[0]); else _idbOpenQueues.delete(name);+ };+ const attempt = () => {+ try {+ if (opening === null) opening = _idbOp('reserve_open',{name});+ if (!_idbOp('open_ready',{name,opening})) { setTimeout(attempt,1); return; }+ const info = _idbOp('info',{name}), version = deleting ? null : requestedVersion ?? (info.version || 1);+ if (!deleting && version < info.version) throw _idbError('VersionError');+ if (deleting || version > info.version) {+ if (!notified) {+ notified = true;+ _idbOp('notify',{name,version});+ _idbPollNotices();+ }+ if (_idbOp('info',{name}).connections) {+ if (!blocked) { blocked = true; _idbDispatch(request,'blocked',{oldVersion:info.version,newVersion:version}); }+ setTimeout(attempt,5); return;+ }+ }+ if (id === null) id = _idbOp('begin',{name,mode:'versionchange',stores:[]});+ const live = _idbOp('ready',{id});+ if (!live) { setTimeout(attempt,1); return; }+ if (deleting) {+ _idbOp('abort',{id}); id = null;+ if (!_idbOp('delete',{name})) { setTimeout(attempt,1); return; }+ _idbSettle(request,undefined); finish(); return;+ }+ if (version < live.version) throw _idbError('VersionError');+ const db = new IDBDatabase(_idbToken,name,version,live.schema,0);+ const succeed = () => {+ const d = _idbSlot(db);+ d.connection = _idbOp('connect',{name}); _idbConnections.set(d.connection,db);+ _idbSlot(request).transaction = null;+ _idbSettle(request,db); finish();+ };+ if (version > live.version) {+ const tx = new IDBTransaction(_idbToken,db,live.schema.map(s => s.name),'versionchange',id,live.schema);+ const t = _idbSlot(tx), d = _idbSlot(db);+ t.originalSchema = __obscuraCore.deserialize(__obscuraCore.serialize(live.schema));+ t.oldVersion = live.version;+ d.upgrade = tx;+ Object.assign(_idbSlot(request),{result:db,readyState:'done',transaction:tx});+ t.onCommit = succeed;+ t.onAbort = () => {d.closed = true; _idbSlot(request).transaction = null; _idbSettle(request,undefined,_idbError('AbortError')); finish();};+ const outcome = _idbDispatch(request,'upgradeneeded',{oldVersion:live.version,newVersion:version});+ if (outcome.threw) _idbAbort(tx,_idbError('AbortError'));+ } else {+ _idbOp('abort',{id}); succeed();+ }+ } catch (error) {+ if (id !== null) { try { _idbOp('abort',{id}); } catch (_) {} }+ _idbSettle(request,undefined,error); finish();+ }+ };+ queue.push(attempt);+ if (queue.length === 1) _idbTask(attempt);+ return request;+}+class IDBFactory {+ constructor(token) { if (token !== _idbToken) throw new TypeError('Illegal constructor'); }+ open(name, version) {+ if (!arguments.length) throw new TypeError('Database name required');+ if (version !== undefined) {+ version = Number(version);+ if (!Number.isFinite(version) || version < 1 || version > Number.MAX_SAFE_INTEGER) throw new TypeError('Invalid version');+ version = Math.floor(version);+ }+ return _idbOpen(String(name),version,false);+ }+ deleteDatabase(name) { if (!arguments.length) throw new TypeError('Database name required'); return _idbOpen(String(name),null,true); }+ databases() {+ try { return Promise.resolve(_idbOp('databases',{})); } catch (error) { return Promise.reject(error); }+ }+ cmp(a,b) { return _idbCompare(_idbKey(a),_idbKey(b)); }+}+for (const [klass, events] of [[IDBRequest,['success','error']], [IDBOpenDBRequest,['blocked','upgradeneeded']],+ [IDBTransaction,['complete','abort','error']], [IDBDatabase,['versionchange','close','error','abort']]]) {+ for (const type of events) Object.defineProperty(klass.prototype,'on'+type,{+ get(){return _idbSlot(this).handlers[type] || null;},+ set(value){+ const slot = _idbSlot(this);+ slot.handlers[type] = typeof value === 'function' ? value : null;+ if (!slot.handlers[type]) {+ if (slot.handlerListeners[type]) _eventTargetRemove(this,type,slot.handlerListeners[type],false);+ delete slot.handlerListeners[type];+ } else if (!slot.handlerListeners[type]) {+ const callback = event => {if (slot.handlers[type]?.call(this,event) === false) event.preventDefault();};+ slot.handlerListeners[type] = callback;+ _eventTargetAdd(this,type,callback,false);+ }+ },+ configurable:true,enumerable:true,+ });+}+for (const klass of [IDBRequest,IDBTransaction,IDBDatabase]) {+ Object.setPrototypeOf(klass.prototype,EventTarget.prototype);+ Object.setPrototypeOf(klass,EventTarget);+}+for (const klass of [IDBFactory,IDBRequest,IDBOpenDBRequest,IDBTransaction,IDBDatabase,+ IDBObjectStore,IDBIndex,IDBCursor,IDBCursorWithValue,IDBKeyRange,IDBVersionChangeEvent]) {+ Object.defineProperty(klass.prototype,Symbol.toStringTag,{value:klass.name,configurable:true});+ _markNative(klass);+ for (const name of Object.getOwnPropertyNames(klass.prototype)) {+ if (name === 'constructor') continue;+ const descriptor = Object.getOwnPropertyDescriptor(klass.prototype,name);+ _markNative(descriptor.value); _markNative(descriptor.get); _markNative(descriptor.set);+ Object.defineProperty(klass.prototype,name,{...descriptor,enumerable:true});+ }+ Object.defineProperty(globalThis,klass.name,{value:klass,writable:true,configurable:true,enumerable:false});+}+const _idbFactory = new IDBFactory(_idbToken);+Object.defineProperty(globalThis,'indexedDB',{get(){+ if (!__obscuraCore.ops.op_storage_access()) throw _idbError('SecurityError');+ return _idbFactory;+},configurable:true,enumerable:true});+Object.defineProperty(globalThis,'__obscura_poll_indexeddb',{+ value:notices => _idbTask(() => _idbPollNotices(notices)),configurable:true,+});diff --git a/crates/obscura-js/src/indexed_db.rs b/crates/obscura-js/src/indexed_db.rsnew file mode 100644index 00000000..a52a761f--- /dev/null+++ b/crates/obscura-js/src/indexed_db.rs@@ -0,0 +1,364 @@+//! Context-owned IndexedDB records. Transactions stage deltas, not copies of a database.+use std::collections::{HashMap, HashSet, VecDeque};+use std::sync::{Arc, Mutex};+use serde_json::{json, Value};++const MAX_BYTES: usize = 64 * 1024 * 1024;+const MAX_HANDLES: usize = 1024;+const RECORD_OVERHEAD: usize = 96;+type DatabaseKey = (String, String);++#[derive(Default)]+struct Database {+ version: u64,+ schema: Vec<Value>,+ records: HashMap<String, HashMap<String, String>>,+ connections: HashMap<u64, u64>,+ queue: VecDeque<u64>,+ openings: VecDeque<(u64, u64)>,+ schema_bytes: usize,+}++struct Transaction {+ owner: u64,+ database: DatabaseKey,+ mode: String,+ scope: HashSet<String>,+ cleared: HashSet<String>,+ writes: HashMap<(String, String), Option<String>>,+ pending_bytes: usize,+}++#[derive(Default)]+struct Inner {+ next: u64,+ bytes: usize,+ pending_bytes: usize,+ databases: HashMap<DatabaseKey, Database>,+ transactions: HashMap<u64, Transaction>,+ notices: HashMap<u64, Vec<Value>>,+}++#[derive(Default)]+pub struct IndexedDbStorage {+ inner: Mutex<Inner>,+ pending_notices: std::sync::atomic::AtomicBool,+}++impl IndexedDbStorage {+ pub fn has_pending_notifications(&self) -> bool {+ self.pending_notices.load(std::sync::atomic::Ordering::Acquire)+ }+}++pub(crate) struct IndexedDbOwner {+ pub(crate) storage: Arc<IndexedDbStorage>,+ id: u64,+}++impl IndexedDbOwner {+ pub(crate) fn new(storage: Arc<IndexedDbStorage>) -> Self {+ let id = {+ let mut inner = storage.inner.lock().unwrap_or_else(|e| e.into_inner());+ inner.next += 1;+ inner.next+ };+ Self { storage, id }+ }++ pub(crate) fn command(&self, origin: &str, action: &str, data: Value) -> Value {+ let mut inner = self.storage.inner.lock().unwrap_or_else(|e| e.into_inner());+ let result = inner.command(self.id, origin, action, data);+ self.storage.pending_notices.store(!inner.notices.is_empty(), std::sync::atomic::Ordering::Release);+ match result {+ Ok(value) => value,+ Err(name) => json!({"error":name}),+ }+ }++ pub(crate) fn take_notices(&self) -> Vec<Value> {+ let mut inner = self.storage.inner.lock().unwrap_or_else(|e| e.into_inner());+ let notices = inner.notices.remove(&self.id).unwrap_or_default();+ self.storage.pending_notices.store(!inner.notices.is_empty(), std::sync::atomic::Ordering::Release);+ notices+ }+}++impl Drop for IndexedDbOwner {+ fn drop(&mut self) {+ let mut inner = self.storage.inner.lock().unwrap_or_else(|e| e.into_inner());+ let ids: HashSet<u64> = inner.transactions.iter()+ .filter_map(|(id, tx)| (tx.owner == self.id).then_some(*id)).collect();+ let released = inner.transactions.values().filter(|tx| tx.owner == self.id).map(|tx| tx.pending_bytes).sum::<usize>();+ inner.pending_bytes = inner.pending_bytes.saturating_sub(released);+ inner.transactions.retain(|id, _| !ids.contains(id));+ for db in inner.databases.values_mut() {+ db.connections.retain(|_, owner| *owner != self.id);+ db.queue.retain(|id| !ids.contains(id));+ db.openings.retain(|(_, owner)| *owner != self.id);+ }+ inner.notices.remove(&self.id);+ self.storage.pending_notices.store(!inner.notices.is_empty(), std::sync::atomic::Ordering::Release);+ }+}++fn text<'a>(data: &'a Value, key: &str) -> Result<&'a str, &'static str> {+ data.get(key).and_then(Value::as_str).ok_or("DataError")+}++impl Inner {+ fn command(&mut self, owner: u64, origin: &str, action: &str, data: Value) -> Result<Value, &'static str> {+ if origin == "null" { return Err("SecurityError"); }+ if action == "databases" {+ return Ok(Value::Array(self.databases.iter().filter_map(|((o, name), db)|+ (o == origin && db.version > 0).then(|| json!({"name":name,"version":db.version}))).collect()));+ }+ if matches!(action, "info" | "connect" | "close" | "notify" | "delete" | "begin"+ | "reserve_open" | "open_ready" | "release_open") {+ let name = text(&data, "name")?;+ if name.len() > 16 * 1024 || self.databases.len() >= MAX_HANDLES+ && !self.databases.contains_key(&(origin.into(), name.into())) { return Err("QuotaExceededError"); }+ let key = (origin.to_string(), name.to_string());+ if action == "delete" {+ let Some(db) = self.databases.get(&key) else { return Ok(json!(true)); };+ if !db.connections.is_empty() || !db.queue.is_empty() { return Ok(json!(false)); }+ if let Some(db) = self.databases.get_mut(&key) {+ self.bytes = self.bytes.saturating_sub(db.schema_bytes);+ for store in db.records.values() {+ for (k, v) in store { self.bytes = self.bytes.saturating_sub(k.len() + v.len() + RECORD_OVERHEAD); }+ }+ db.records.clear(); db.schema.clear(); db.schema_bytes = 0; db.version = 0;+ }+ return Ok(json!(true));+ }+ let db = self.databases.entry(key.clone()).or_default();+ match action {+ "reserve_open" => {+ if db.openings.len() >= MAX_HANDLES { return Err("QuotaExceededError"); }+ self.next += 1;+ db.openings.push_back((self.next, owner));+ return Ok(json!(self.next));+ }+ "open_ready" | "release_open" => {+ let id = data["opening"].as_u64().ok_or("DataError")?;+ if action == "open_ready" { return Ok(json!(db.openings.front() == Some(&(id, owner)))); }+ db.openings.retain(|entry| *entry != (id, owner));+ if db.openings.is_empty() && db.version == 0 && db.connections.is_empty() && db.queue.is_empty() {+ self.databases.remove(&key);+ }+ return Ok(Value::Null);+ }+ "info" => return Ok(json!({"version":db.version,"schema":db.schema,"connections":db.connections.len()})),+ "connect" => {+ if db.connections.len() >= MAX_HANDLES { return Err("QuotaExceededError"); }+ self.next += 1;+ db.connections.insert(self.next, owner);+ return Ok(json!(self.next));+ }+ "close" => {+ let id = data["connection"].as_u64().ok_or("DataError")?;+ if db.connections.get(&id) == Some(&owner) { db.connections.remove(&id); }+ return Ok(Value::Null);+ }+ "notify" => {+ for (&id, &other) in &db.connections {+ let notice = json!({"connection":id,"version":data["version"]});+ let pending = self.notices.entry(other).or_default();+ if !pending.contains(¬ice) && pending.len() < MAX_HANDLES { pending.push(notice); }+ }+ return Ok(Value::Null);+ }+ "begin" => {+ if self.transactions.len() >= MAX_HANDLES { return Err("QuotaExceededError"); }+ let mode = text(&data, "mode")?.to_string();+ if !matches!(mode.as_str(), "readonly" | "readwrite" | "versionchange") { return Err("TypeError"); }+ if mode != "versionchange" {+ let connection = data["connection"].as_u64().ok_or("InvalidStateError")?;+ if db.connections.get(&connection) != Some(&owner) { return Err("InvalidStateError"); }+ }+ let scope = data["stores"].as_array().ok_or("DataError")?.iter()+ .map(|s| s.as_str().map(str::to_string).ok_or("DataError"))+ .collect::<Result<HashSet<_>, _>>()?;+ self.next += 1;+ let id = self.next;+ db.queue.push_back(id);+ self.transactions.insert(id, Transaction { owner, database:key, mode, scope,+ cleared:HashSet::new(), writes:HashMap::new(), pending_bytes:0 });+ return Ok(json!(id));+ }+ _ => unreachable!(),+ }+ }+ let id = data["id"].as_u64().ok_or("TransactionInactiveError")?;+ let tx = self.transactions.get(&id).ok_or("TransactionInactiveError")?;+ if tx.owner != owner || tx.database.0 != origin { return Err("InvalidStateError"); }+ let db = self.databases.get(&tx.database).ok_or("InvalidStateError")?;+ if action == "abort" {+ let key = tx.database.clone();+ self.pending_bytes = self.pending_bytes.saturating_sub(tx.pending_bytes);+ self.transactions.remove(&id);+ if let Some(db) = self.databases.get_mut(&key) { db.queue.retain(|queued| *queued != id); }+ return Ok(Value::Null);+ }+ if action == "ready" {+ return Ok(if db.queue.front() == Some(&id) {+ json!({"version":db.version,"schema":db.schema})+ } else { Value::Null });+ }+ if db.queue.front() != Some(&id) { return Err("TransactionInactiveError"); }+ if action == "commit" {+ let schema = data["schema"].as_array().ok_or("DataError")?.clone();+ let version = if tx.mode == "versionchange" { Some(data["version"].as_u64().filter(|v| *v > 0).ok_or("DataError")?) }+ else { None };+ if schema.len() > MAX_HANDLES { return Err("QuotaExceededError"); }+ let names: HashSet<String> = schema.iter()+ .map(|s| text(s, "name").map(str::to_string)).collect::<Result<_, _>>()?;+ let schema_bytes = serde_json::to_vec(&schema).map_err(|_| "DataError")?.len();+ let mut bytes = self.bytes.saturating_sub(db.schema_bytes).saturating_add(schema_bytes);+ for (name, records) in &db.records {+ if !names.contains(name) || tx.cleared.contains(name) {+ for (k, v) in records { bytes = bytes.saturating_sub(k.len() + v.len() + RECORD_OVERHEAD); }+ }+ }+ for ((store, key), value) in &tx.writes {+ if !names.contains(store) { continue; }+ if !tx.cleared.contains(store) {+ if let Some(old) = db.records.get(store).and_then(|s| s.get(key)) {+ bytes = bytes.saturating_sub(key.len() + old.len() + RECORD_OVERHEAD);+ }+ }+ if let Some(value) = value { bytes = bytes.saturating_add(key.len() + value.len() + RECORD_OVERHEAD); }+ }+ if bytes > MAX_BYTES { return Err("QuotaExceededError"); }+ let tx = self.transactions.remove(&id).ok_or("TransactionInactiveError")?;+ self.pending_bytes = self.pending_bytes.saturating_sub(tx.pending_bytes);+ let db = self.databases.get_mut(&tx.database).ok_or("InvalidStateError")?;+ db.records.retain(|name, _| names.contains(name) && !tx.cleared.contains(name));+ for ((store, key), value) in tx.writes {+ if !names.contains(&store) { continue; }+ let records = db.records.entry(store).or_default();+ if let Some(value) = value { records.insert(key, value); } else { records.remove(&key); }+ }+ db.schema = schema;+ db.schema_bytes = schema_bytes;+ if let Some(version) = version { db.version = version; }+ db.queue.pop_front();+ self.bytes = bytes;+ return Ok(Value::Null);+ }+ let store = text(&data, "store")?.to_string();+ if tx.mode != "versionchange" && !tx.scope.contains(&store) { return Err("NotFoundError"); }+ match action {+ "get" => {+ let key = text(&data, "key")?;+ let value = tx.writes.get(&(store.clone(), key.to_string())).cloned()+ .unwrap_or_else(|| if tx.cleared.contains(&store) { None }+ else { db.records.get(&store).and_then(|s| s.get(key)).cloned() });+ Ok(json!(value))+ }+ "entries" => {+ let mut records = if tx.cleared.contains(&store) { HashMap::new() }+ else { db.records.get(&store).cloned().unwrap_or_default() };+ for ((name, key), value) in &tx.writes {+ if name != &store { continue; }+ if let Some(value) = value { records.insert(key.clone(), value.clone()); }+ else { records.remove(key); }+ }+ Ok(json!(records.into_iter().collect::<Vec<_>>()))+ }+ "put" | "remove" | "clear" => {+ if tx.mode == "readonly" { return Err("ReadOnlyError"); }+ let tx = self.transactions.get_mut(&id).ok_or("TransactionInactiveError")?;+ if action == "clear" {+ tx.cleared.insert(store.clone());+ let released: usize = tx.writes.iter().filter(|((name, _), _)| name == &store)+ .map(|((name, key), value)| name.len() + key.len() + value.as_ref().map_or(0, String::len) + RECORD_OVERHEAD).sum();+ tx.pending_bytes = tx.pending_bytes.saturating_sub(released);+ self.pending_bytes = self.pending_bytes.saturating_sub(released);+ tx.writes.retain(|(name, _), _| name != &store);+ } else {+ let key = text(&data, "key")?.to_string();+ let value = if action == "put" { Some(text(&data, "value")?.to_string()) } else { None };+ if key.len() > 64 * 1024 || value.as_ref().is_some_and(|v| v.len() > 16 * 1024 * 1024) {+ return Err("QuotaExceededError");+ }+ let old = tx.writes.get(&(store.clone(), key.clone())).map_or(0, |old|+ store.len() + key.len() + old.as_ref().map_or(0, String::len) + RECORD_OVERHEAD);+ let added = store.len() + key.len() + value.as_ref().map_or(0, String::len) + RECORD_OVERHEAD;+ let total = self.pending_bytes.saturating_sub(old).saturating_add(added);+ if self.bytes.saturating_add(total) > MAX_BYTES { return Err("QuotaExceededError"); }+ let pending = tx.pending_bytes.saturating_sub(old).saturating_add(added);+ self.pending_bytes = total;+ tx.pending_bytes = pending;+ tx.writes.insert((store, key), value);+ }+ Ok(Value::Null)+ }+ _ => Err("NotSupportedError"),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ fn begin(owner: &IndexedDbOwner, name: &str, mode: &str) -> u64 {+ let connection = owner.command("https://idb.test", "connect", json!({"name":name}));+ let id = owner.command("https://idb.test", "begin",+ json!({"name":name,"mode":mode,"stores":["items"],"connection":connection})).as_u64().unwrap();+ assert!(!owner.command("https://idb.test", "ready", json!({"id":id})).is_null());+ id+ }+ #[test]+ fn pending_writes_share_one_context_memory_budget() {+ let store = Arc::new(IndexedDbStorage::default());+ let owner = IndexedDbOwner::new(store);+ let first = begin(&owner,"first","versionchange");+ let second = begin(&owner,"second","versionchange");+ let value = "x".repeat(8 * 1024 * 1024);+ let mut refused = false;+ for i in 0..9 {+ let result = owner.command("https://idb.test","put",+ json!({"id":if i < 4 {first} else {second},"store":"items","key":i.to_string(),"value":value}));+ refused |= result["error"] == "QuotaExceededError";+ }+ assert!(refused,"parallel databases must not multiply the context's pending-write budget");+ }+ #[test]+ fn malformed_commit_cannot_publish_writes_or_consume_the_transaction() {+ let owner = IndexedDbOwner::new(Arc::new(IndexedDbStorage::default()));+ let id = begin(&owner,"atomic","versionchange");+ owner.command("https://idb.test","put",json!({"id":id,"store":"items","key":"key","value":"value"}));+ assert_eq!(owner.command("https://idb.test","commit",json!({"id":id,"schema":[{"name":"items"}]}))["error"],"DataError");+ assert_eq!(owner.command("https://idb.test","info",json!({"name":"atomic"}))["schema"],json!([]));+ assert_eq!(owner.command("https://idb.test","get",json!({"id":id,"store":"items","key":"key"})),json!("value"));+ }+ #[test]+ fn dropping_a_document_aborts_its_writes_and_unblocks_waiting_transactions() {+ let store = Arc::new(IndexedDbStorage::default());+ let owner = IndexedDbOwner::new(store.clone());+ let id = begin(&owner,"dropped","versionchange");+ owner.command("https://idb.test","put",json!({"id":id,"store":"items","key":"key","value":"discard"}));+ let next = IndexedDbOwner::new(store);+ let waiting = next.command("https://idb.test","begin",json!({"name":"dropped","mode":"versionchange","stores":[]})).as_u64().unwrap();+ assert!(next.command("https://idb.test","ready",json!({"id":waiting})).is_null());+ drop(owner);+ assert!(!next.command("https://idb.test","ready",json!({"id":waiting})).is_null());+ assert!(next.command("https://idb.test","get",json!({"id":waiting,"store":"items","key":"key"})).is_null());+ }+ #[test]+ fn opening_requests_are_ordered_across_documents_and_released_on_teardown() {+ let storage = Arc::new(IndexedDbStorage::default());+ let first = IndexedDbOwner::new(storage.clone());+ let second = IndexedDbOwner::new(storage);+ let a = first.command("https://idb.test","reserve_open",json!({"name":"shared"}));+ let b = second.command("https://idb.test","reserve_open",json!({"name":"shared"}));+ assert!(a.is_u64() && b.is_u64());+ assert_eq!(first.command("https://idb.test","open_ready",json!({"name":"shared","opening":a})),json!(true));+ assert_eq!(second.command("https://idb.test","open_ready",json!({"name":"shared","opening":b})),json!(false));+ drop(first);+ assert_eq!(second.command("https://idb.test","open_ready",json!({"name":"shared","opening":b})),json!(true));+ assert_eq!(second.command("https://idb.test","delete",json!({"name":"shared"})),json!(true));+ assert_eq!(second.command("https://idb.test","open_ready",json!({"name":"shared","opening":b})),json!(true));+ }+}diff --git a/crates/obscura-js/src/indexed_db_tests.rs b/crates/obscura-js/src/indexed_db_tests.rsnew file mode 100644index 00000000..32f7acfa--- /dev/null+++ b/crates/obscura-js/src/indexed_db_tests.rs@@ -0,0 +1,342 @@+use crate::runtime::ObscuraJsRuntime;+use serde_json::{json, Value};++async fn probe(script: &str) -> Value {+ let mut rt = ObscuraJsRuntime::new();+ rt.set_dom(obscura_dom::parse_html("<!doctype html><body></body>"));+ rt.set_url("https://idb.test/");+ rt.run_page_init();+ rt.execute_script("indexeddb-regression", &format!(r#"+ globalThis.idbResult = null;+ const opened = (name, version = 1, upgrade = db => db.createObjectStore('items')) => new Promise((resolve, reject) => {{+ const r = indexedDB.open(name, version);+ r.onupgradeneeded = () => upgrade(r.result);+ r.onsuccess = () => resolve(r.result);+ r.onerror = () => reject(r.error);+ }});+ const requested = r => new Promise((resolve, reject) => {{+ r.onsuccess = () => resolve(r.result);+ r.onerror = () => reject(r.error);+ }});+ const finished = tx => new Promise(resolve => {{+ tx.oncomplete = () => resolve('complete');+ tx.onabort = () => resolve('abort');+ }});+ (async () => {{ {script} }})().then(+ value => idbResult = value,+ error => idbResult = {{error:error.name, message:error.message}}+ );+ "#)).unwrap();+ rt.run_event_loop_bounded(1000).await.unwrap();+ rt.evaluate("idbResult").unwrap()+}++#[tokio::test]+async fn indexeddb_upgrade_precedes_open_and_requests_precede_commit() {+ let out = probe(r#"+ const events = [];+ const r = indexedDB.open('ordering', 1);+ const db = await new Promise(resolve => {+ r.onupgradeneeded = () => { events.push('upgrade'); r.result.createObjectStore('items'); };+ r.onsuccess = () => { events.push('open'); resolve(r.result); };+ });+ const tx = db.transaction('items', 'readwrite');+ const done = finished(tx).then(() => events.push('complete'));+ tx.objectStore('items').put('kept', 1).onsuccess = () => events.push('put');+ await done;+ const value = await requested(db.transaction('items').objectStore('items').get(1));+ return {events, value, schema:db.objectStoreNames.contains('items')};+ "#).await;+ assert_eq!(out, json!({"events":["upgrade","open","put","complete"],"value":"kept","schema":true}));+}++#[tokio::test]+async fn indexeddb_abort_rolls_back_and_readonly_writes_throw() {+ let out = probe(r#"+ const db = await opened('abort');+ const tx = db.transaction('items', 'readwrite');+ const done = finished(tx);+ const r = tx.objectStore('items').put('discard', 1);+ let requestError;+ r.onerror = () => {requestError = r.error.name;};+ tx.abort();+ const terminal = await done;+ let readonly;+ const read = db.transaction('items');+ const value = await requested(read.objectStore('items').get(1));+ try { db.transaction('items').objectStore('items').put('bad', 2); }+ catch (e) { readonly = e.name; }+ return {terminal, requestError, missing:value === undefined, readonly};+ "#).await;+ assert_eq!(out, json!({"terminal":"abort","requestError":"AbortError","missing":true,"readonly":"ReadOnlyError"}));+}++#[tokio::test]+async fn indexeddb_values_are_cloned_and_duplicate_add_aborts_atomically() {+ let out = probe(r#"+ const db = await opened('clone');+ const tx = db.transaction('items', 'readwrite'), done = finished(tx);+ const source = {n:1, date:new Date(123), bytes:new Uint8Array([0,255]), map:new Map([['a',2]])};+ source.self = source;+ const store = tx.objectStore('items');+ store.put(source, 'clone'); source.n = 99;+ const cloned = await requested(store.get('clone'));+ await done;+ const dup = db.transaction('items', 'readwrite'), dupDone = finished(dup);+ const s = dup.objectStore('items'); s.add('first', 1);+ let error;+ s.add('second', 1).onerror = e => {error = e.target.error.name;};+ const terminal = await dupDone;+ const missing = await requested(db.transaction('items').objectStore('items').get(1));+ return [cloned.n, cloned.date.getTime(), Array.from(cloned.bytes), cloned.map.get('a'),+ cloned.self === cloned, error, terminal, missing === undefined];+ "#).await;+ assert_eq!(out, json!([1,123,[0,255],2,true,"ConstraintError","abort",true]));+}++#[tokio::test]+async fn indexeddb_typed_keys_ranges_and_request_callbacks_share_transaction() {+ let out = probe(r#"+ const db = await opened('keys');+ const tx = db.transaction('items', 'readwrite'), done = finished(tx);+ const s = tx.objectStore('items');+ s.put('number', 1); s.put('string', '1'); s.put('date', new Date(1));+ s.put('array', [1,'a']); s.put('binary', new Uint8Array([1]));+ const first = s.get(1);+ first.onsuccess = () => s.put('callback', 2);+ await done;+ const read = db.transaction('items'), r = read.objectStore('items');+ return [await requested(r.get(1)), await requested(r.get('1')),+ await requested(r.get(new Date(1))), await requested(r.get([1,'a'])),+ await requested(r.get(new Uint8Array([1]))),+ await requested(r.getAll(IDBKeyRange.bound(1,2))),+ await requested(r.count())];+ "#).await;+ assert_eq!(out, json!(["number","string","date","array","binary",["number","callback"],6]));+}++#[tokio::test]+async fn indexeddb_failed_upgrade_keeps_previous_version_and_schema() {+ let out = probe(r#"+ const db = await opened('upgrade'); db.close();+ const r = indexedDB.open('upgrade', 2);+ const error = await new Promise(resolve => {+ r.onupgradeneeded = () => {r.result.createObjectStore('discard'); r.transaction.abort();};+ r.onerror = () => resolve(r.error.name);+ r.onsuccess = () => resolve('unexpected success');+ });+ const old = await requested(indexedDB.open('upgrade'));+ return [error, old.version, old.objectStoreNames.contains('items'), old.objectStoreNames.contains('discard')];+ "#).await;+ assert_eq!(out, json!(["AbortError",1,true,false]));+}++#[tokio::test]+async fn indexeddb_request_error_can_be_canceled_without_aborting() {+ let out = probe(r#"+ const db = await opened('handled');+ const tx = db.transaction('items','readwrite'), done = finished(tx);+ const s = tx.objectStore('items'); s.add('first',1);+ s.add('duplicate',1).onerror = e => e.preventDefault();+ s.put('second',2);+ const terminal = await done;+ return [terminal,await requested(db.transaction('items').objectStore('items').getAll())];+ "#).await;+ assert_eq!(out, json!(["complete",["first","second"]]));+}++#[tokio::test]+async fn indexeddb_unique_indexes_and_cursors_use_generated_keys() {+ let out = probe(r#"+ const request = indexedDB.open('indexed',1);+ const db = await new Promise((resolve,reject) => {+ request.onupgradeneeded = () => request.result.createObjectStore('users',{keyPath:'id',autoIncrement:true})+ .createIndex('email','email',{unique:true});+ request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error);+ });+ const tx = db.transaction('users','readwrite'), done = finished(tx), users = tx.objectStore('users');+ const first = users.add({email:'b@test'}), second = users.add({email:'a@test'});+ const keys = [await requested(first),await requested(second)]; await done;+ const read = db.transaction('users'), index = read.objectStore('users').index('email');+ const found = await requested(index.get('b@test'));+ const rows = await new Promise(resolve => {+ const rows = [], cursor = index.openCursor();+ cursor.onsuccess = () => {const c=cursor.result;if (!c) return resolve(rows);+ rows.push([c.key,c.primaryKey,c.value.id]); c.continue();};+ });+ const bad = db.transaction('users','readwrite'), badDone = finished(bad);+ bad.objectStore('users').add({email:'a@test'});+ return [keys,found.id,rows,await badDone];+ "#).await;+ assert_eq!(out, json!([[1,2],1,[["a@test",2,2],["b@test",1,1]],"abort"]));+}++#[tokio::test]+async fn indexeddb_waiting_upgrade_notifies_and_respects_closed_connections() {+ let out = probe(r#"+ const first = await opened('connections'), events = [];+ first.onversionchange = e => {events.push([e.oldVersion,e.newVersion]);first.close();};+ const r = indexedDB.open('connections',2);+ const upgraded = await new Promise((resolve,reject) => {+ r.onupgradeneeded = () => {events.push('upgrade');r.result.createObjectStore('second');};+ r.onsuccess = () => resolve(r.result);r.onerror=()=>reject(r.error);+ });+ return [events,upgraded.version,upgraded.objectStoreNames.contains('second')];+ "#).await;+ assert_eq!(out, json!([[[1,2],"upgrade"],2,true]));+}++#[tokio::test]+async fn indexeddb_transaction_is_inactive_in_unrelated_timer_tasks() {+ let out = probe(r#"+ const db = await opened('inactive');+ const tx = db.transaction('items','readwrite');+ const s = tx.objectStore('items');+ s.put('first',1);+ return await new Promise(resolve => setTimeout(() => {+ try {s.put('late',2);resolve('accepted');}catch(e){resolve(e.name);}+ },0));+ "#).await;+ assert_eq!(out, json!("TransactionInactiveError"));+}++#[tokio::test]+async fn indexeddb_rejects_dom_nodes_instead_of_storing_a_plain_object() {+ let out = probe(r#"+ const db = await opened('uncloneable');+ const tx = db.transaction('items','readwrite');+ try {tx.objectStore('items').put({nested:document.body},1);return 'accepted';}+ catch(e){return e.name;}+ "#).await;+ assert_eq!(out, json!("DataCloneError"));+}++#[tokio::test]+async fn indexeddb_cross_document_versionchange_is_delivered_by_the_event_loop() {+ let storage = std::sync::Arc::new(crate::indexed_db::IndexedDbStorage::default());+ let setup = |storage| {+ let mut rt = ObscuraJsRuntime::new();+ rt.set_dom(obscura_dom::parse_html("<!doctype html><body></body>"));+ rt.set_url("https://idb.test/");+ rt.set_indexed_db(storage);+ rt.run_page_init();+ rt+ };+ let mut first = setup(storage.clone());+ first.execute_script("first", r#"+ globalThis.notified = false;+ const request = indexedDB.open('cross-document',1);+ request.onsuccess = () => { const db = request.result;+ db.onversionchange = () => {notified = true; db.close();}; };+ "#).unwrap();+ first.run_event_loop_bounded(100).await.unwrap();+ let mut second = setup(storage);+ second.execute_script("second", r#"+ globalThis.version = 0;+ const request = indexedDB.open('cross-document',2);+ request.onsuccess = () => version = request.result.version;+ "#).unwrap();+ second.run_event_loop_bounded(10).await.unwrap();+ first.run_event_loop_bounded(100).await.unwrap();+ assert_eq!(first.evaluate("notified").unwrap(), json!(true));+ second.run_event_loop_bounded(100).await.unwrap();+ assert_eq!(second.evaluate("version").unwrap().as_f64(), Some(2.0));+}++#[tokio::test]+async fn indexeddb_failed_unique_insert_does_not_consume_an_auto_increment_key() {+ let out = probe(r#"+ const r = indexedDB.open('generator',1);+ const db = await new Promise(resolve => {+ r.onupgradeneeded = () => r.result.createObjectStore('items',{autoIncrement:true}).createIndex('unique','x',{unique:true});+ r.onsuccess = () => resolve(r.result);+ });+ const tx = db.transaction('items','readwrite'), done = finished(tx), s = tx.objectStore('items');+ s.add({x:1}); s.add({x:1}).onerror = e => e.preventDefault();+ const key = await requested(s.add({x:2})); await done;+ return key;+ "#).await;+ assert_eq!(out.as_f64(),Some(2.0));+}++#[tokio::test]+async fn indexeddb_handlers_keep_listener_registration_order() {+ let out = probe(r#"+ const r = indexedDB.open('listeners',1), events = [];+ r.addEventListener('success', () => events.push('listener'));+ r.onsuccess = () => events.push('handler');+ await new Promise(resolve => r.addEventListener('success',resolve));+ return [events,r instanceof EventTarget,Object.prototype.toString.call(r)];+ "#).await;+ assert_eq!(out,json!([["listener","handler"],true,"[object IDBOpenDBRequest]"]));+}++#[tokio::test]+async fn indexeddb_new_javascript_task_cannot_add_to_an_existing_transaction() {+ let mut rt = ObscuraJsRuntime::new();+ rt.set_dom(obscura_dom::parse_html("<!doctype html>"));+ rt.set_url("https://idb.test/");+ rt.run_page_init();+ rt.execute_script("open",r#"+ globalThis.db = null;+ const request = indexedDB.open('task',1);+ request.onupgradeneeded = () => request.result.createObjectStore('items');+ request.onsuccess = () => db = request.result;+ "#).unwrap();+ rt.run_event_loop_bounded(100).await.unwrap();+ rt.execute_script("first-task",r#"+ globalThis.store = db.transaction('items','readwrite').objectStore('items');+ store.put('first',1);+ "#).unwrap();+ let result = rt.evaluate("(() => {try {store.put('late',2);return 'accepted';}catch(e){return e.name;}})()").unwrap();+ assert_eq!(result,json!("TransactionInactiveError"));+}++#[tokio::test]+async fn indexeddb_clones_files_and_blob_aliases_without_losing_their_interfaces() {+ let out = probe(r#"+ const db = await opened('files');+ const tx = db.transaction('items','readwrite'), done = finished(tx);+ const file = new File([new Uint8Array([0,255,117])],'fixture.bin',{type:'application/octet-stream',lastModified:123});+ tx.objectStore('items').put({file,alias:file,map:new Map([['file',file]])},1); await done;+ const copy = await requested(db.transaction('items').objectStore('items').get(1));+ return [copy.file instanceof File,copy.file.name,copy.file.type,copy.file.lastModified,+ Array.from(new Uint8Array(await copy.file.arrayBuffer())),copy.alias === copy.file,copy.map.get('file') === copy.file];+ "#).await;+ assert_eq!(out,json!([true,"fixture.bin","application/octet-stream",123,[0,255,117],true,true]));+}++#[tokio::test]+async fn indexeddb_cloned_nonextractable_crypto_keys_keep_their_material_and_permissions() {+ let out = probe(r#"+ const key = await crypto.subtle.importKey('raw',new Uint8Array([1,2,3]),{name:'HMAC',hash:'SHA-256'},false,['sign']);+ const expected = new Uint8Array(await crypto.subtle.sign('HMAC',key,new Uint8Array([4,5,6])));+ const db = await opened('keys-storage');+ const tx = db.transaction('items','readwrite'), done = finished(tx);+ tx.objectStore('items').put({key},1); await done;+ const copy = (await requested(db.transaction('items').objectStore('items').get(1))).key;+ const actual = new Uint8Array(await crypto.subtle.sign('HMAC',copy,new Uint8Array([4,5,6])));+ let rejected;+ try {await crypto.subtle.exportKey('raw',copy);rejected=false;}catch(e){rejected=true;}+ return [copy instanceof CryptoKey,copy.extractable,copy.usages,actual.length,+ actual.every((b,i) => b === expected[i]),rejected];+ "#).await;+ assert_eq!(out,json!([true,false,["sign"],32,true,true]));+}++#[tokio::test]+async fn indexeddb_empty_upgrade_completes_and_index_metadata_outlives_transactions() {+ let out = probe(r#"+ const empty = await new Promise((resolve,reject) => {+ const req = indexedDB.open('empty');+ req.onsuccess = () => resolve(req.result); req.onerror = () => reject(req.error);+ });+ const db = await opened('metadata',1,db => {+ db.createObjectStore('items').createIndex('email','email',{unique:true});+ });+ const tx = db.transaction('items'), done = finished(tx), index = tx.objectStore('items').index('email');+ await done;+ return [empty.version,empty.objectStoreNames.length,index.keyPath,index.unique,index.multiEntry];+ "#).await;+ assert_eq!(out,json!([1,0,"email",true,false]));+}diff --git a/crates/obscura-js/src/lib.rs b/crates/obscura-js/src/lib.rsindex 061b89c3..2a7e7324 100644--- a/crates/obscura-js/src/lib.rs+++ b/crates/obscura-js/src/lib.rs@@ -1,6 +1,7 @@pub mod cdp_watchdog;pub mod frame;mod import_map;+pub mod indexed_db;pub mod markdown;pub mod module_loader;pub mod ops;@@ -8,6 +9,9 @@ pub mod runtime;pub mod v8_flags;mod write_stream;+#[cfg(test)]+mod indexed_db_tests;+pub use markdown::HTML_TO_MARKDOWN_JS;pub use v8_flags::set_v8_flags;diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex f0c3a892..cbc55b84 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -354,6 +354,8 @@ pub struct ObscuraState {/// origin: an entry survives realm teardown on a same-origin navigation but/// never leaves the tab (issue #678).pub session_storage: Option<Arc<OriginStorage>>,+ pub indexed_db: Arc<crate::indexed_db::IndexedDbStorage>,+ pub(crate) indexed_db_owner: Option<crate::indexed_db::IndexedDbOwner>,pub http_client: Option<Arc<ObscuraHttpClient>>,/// The owning page's passive on_request/on_response callbacks (issue/// #408). Page-scoped, so scripted fetch()/XHR observation stays local to@@ -600,6 +602,7 @@ impl ObscuraState {// own bucket instead of the top document's.self.local_storage = parent.local_storage.clone();self.session_storage = parent.session_storage.clone();+ self.indexed_db = parent.indexed_db.clone();self.http_client = parent.http_client.clone();self.callbacks = parent.callbacks.clone();self.encoding = parent.encoding.clone();@@ -635,6 +638,8 @@ impl ObscuraState {cookie_jar: None,local_storage: Some(Arc::new(OriginStorage::default())),session_storage: Some(Arc::new(OriginStorage::default())),+ indexed_db: Arc::new(crate::indexed_db::IndexedDbStorage::default()),+ indexed_db_owner: None,http_client: None,callbacks: None,#[cfg(feature = "stealth")]@@ -6163,6 +6168,30 @@ fn op_storage_access(scope: &mut v8::PinScope, state: &OpState) -> bool {&*origin != "null"}+#[op2]+#[string]+fn op_indexed_db(scope: &mut v8::PinScope, state: &OpState, #[string] action: &str, #[string] payload: &str) -> String {+ if payload.len() > 24 * 1024 * 1024 { return "{\"error\":\"QuotaExceededError\"}".into(); }+ let gs = realm_state(scope, state);+ let mut gs = gs.borrow_mut();+ if gs.indexed_db_owner.is_none() {+ gs.indexed_db_owner = Some(crate::indexed_db::IndexedDbOwner::new(gs.indexed_db.clone()));+ }+ let origin = storage_origin(&gs);+ let result = serde_json::from_str(payload).map(|data|+ gs.indexed_db_owner.as_ref().map(|owner| if action == "notices" {+ serde_json::json!(owner.take_notices())+ } else { owner.command(&origin, action, data) }).unwrap_or_default())+ .unwrap_or_else(|_| serde_json::json!({"error":"DataError"}));+ result.to_string()+}++#[op2(fast)]+#[number]+fn op_indexed_db_task(state: &OpState) -> u64 {+ state.borrow::<SharedState>().borrow().animation_task_generation+}+fn origin_storage_command(storage: &Option<Arc<OriginStorage>>,origin: &str,@@ -7488,6 +7517,8 @@ pub fn build_extension() -> Extension {op_get_cookies(),op_set_cookie(),op_storage_access(),+ op_indexed_db(),+ op_indexed_db_task(),op_local_storage(),op_session_storage(),op_navigate(),diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex c9575373..3d23c050 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -556,6 +556,29 @@ impl ObscuraJsRuntime {// caller that triggered it did not need the error value.self.recover_heap_limit();begin_animation_task(&mut self.state.borrow_mut());+ self.poll_indexed_db_notifications();+ }++ fn poll_indexed_db_notifications(&mut self) {+ if !self.state.borrow().indexed_db.has_pending_notifications() { return; }+ let root_notices = self.state.borrow().indexed_db_owner.as_ref()+ .map(|owner| owner.take_notices()).unwrap_or_default();+ let realms = self.realm_states().borrow().media_realms();+ let mut deliveries = Vec::new();+ if !root_notices.is_empty() {+ deliveries.push((self.runtime().main_context(), root_notices));+ }+ for (context, state) in realms {+ let notices = state.borrow().indexed_db_owner.as_ref()+ .map(|owner| owner.take_notices()).unwrap_or_default();+ if !notices.is_empty() { deliveries.push((context, notices)); }+ }+ for (context, notices) in deliveries {+ let script = format!("globalThis.__obscura_poll_indexeddb({});", serde_json::json!(notices));+ if let Err(error) = self.eval_in_realm(&context, &script) {+ tracing::warn!("IndexedDB notification failed: {error}");+ }+ }}pub fn new() -> Self {Self::with_base_url("about:blank")@@ -1174,6 +1197,12 @@ impl ObscuraJsRuntime {self.state.borrow_mut().local_storage = Some(storage);}+ pub fn set_indexed_db(&self, storage: std::sync::Arc<crate::indexed_db::IndexedDbStorage>) {+ let mut state = self.state.borrow_mut();+ state.indexed_db_owner = None;+ state.indexed_db = storage;+ }+/// Install the page-owned `sessionStorage` backing store, so an entry/// survives realm teardown on a same-origin navigation and on CDP target/// switching while staying inside the tab (issue #678).diff --git a/docs/Persist-cookies-and-storage.md b/docs/Persist-cookies-and-storage.mdindex bc615618..ef34c780 100644--- a/docs/Persist-cookies-and-storage.md+++ b/docs/Persist-cookies-and-storage.md@@ -72,6 +72,31 @@ database. Opaque-origin documents cannot access either store.Automatic cross-document `storage` events are not implemented by this change.+## IndexedDB++IndexedDB data lives in memory, shared by pages in the same browser context and+origin. It survives navigation, but not process restart. Incognito contexts do+not share it. `--storage-dir` does not persist IndexedDB.++Transactions stage record changes and publish them atomically on completion;+aborting also rolls back schema changes and generated keys. Values use structured+serialization, including typed keys, cyclic graphs, files and symmetric crypto+keys. Readonly writes and uncloneable values fail instead of reporting success.+Upgrades notify existing connections and wait for them to close.++The context has a 64 MiB budget for committed records, schema and pending writes,+including serialized-value and record overhead. Individual serialized values+are limited to 16 MiB and encoded keys to 64 KiB. Quota failures abort an+unhandled write transaction, leaving its committed records unchanged.++This is not full IndexedDB conformance. Transactions currently serialize per+database, including readonly transactions; index queries and cursor steps scan+records rather than using a native index. Store/index renaming,+`continuePrimaryKey()`, the newer bulk-read options dictionaries, and on-disk+durability are not implemented. Database and schema names containing unpaired+UTF-16 units are not supported. These limits do not change the behavior of+cookies or Web Storage.+## Login once, scrape many```bash