alpha2-host 0.10.0

Native project-rendering sidecar and batch CLI for alpha2.
//! The `diagnose` operation, answered with the functions the browser and Python bindings use.

use alpha2_model::DiagnoseOptions;
use serde_json::Value;

use crate::compose_request::{read_fonts, refused};
use crate::protocol::{DiagnoseDocument, DiagnoseRequest, HostError};

/// The document's report. A document with problems is answered, not refused.
///
/// # Errors
/// `INVALID_INPUT` for options that do not parse and a font file that cannot be read.
pub fn answer(request: &DiagnoseRequest) -> Result<Value, HostError> {
    let report = match request.document {
        DiagnoseDocument::Project => {
            alpha2_model::diagnose_project(&request.text, &options(request.options_text())?)
        }
        DiagnoseDocument::PluginManifest => alpha2_engine::extract::diagnose_manifest(
            &request.text,
            &options(request.options_text())?,
        ),
        DiagnoseDocument::Spec | DiagnoseDocument::Template => {
            let answer = alpha2_compose::diagnose_json_with_fonts(
                request.document.name(),
                &request.text,
                request.options_text(),
                &read_fonts(&request.fonts)?,
            )
            .map_err(|error| refused(&error))?;
            return serde_json::from_str(&answer).map_err(HostError::json);
        }
    };
    serde_json::to_value(report).map_err(HostError::json)
}

fn options(text: &str) -> Result<DiagnoseOptions, HostError> {
    if text.trim().is_empty() {
        return Ok(DiagnoseOptions::default());
    }
    serde_json::from_str(text)
        .map_err(|error| HostError::new("INVALID_INPUT", format!("options: {error}")))
}