ai-agent 0.13.4

Idiomatic agent sdk inspired by the claude code source leak
Documentation
//! Converts Zod-like schemas to JSON Schema.
//!
//! This module provides functionality to convert type schemas to JSON Schema format.
//! Note: In Rust, we use serde_json::Value directly instead of Zod schemas.
//! This module provides a similar interface for compatibility.

use serde_json::Value;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};

type JsonSchema7Type = serde_json::Value;

/// Cache for schema conversions. Since Rust doesn't have WeakMap with object identity,
/// we use a simple HashMap with schema identifiers (JSON strings).
/// In practice, this would be keyed by the schema's canonical JSON representation.
lazy_static::lazy_static! {
    static ref SCHEMA_CACHE: RwLock<HashMap<String, JsonSchema7Type>> = RwLock::new(HashMap::new());
}

/// Converts a JSON Schema (as Value) to JSON Schema format.
/// This is a simple pass-through since we already have JSON values in Rust.
pub fn zod_to_json_schema(schema: &Value) -> JsonSchema7Type {
    // Try to use cache based on schema string representation
    let schema_key = schema.to_string();

    // Check cache first
    if let Ok(cache) = SCHEMA_CACHE.read() {
        if let Some(cached) = cache.get(&schema_key) {
            return cached.clone();
        }
    }

    // For JSON schema, we just return the value as-is since it's already valid JSON
    // In a real implementation, this might validate and normalize the schema
    let result = schema.clone();

    // Store in cache
    if let Ok(mut cache) = SCHEMA_CACHE.write() {
        cache.insert(schema_key, result.clone());
    }

    result
}

/// Convenience function to create a JSON schema from a JSON schema string.
pub fn parse_json_schema(schema_str: &str) -> Result<JsonSchema7Type, serde_json::Error> {
    let parsed: Value = serde_json::from_str(schema_str)?;
    Ok(zod_to_json_schema(&parsed))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_zod_to_json_schema() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "name": { "type": "string" }
            }
        });
        let result = zod_to_json_schema(&schema);
        assert_eq!(result.get("type").unwrap(), "object");
    }

    #[test]
    fn test_parse_json_schema() {
        let schema_str = r#"{"type": "string"}"#;
        let result = parse_json_schema(schema_str).unwrap();
        assert_eq!(result.get("type").unwrap(), "string");
    }
}