Lines
100 %
Functions
78.57 %
Branches
//! Script compile entry: automation source to the stored bytecode.
//!
//! [`compile_script`] is the one script compiler. It compiles in Script mode
//! against the entity-script surface the trigger runner links, and backs `nms --compile` and the save paths [`create_script`] and
//! [`update_script_source`]. `rpc` owns the compile-then-store step because
//! `server` cannot depend on it; the server functions take source and bytecode
//! together.
use nomiscript::{Compiler, Reader, SymbolTable};
use server::error::ServerError;
use server::user::User;
use thiserror::Error;
use uuid::Uuid;
#[derive(Debug, Error)]
pub enum ScriptError {
/// The source failed to parse or compile; shown at the `source` field.
#[error("script compile error: {0}")]
Compile(String),
#[error(transparent)]
Server(#[from] ServerError),
}
/// Compiles `source` as an automation script, returning the wasm bytes.
///
/// No rpc host natives are registered: the compiler declares every registered
/// native as a wasm import, and the trigger runner links none of them, so a
/// module built with them would not load.
/// # Errors
/// [`ScriptError::Compile`] with the reader or compiler message, which carries
/// the source position where the compiler gives one.
pub fn compile_script(source: &str) -> Result<Vec<u8>, ScriptError> {
if source.trim().is_empty() {
return Err(ScriptError::Compile(
"the script source is empty".to_string(),
));
let mut symbols = SymbolTable::with_builtins();
let program = Reader::parse(source).map_err(|err| ScriptError::Compile(err.to_string()))?;
Compiler::new()
.compile(&program, &mut symbols)
.map_err(|err| ScriptError::Compile(err.to_string()))
/// Compiles `source` and stores it with its bytecode as a new script.
/// A compile failure stores nothing; otherwise the server failure.
pub async fn create_script(
user: &User,
source: String,
name: Option<String>,
) -> Result<Uuid, ScriptError> {
let bytecode = compile_script(&source)?;
Ok(user
.create_script_from_source(source, bytecode, name, true)
.await?)
/// Recompiles `source` and replaces the script's source and bytecode together.
/// A compile failure leaves the script as it was; otherwise the server failure.
pub async fn update_script_source(
id: Uuid,
) -> Result<(), ScriptError> {
Ok(user.update_script_source(id, source, bytecode).await?)