Skip to main content

soma_codemode/runner/
js_args.rs

1use serde_json::Value;
2
3pub(super) fn required_string_arg<'a>(
4    cx: &crate::javy::quickjs::Ctx<'a>,
5    args: &[crate::javy::quickjs::Value<'a>],
6    index: usize,
7    message: &str,
8) -> crate::javy::quickjs::Result<String> {
9    let value = args
10        .get(index)
11        .ok_or_else(|| javy_type_error(cx.clone(), message))?;
12    let text = crate::javy::val_to_string(cx, value.clone())
13        .map_err(|err| crate::javy::to_js_error(cx.clone(), err))?;
14    if text.trim().is_empty() {
15        Err(javy_type_error(cx.clone(), message))
16    } else {
17        Ok(text)
18    }
19}
20
21pub(super) fn optional_string_arg<'a>(
22    cx: &crate::javy::quickjs::Ctx<'a>,
23    args: &[crate::javy::quickjs::Value<'a>],
24    index: usize,
25) -> crate::javy::quickjs::Result<Option<String>> {
26    args.get(index)
27        .filter(|value| !value.is_null() && !value.is_undefined())
28        .map(|value| {
29            crate::javy::val_to_string(cx, value.clone())
30                .map_err(|err| crate::javy::to_js_error(cx.clone(), err))
31        })
32        .transpose()
33}
34
35pub(super) fn json_arg<'a>(
36    cx: &crate::javy::quickjs::Ctx<'a>,
37    args: &[crate::javy::quickjs::Value<'a>],
38    index: usize,
39    default: &str,
40) -> crate::javy::quickjs::Result<Value> {
41    let text = args
42        .get(index)
43        .map(|value| cx.json_stringify(value.clone()))
44        .transpose()?
45        .flatten()
46        .map(|value| value.to_string())
47        .transpose()?
48        .unwrap_or_else(|| default.to_string());
49    serde_json::from_str(&text).map_err(|err| {
50        javy_type_error(
51            cx.clone(),
52            format!("argument must be JSON-serializable: {err}"),
53        )
54    })
55}
56
57pub(super) fn javy_type_error(
58    cx: crate::javy::quickjs::Ctx<'_>,
59    message: impl Into<String>,
60) -> crate::javy::quickjs::Error {
61    crate::javy::to_js_error(cx, anyhow::anyhow!(message.into()))
62}