use std::path::{Path, PathBuf};
use crate::Value;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct FnHandle(pub u32);
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PathPart {
Key(String),
Index(usize),
}
pub const UNLISTED_OBJECT: &str = "an object with properties Brrrty can't list";
pub fn refused_plain_object(what: &str) -> bool {
what.starts_with(UNLISTED_OBJECT)
}
pub fn path_text(path: &[PathPart]) -> String {
const KEEP: usize = 6;
let mut out = String::from("data");
for (n, part) in path.iter().enumerate() {
if path.len() > 3 * KEEP && n >= KEEP && n < path.len() - KEEP {
if n == KEEP {
out.push_str(&format!("<{} levels>", path.len() - 2 * KEEP));
}
continue;
}
match part {
PathPart::Index(i) => out.push_str(&format!("[{i}]")),
PathPart::Key(k) => {
let plain = k
.chars()
.next()
.is_some_and(|c| c.is_ascii_alphabetic() || c == '_' || c == '$')
&& k.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$');
if plain {
out.push('.');
out.push_str(k);
} else {
out.push('[');
out.push_str(&serde_json::Value::String(k.clone()).to_string());
out.push(']');
}
}
}
}
out
}
#[derive(Debug, Clone, PartialEq)]
pub struct Decoded {
pub value: Value,
pub functions: Vec<(Vec<PathPart>, FnHandle)>,
pub refused: Vec<(Vec<PathPart>, String)>,
}
impl Decoded {
pub fn is_exact(&self) -> bool {
self.functions.is_empty() && self.refused.is_empty()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct JsError {
pub name: String,
pub message: String,
pub stack: String,
pub file: Option<PathBuf>,
pub line: Option<u32>,
pub column: Option<u32>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuntimeFailure {
pub message: String,
pub stderr_tail: Vec<String>,
pub stopped: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub enum JsResult<T> {
Ok(T),
Thrown(JsError),
Failed(RuntimeFailure),
}
pub trait JsRuntime: Send {
fn set_argument(&mut self, arg: &Value) -> JsResult<()>;
fn load(&mut self, file: &Path, call: bool) -> JsResult<Decoded>;
fn call(&mut self, f: FnHandle, args: &[Value]) -> JsResult<Decoded>;
fn vars_used(&mut self, f: FnHandle, data: &Value) -> JsResult<Vec<String>>;
fn reads(&mut self) -> JsResult<Vec<PathBuf>>;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn paths_read_like_javascript() {
let p = [
PathPart::Key("posts".into()),
PathPart::Index(3),
PathPart::Key("a b".into()),
PathPart::Key("$ok_1".into()),
];
assert_eq!(path_text(&p), r#"data.posts[3]["a b"].$ok_1"#);
assert_eq!(path_text(&[]), "data");
}
#[test]
fn a_very_deep_path_keeps_its_ends() {
let p: Vec<PathPart> = (0..40).map(|_| PathPart::Key("c".into())).collect();
assert_eq!(path_text(&p), "data.c.c.c.c.c.c<28 levels>.c.c.c.c.c.c");
}
}