Skip to main content

quickjs_jit_stdlib/llrt/llrt_utils/
object.rs

1// Vendored from LLRT d9fd873e793c (libs/llrt_utils/src/object.rs); module paths and
2// feature names adapted by scripts/import-stdlib.py.
3// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4// SPDX-License-Identifier: Apache-2.0
5use std::collections::BTreeMap;
6
7use rquickjs::{
8    atom::PredefinedAtom,
9    function::{Constructor, IntoJsFunc},
10    object::Property,
11    prelude::Func,
12    Array, Coerced, Ctx, Error, Exception, FromJs, IntoAtom, IntoJs, Object, Result, Undefined,
13    Value,
14};
15
16use crate::utils::primordials::{BasePrimordials, Primordial};
17
18pub trait ObjectExt<'js> {
19    fn get_optional<K: IntoAtom<'js> + Clone, V: FromJs<'js>>(&self, k: K) -> Result<Option<V>>;
20    fn get_required<K: AsRef<str>, V: FromJs<'js>>(
21        &self,
22        k: K,
23        object_name: &'static str,
24    ) -> Result<V>;
25    fn into_object_or_throw(self, ctx: &Ctx<'js>, object_name: &'static str)
26        -> Result<Object<'js>>;
27}
28
29impl<'js> ObjectExt<'js> for Object<'js> {
30    fn get_optional<K: IntoAtom<'js> + Clone, V: FromJs<'js> + Sized>(
31        &self,
32        k: K,
33    ) -> Result<Option<V>> {
34        self.get::<K, Option<V>>(k)
35    }
36
37    fn get_required<K: AsRef<str>, V: FromJs<'js>>(
38        &self,
39        k: K,
40        object_name: &'static str,
41    ) -> Result<V> {
42        let k = k.as_ref();
43        self.get::<&str, Option<V>>(k)?.ok_or_else(|| {
44            Exception::throw_type(
45                self.ctx(),
46                &[object_name, " '", k, "' property required"].concat(),
47            )
48        })
49    }
50
51    fn into_object_or_throw(self, _: &Ctx<'js>, _: &'static str) -> Result<Object<'js>> {
52        Ok(self)
53    }
54}
55
56impl<'js> ObjectExt<'js> for Value<'js> {
57    fn get_optional<K: IntoAtom<'js> + Clone, V: FromJs<'js>>(&self, k: K) -> Result<Option<V>> {
58        if let Some(obj) = self.as_object() {
59            return obj.get_optional(k);
60        }
61        Ok(None)
62    }
63
64    fn get_required<K: AsRef<str>, V: FromJs<'js>>(
65        &self,
66        k: K,
67        object_name: &'static str,
68    ) -> Result<V> {
69        self.as_object()
70            .ok_or_else(|| not_a_object_error(self.ctx(), object_name))?
71            .get_required(k, object_name)
72    }
73
74    fn into_object_or_throw(
75        self,
76        ctx: &Ctx<'js>,
77        object_name: &'static str,
78    ) -> Result<Object<'js>> {
79        self.into_object()
80            .ok_or_else(|| not_a_object_error(ctx, object_name))
81    }
82}
83
84pub fn not_a_object_error(ctx: &Ctx<'_>, object_name: &str) -> Error {
85    Exception::throw_type(ctx, &[object_name, " is not an object"].concat())
86}
87
88pub struct Proxy<'js> {
89    target: Value<'js>,
90    options: Object<'js>,
91}
92
93impl<'js> IntoJs<'js> for Proxy<'js> {
94    fn into_js(self, ctx: &Ctx<'js>) -> Result<Value<'js>> {
95        BasePrimordials::get(ctx)?
96            .constructor_proxy
97            .construct::<_, Value>((self.target, self.options))
98    }
99}
100
101impl<'js> Proxy<'js> {
102    pub fn new(ctx: Ctx<'js>) -> Result<Self> {
103        let options = Object::new(ctx.clone())?;
104        Ok(Self {
105            target: Undefined.into_value(ctx),
106            options,
107        })
108    }
109
110    pub fn with_target(ctx: Ctx<'js>, target: Value<'js>) -> Result<Self> {
111        let options = Object::new(ctx)?;
112        Ok(Self { target, options })
113    }
114
115    pub fn setter<T, P: 'js>(&self, setter: Func<T, P>) -> Result<()>
116    where
117        T: IntoJsFunc<'js, P> + 'js,
118    {
119        self.options.set(PredefinedAtom::Setter, setter)?;
120        Ok(())
121    }
122
123    pub fn getter<T, P: 'js>(&self, getter: Func<T, P>) -> Result<()>
124    where
125        T: IntoJsFunc<'js, P> + 'js,
126    {
127        self.options.set(PredefinedAtom::Getter, getter)?;
128        Ok(())
129    }
130}
131
132pub fn array_to_btree_map<'js>(
133    ctx: &Ctx<'js>,
134    array: Array<'js>,
135) -> Result<BTreeMap<String, Coerced<String>>> {
136    let value = object_from_entries(ctx, array)?;
137    let value = value.into_value();
138    BTreeMap::from_js(ctx, value)
139}
140
141pub fn object_from_entries<'js>(ctx: &Ctx<'js>, array: Array<'js>) -> Result<Object<'js>> {
142    let obj = Object::new(ctx.clone())?;
143    for value in array.into_iter().flatten() {
144        if let Some(entry) = value.as_array() {
145            if let Ok(key) = entry.get::<Value>(0) {
146                if let Ok(value) = entry.get::<Value>(1) {
147                    let _ = obj.set(key, value); //ignore result of failed
148                }
149            }
150        }
151    }
152    Ok(obj)
153}
154
155/// Build a constructor that behaves like `class Name extends Parent`
156pub fn define_subclass<'js, F, P>(
157    ctx: &Ctx<'js>,
158    name: &str,
159    parent: &Constructor<'js>,
160    construct: F,
161) -> Result<Constructor<'js>>
162where
163    F: IntoJsFunc<'js, P> + 'js,
164{
165    let parent_proto: Object = parent.get(PredefinedAtom::Prototype)?;
166    let proto = Object::new(ctx.clone())?;
167    proto.set_prototype(Some(&parent_proto))?;
168    let constructor = Constructor::new_prototype(ctx, proto, construct)?;
169    constructor.set_prototype(parent.as_object())?;
170    constructor.prop(PredefinedAtom::Name, Property::from(name).configurable())?;
171    Ok(constructor)
172}