use anyhow::{Context, Result, bail};
use camino::Utf8Path;
use odk_schema::CompiledSchema;
use std::process::Command;
pub fn compile_ts_schema(schema_path: &Utf8Path) -> Result<CompiledSchema> {
let schema_path = schema_path
.canonicalize_utf8()
.context("Failed to resolve schema path")?;
let odk_ts_import = std::env::var("ODK_TS_PATH")
.map(|path| format!("{path}/src/index.ts"))
.unwrap_or_else(|_| "@omnidotdev/odk".to_string());
if which::which("bun").is_err() {
bail!(
"bun not found. Install it with:\n\
curl -fsSL https://bun.sh/install | bash"
);
}
let script = format!(
r#"
import schema from "{schema_path}";
import {{ odk }} from "{odk_ts_import}";
process.stdout.write(odk.toJSON(schema));
"#,
);
let output = Command::new("bun")
.arg("-e")
.arg(&script)
.output()
.context("Failed to execute bun")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
bail!("Schema compilation failed:\n{}", stderr);
}
let stdout = String::from_utf8(output.stdout).context("Invalid UTF-8 in bun output")?;
let schema: CompiledSchema =
serde_json::from_str(&stdout).context("Failed to parse compiled schema JSON")?;
Ok(schema)
}