use crate::validation::Severity;
use serde::Serialize;
use wasm_bindgen::prelude::*;
#[derive(Serialize)]
struct ValidationReport {
errors: Vec<crate::validation::SemanticError>,
warnings: Vec<crate::validation::SemanticError>,
}
#[wasm_bindgen(start)]
pub fn init() {
#[cfg(feature = "wasm")]
console_error_panic_hook::set_once();
}
#[wasm_bindgen]
pub fn parse_agent(source: &str) -> Result<JsValue, JsValue> {
match crate::parse(source) {
Ok(ast) => serde_wasm_bindgen::to_value(&ast)
.map_err(|e| JsValue::from_str(&format!("Serialization error: {}", e))),
Err(errs) => Err(JsValue::from_str(&errs.join("\n"))),
}
}
#[wasm_bindgen]
pub fn parse_agent_to_json(source: &str) -> Result<String, JsValue> {
match crate::parse(source) {
Ok(ast) => serde_json::to_string_pretty(&ast)
.map_err(|e| JsValue::from_str(&format!("JSON serialization error: {}", e))),
Err(errs) => Err(JsValue::from_str(&errs.join("\n"))),
}
}
#[wasm_bindgen]
pub fn validate_agent(source: &str) -> Result<bool, JsValue> {
match crate::parse(source) {
Ok(ast) => {
let issues = crate::validate_ast(&ast);
let errors: Vec<String> = issues
.into_iter()
.filter(|i| i.severity == Severity::Error)
.map(|i| i.message)
.collect();
if errors.is_empty() {
Ok(true)
} else {
Err(JsValue::from_str(&errors.join("\n")))
}
}
Err(errs) => Err(JsValue::from_str(&errs.join("\n"))),
}
}
#[wasm_bindgen]
pub fn validate_agent_semantic(source: &str) -> Result<JsValue, JsValue> {
let (errors, warnings) = match crate::parse(source) {
Ok(ast) => {
let issues = crate::validate_ast(&ast);
issues
.into_iter()
.partition(|i| i.severity == Severity::Error)
}
Err(parse_errs) => {
let errors = parse_errs
.into_iter()
.map(|msg| crate::validation::SemanticError {
message: msg,
span: None,
severity: Severity::Error,
hint: None,
})
.collect();
(errors, vec![])
}
};
let report = ValidationReport { errors, warnings };
serde_wasm_bindgen::to_value(&report).map_err(|e| JsValue::from_str(&e.to_string()))
}
#[wasm_bindgen]
pub fn version() -> String {
env!("CARGO_PKG_VERSION").to_string()
}
#[wasm_bindgen]
pub fn serialize_agent(ast: JsValue) -> Result<String, JsValue> {
let agent: crate::ast::AgentFile = serde_wasm_bindgen::from_value(ast)
.map_err(|e| JsValue::from_str(&format!("Failed to deserialize AST: {}", e)))?;
Ok(crate::serialize(&agent))
}
#[wasm_bindgen]
pub fn normalize_agent(source: &str) -> Result<String, JsValue> {
match crate::parse(source) {
Ok(ast) => Ok(crate::serialize(&ast)),
Err(errs) => Err(JsValue::from_str(&errs.join("\n"))),
}
}