The headless browser for AI agents and web scraping
fix(cdp): preserve undefined in by-value results
Paul Eipper20a3e0248150
diff --git a/crates/obscura-cdp/tests/runtime_by_value_undefined.rs b/crates/obscura-cdp/tests/runtime_by_value_undefined.rsnew file mode 100644index 00000000..7e576e06--- /dev/null+++ b/crates/obscura-cdp/tests/runtime_by_value_undefined.rs@@ -0,0 +1,81 @@+use obscura_cdp::dispatch::{dispatch, CdpContext};+use obscura_cdp::types::CdpRequest;+use serde_json::{json, Value};++async fn check_by_value(method: &str, await_promise: bool) {+ let mut ctx = CdpContext::new();+ let page_id = ctx.create_page();+ let session_id = "by-value".to_string();+ ctx.sessions.insert(session_id.clone(), page_id);++ for (expression, expected_type, expected_value) in [+ ("undefined", "undefined", None),+ ("null", "object", Some(Value::Null)),+ ("0", "number", Some(json!(0.0))),+ ("false", "boolean", Some(json!(false))),+ ("''", "string", Some(json!(""))),+ ("({answer: 42})", "object", Some(json!({"answer": 42}))),+ ("[null, 1]", "object", Some(json!([null, 1]))),+ ] {+ let expression = if await_promise {+ format!("Promise.resolve({expression})")+ } else {+ expression.to_string()+ };+ let mut params = json!({"returnByValue": true, "awaitPromise": await_promise});+ if method == "Runtime.evaluate" {+ params["expression"] = json!(expression);+ } else {+ params["functionDeclaration"] = json!(format!("function() {{ return {expression}; }}"));+ }+ let response = dispatch(+ &CdpRequest {+ id: 1,+ method: method.to_string(),+ params,+ session_id: Some(session_id.clone()),+ },+ &mut ctx,+ )+ .await;+ assert!(response.error.is_none(), "{method}: {:?}", response.error);+ let reply = response.result.unwrap();+ assert!(reply.get("exceptionDetails").is_none(), "{reply}");+ let result = &reply["result"];+ assert_eq!(+ result["type"], expected_type,+ "{method}, {expression}: {reply}"+ );+ assert_eq!(+ result.get("value"),+ expected_value.as_ref(),+ "{method}, {expression}: {reply}"+ );+ assert!(result.get("objectId").is_none(), "{reply}");+ if expected_type == "undefined" {+ assert!(result.get("subtype").is_none(), "{reply}");+ } else if expected_value == Some(Value::Null) {+ assert_eq!(result["subtype"], "null", "{reply}");+ }+ }+}++#[tokio::test(flavor = "current_thread")]+async fn evaluate_by_value_preserves_undefined() {+ check_by_value("Runtime.evaluate", false).await;+}++#[tokio::test(flavor = "current_thread")]+async fn call_function_on_by_value_preserves_undefined() {+ check_by_value("Runtime.callFunctionOn", false).await;+}++#[tokio::test(flavor = "current_thread")]+async fn evaluate_awaited_by_value_preserves_undefined() {+ check_by_value("Runtime.evaluate", true).await;+}++#[tokio::test(flavor = "current_thread")]+async fn call_function_on_awaited_by_value_preserves_undefined() {+ check_by_value("Runtime.callFunctionOn", true).await;+}diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex 6d59cbdf..0c8c2825 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -1998,8 +1998,7 @@ impl ObscuraJsRuntime {format!("globalThis.__obscura_objects['{}']", oid),).map_err(|e| format!("JS error: {}", e))?;- let json_val = self.v8_to_json(read)?;- return Ok(Self::info_from_json(&json_val));+ return self.v8_to_cdp_value(read);}Ok(Self::info_from_meta(&meta_json, Some(oid)))@@ -2132,8 +2131,7 @@ impl ObscuraJsRuntime {format!("globalThis.__obscura_objects['{}']", oid),).map_err(|e| format!("JS error: {}", e))?;- let json_val = self.v8_to_json(read)?;- return Ok(Self::info_from_json(&json_val));+ return self.v8_to_cdp_value(read);}let meta_result = self@@ -2168,8 +2166,7 @@ impl ObscuraJsRuntime {let result = self.execute_runtime_script("<callFnByValue>", code).map_err(|e| format!("JS error: {}", e))?;- let json_val = self.v8_to_json(result)?;- return Ok(Self::info_from_json(&json_val));+ return self.v8_to_cdp_value(result);}let code = format!(@@ -3528,6 +3525,31 @@ impl ObscuraJsRuntime {Ok(serde_json::Value::String(s))}+ fn v8_to_cdp_value(+ &mut self,+ result: deno_core::v8::Global<deno_core::v8::Value>,+ ) -> Result<RemoteObjectInfo, String> {+ // JSON collapses undefined into null. Classify it before serialization.+ let is_undefined = {+ let mut entered = self.runtime();+ let scope = &mut entered.handle_scope();+ deno_core::v8::Local::new(scope, &result).is_undefined()+ };+ if is_undefined {+ return Ok(RemoteObjectInfo {+ thrown: false,+ js_type: "undefined".into(),+ subtype: None,+ class_name: String::new(),+ description: String::new(),+ object_id: None,+ value: None,+ });+ }+ let value = self.v8_to_json(result)?;+ Ok(Self::info_from_json(&value))+ }+fn info_from_json(value: &serde_json::Value) -> RemoteObjectInfo {match value {serde_json::Value::Null => RemoteObjectInfo {