Skip to content

Commit bcf847d

Browse files
committed
feat: add methods to check for Javascript Proxy and retrieve its target
1 parent 21416c0 commit bcf847d

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

src/value/value.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,12 @@ impl OwnedJsValue {
164164
unsafe { q::JS_IsArray(self.value) }
165165
}
166166

167+
/// Check if this value is a Javascript Proxy object.
168+
#[inline]
169+
pub fn is_proxy(&self) -> bool {
170+
unsafe { q::JS_IsProxy(self.value) }
171+
}
172+
167173
/// Check if this value is a Javascript function.
168174
#[inline]
169175
pub fn is_function(&self) -> bool {
@@ -253,6 +259,21 @@ impl OwnedJsValue {
253259
OwnedJsArray::try_from_value(self.clone())
254260
}
255261

262+
pub fn get_proxy_target(&self, recursive: bool) -> Result<OwnedJsValue, ValueError> {
263+
if !self.is_proxy() {
264+
return Err(ValueError::UnexpectedType);
265+
}
266+
267+
let target = unsafe { q::JS_GetProxyTarget(self.context, self.value) };
268+
let target = OwnedJsValue::new(self.context, target);
269+
270+
if recursive && target.is_proxy() {
271+
target.get_proxy_target(true)
272+
} else {
273+
Ok(target)
274+
}
275+
}
276+
256277
/// Try convert this value into a object
257278
pub fn try_into_object(self) -> Result<OwnedJsObject, ValueError> {
258279
OwnedJsObject::try_from_value(self)

tests/runtime.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,25 @@ fn test_eval_pass() {
6262
}
6363
}
6464

65+
false
66+
}),
67+
),
68+
(
69+
"new Proxy([1,2], {})",
70+
Box::new(|v| {
71+
if v.is_proxy() {
72+
let target = v.get_proxy_target(false).unwrap();
73+
if target.is_array() {
74+
let arr = target.to_array().unwrap();
75+
if arr.length() == 2
76+
&& arr.get_index(0).unwrap().unwrap().to_int().unwrap() == 1
77+
&& arr.get_index(1).unwrap().unwrap().to_int().unwrap() == 2
78+
{
79+
return true;
80+
}
81+
}
82+
}
83+
6584
false
6685
}),
6786
),

0 commit comments

Comments
 (0)