evorule-plugin-kit 0.2.0

In-process native plugin mechanism common crate: NativeService trait, service declaration entries, and a generic filter router shared by all evorule-services plugin families
Documentation
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2026 EvoRule Project
// This file is part of EvoRule, licensed under GNU Affero General Public License v3 or later.
//! Production conversion surface: `serde_json::Value` -> canonical `JsonValue`.
//!
//! This is the single implementation of the serde-to-canonical conversion
//! across the ecosystem. It was promoted from the rule loader's internal
//! helper to this kit so that any consumer (server-side loader, plugin
//! families, future ecosystem applications) can reuse the exact same
//! conversion without re-deriving it.
//!
//! # Semantics (pinned, do not diverge)
//!
//! - `Null` / `Bool` / `String` map one-to-one;
//! - numbers: `i64`-representable values become `Integer`; anything else
//!   (floats) becomes the canonical domain-decimal string form (TCB string
//!   decimal convention, deterministic across platforms);
//! - arrays and objects convert recursively; object members land in a
//!   `BTreeMap` so key order is normalized (determinism discipline).

use std::collections::BTreeMap;

use crate::reexports::JsonValue;

/// Convert a `serde_json::Value` into the canonical `JsonValue` form.
///
/// The sole conversion implementation ecosystem-wide: consumers must call
/// this instead of hand-writing a second copy (single-implementation
/// discipline). Behavior is pinned by the tests in this module; any change
/// here must be mirrored by the consumers' golden vectors.
pub fn serde_to_tcb(v: serde_json::Value) -> JsonValue {
    match v {
        serde_json::Value::Null => JsonValue::Null,
        serde_json::Value::Bool(b) => JsonValue::Bool(b),
        serde_json::Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                JsonValue::Integer(i)
            } else {
                JsonValue::String(n.to_string().into())
            }
        }
        serde_json::Value::String(s) => JsonValue::String(s.into()),
        serde_json::Value::Array(arr) => {
            JsonValue::Array(arr.into_iter().map(serde_to_tcb).collect())
        }
        serde_json::Value::Object(obj) => {
            let mut map = BTreeMap::new();
            for (k, val) in obj {
                map.insert(k, serde_to_tcb(val));
            }
            JsonValue::Object(map)
        }
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
    use super::*;
    use serde_json::json;

    #[test]
    fn scalars_map_one_to_one() {
        assert!(matches!(serde_to_tcb(json!(null)), JsonValue::Null));
        assert!(matches!(serde_to_tcb(json!(true)), JsonValue::Bool(true)));
        assert!(matches!(serde_to_tcb(json!(false)), JsonValue::Bool(false)));
        match serde_to_tcb(json!("hello")) {
            JsonValue::String(s) => assert_eq!(s.as_ref(), "hello"),
            other => panic!("expected String, got {other:?}"),
        }
    }

    #[test]
    fn integers_stay_integer() {
        match serde_to_tcb(json!(42)) {
            JsonValue::Integer(i) => assert_eq!(i, 42),
            other => panic!("expected Integer, got {other:?}"),
        }
        match serde_to_tcb(json!(-7)) {
            JsonValue::Integer(i) => assert_eq!(i, -7),
            other => panic!("expected Integer, got {other:?}"),
        }
    }

    #[test]
    fn floats_become_domain_decimal_strings() {
        // Non-i64 numbers land as the canonical string decimal form (TCB
        // convention): deterministic textual rendering, not a float variant.
        match serde_to_tcb(json!(2.5)) {
            JsonValue::String(s) => assert_eq!(s.as_ref(), "2.5"),
            other => panic!("expected String decimal form, got {other:?}"),
        }
    }

    #[test]
    fn arrays_convert_recursively() {
        match serde_to_tcb(json!([1, "a", true, null])) {
            JsonValue::Array(items) => {
                assert_eq!(items.len(), 4);
                assert!(matches!(items[0], JsonValue::Integer(1)));
                assert!(matches!(items[1], JsonValue::String(_)));
                assert!(matches!(items[2], JsonValue::Bool(true)));
                assert!(matches!(items[3], JsonValue::Null));
            }
            other => panic!("expected Array, got {other:?}"),
        }
    }

    #[test]
    fn objects_convert_recursively_and_normalize_key_order() {
        // Insertion order differs from lexicographic order; the BTreeMap
        // normalization must still yield an object with all members present.
        let out = serde_to_tcb(json!({
            "zeta": 1,
            "nested": {"beta": [2.5, "x"], "alpha": null},
            "alpha": "first"
        }));
        match out {
            JsonValue::Object(map) => {
                assert_eq!(map.len(), 3);
                let keys: Vec<_> = map.keys().cloned().collect();
                assert_eq!(keys, vec!["alpha", "nested", "zeta"]);
                match &map["nested"] {
                    JsonValue::Object(inner) => {
                        let inner_keys: Vec<_> = inner.keys().cloned().collect();
                        assert_eq!(inner_keys, vec!["alpha", "beta"]);
                        match &inner["beta"] {
                            JsonValue::Array(items) => {
                                match &items[0] {
                                    JsonValue::String(s) => assert_eq!(s.as_ref(), "2.5"),
                                    other => panic!("expected String decimal, got {other:?}"),
                                }
                                assert!(
                                    matches!(items[1], JsonValue::String(ref s) if s.as_ref() == "x")
                                );
                            }
                            other => panic!("expected Array, got {other:?}"),
                        }
                    }
                    other => panic!("expected Object, got {other:?}"),
                }
            }
            other => panic!("expected Object, got {other:?}"),
        }
    }

    #[test]
    fn round_trip_shape_matches_loader_semantics() {
        // Fixture shape mirroring the rule-set metadata surface consumed by
        // the loader and the graph-dispatch family: constants + registry.
        let out = serde_to_tcb(json!({
            "metadata": {
                "constants": [
                    { "constant_id": "c1", "version": "2018", "value_hash": "h1", "domain_lo": 0, "domain_hi": 1 }
                ]
            }
        }));
        match out {
            JsonValue::Object(map) => match &map["metadata"] {
                JsonValue::Object(meta) => match &meta["constants"] {
                    JsonValue::Array(items) => {
                        assert_eq!(items.len(), 1);
                        match &items[0] {
                            JsonValue::Object(entry) => {
                                match &entry["domain_lo"] {
                                    JsonValue::Integer(i) => assert_eq!(*i, 0),
                                    other => panic!("expected Integer, got {other:?}"),
                                }
                                match &entry["version"] {
                                    JsonValue::String(s) => assert_eq!(s.as_ref(), "2018"),
                                    other => panic!("expected String, got {other:?}"),
                                }
                            }
                            other => panic!("expected Object entry, got {other:?}"),
                        }
                    }
                    other => panic!("expected Array, got {other:?}"),
                },
                other => panic!("expected Object metadata, got {other:?}"),
            },
            other => panic!("expected Object, got {other:?}"),
        }
    }
}