rorpc 0.2.5

Rust oRPC — annotation-driven Axum handlers with automatic TypeScript contract generation
Documentation
//! Namespace resolution utilities.
//!
//! Provides shared logic for resolving namespace prefixes at runtime,
//! used by both `generate_contract()` and the `router!()` macro.

use std::collections::HashMap;

use crate::NamespaceMetadata;

/// Build a namespace lookup map from inventory-registered namespace metadata.
///
/// Maps each module path to its namespace prefix.
///
/// # Example
///
/// ```ignore
/// let map = build_namespace_map();
/// assert_eq!(map.get("myapp::api::users"), Some(&"/api"));
/// ```
pub fn build_namespace_map() -> HashMap<&'static str, &'static str> {
    let mut namespace_map = HashMap::new();
    for ns in inventory::iter::<NamespaceMetadata> {
        namespace_map.insert(ns.module_path, ns.prefix);
    }
    namespace_map
}

/// Resolve the full path for a handler by applying namespace prefixes.
///
/// Walks up the module path hierarchy (from most specific to root) and
/// applies the first matching namespace prefix found.
///
/// # Arguments
///
/// * `handler_module_path` - The module path where the handler is defined (e.g., "myapp::api::users")
/// * `handler_path` - The base handler path (e.g., "/create")
/// * `namespace_map` - The namespace lookup map from `build_namespace_map()`
///
/// # Returns
///
/// The composed path with namespace prefix applied (e.g., "/api/create"),
/// or the original handler path if no namespace matches.
///
/// # Example
///
/// ```ignore
/// let namespace_map = build_namespace_map();
/// let path = resolve_namespace_path("myapp::api::users", "/create", &namespace_map);
/// assert_eq!(path, "/api/create");
/// ```
pub fn resolve_namespace_path(
    handler_module_path: &str,
    handler_path: &str,
    namespace_map: &HashMap<&'static str, &'static str>,
) -> String {
    let module_parts: Vec<&str> = handler_module_path.split("::").collect();

    // Walk from most specific (full path) to least specific (root)
    for i in (0..=module_parts.len()).rev() {
        let parent_path = module_parts[..i].join("::");
        if let Some(prefix) = namespace_map.get(parent_path.as_str()) {
            // Found a matching namespace — compose prefix + handler path
            return format!("{}{}", prefix, handler_path);
        }
    }

    // No namespace found — return handler path as-is
    handler_path.to_string()
}

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

    #[test]
    fn resolve_with_exact_module_match() {
        let mut map = HashMap::new();
        map.insert("myapp::api::users", "/api");

        let result = resolve_namespace_path("myapp::api::users", "/create", &map);
        assert_eq!(result, "/api/create");
    }

    #[test]
    fn resolve_with_parent_module_match() {
        let mut map = HashMap::new();
        map.insert("myapp::api", "/api");

        let result = resolve_namespace_path("myapp::api::users", "/create", &map);
        assert_eq!(result, "/api/create");
    }

    #[test]
    fn resolve_without_match_returns_original() {
        let map = HashMap::new();

        let result = resolve_namespace_path("myapp::other", "/create", &map);
        assert_eq!(result, "/create");
    }

    #[test]
    fn resolve_prefers_most_specific_match() {
        let mut map = HashMap::new();
        map.insert("myapp", "/root");
        map.insert("myapp::api", "/api");

        let result = resolve_namespace_path("myapp::api::users", "/create", &map);
        assert_eq!(result, "/api/create");
    }
}

// ===========================================================================
// Schema Resolution
// ===========================================================================

/// Convert module path to PascalCase TypeScript name for disambiguation.
///
/// # Examples
///
/// ```ignore
/// assert_eq!(
///     module_path_to_ts_name("issue1_duplicate_schemas::entities::Session", "Session"),
///     "EntitiesSession"
/// );
/// assert_eq!(
///     module_path_to_ts_name("issue1_duplicate_schemas::types::Session", "Session"),
///     "TypesSession"
/// );
/// ```
///
/// Strips the crate root (first segment) and the type name (last segment).
/// Everything in between becomes the disambiguating prefix in PascalCase.
pub fn module_path_to_ts_name(module_path: &str, type_name: &str) -> String {
    let parts: Vec<&str> = module_path.split("::").collect();

    // Strip the crate root (first segment) and the type name (last segment)
    // Everything in between becomes the disambiguating prefix
    let middle: Vec<&str> = parts
        .iter()
        .skip(1) // skip crate root (e.g. "issue1_duplicate_schemas")
        .copied()
        .filter(|p| *p != type_name) // skip the type name itself
        .collect();

    if middle.is_empty() {
        // No distinguishing module segments — fall back to full crate name prefix
        let crate_root = parts.first().copied().unwrap_or("");
        let pascal_crate = crate_root
            .split('_')
            .map(|word| {
                let mut c = word.chars();
                match c.next() {
                    None => String::new(),
                    Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
                }
            })
            .collect::<String>();
        return format!("{}{}", pascal_crate, type_name);
    }

    // Convert each middle segment to PascalCase: "entities" → "Entities"
    let mut name_parts: Vec<String> = middle
        .iter()
        .map(|p| {
            let mut c = p.chars();
            match c.next() {
                None => String::new(),
                Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
            }
        })
        .collect();

    name_parts.push(type_name.to_string());
    name_parts.join("")
}

/// Pick the best `ts_schema_name` for `type_ref` given the module path of
/// the schema that contains the reference.
///
/// Strategy:
/// 1. Exactly one candidate → unambiguous, use it directly.
/// 2. Multiple candidates → prefer the one whose `module_path` shares the
///    most leading path segments with `referencing_module`.
/// 3. Still tied → pick the first alphabetically (deterministic).
pub fn resolve_type_ref(
    type_ref: &str,
    referencing_module: &str,
    candidates_by_name: &HashMap<&'static str, Vec<(String, &'static str)>>,
) -> Option<String> {
    let candidates = candidates_by_name.get(type_ref)?;

    if candidates.len() == 1 {
        return Some(candidates[0].0.clone());
    }

    // Count shared leading segments between two module paths
    fn shared_prefix_len(a: &str, b: &str) -> usize {
        a.split("::")
            .zip(b.split("::"))
            .take_while(|(x, y)| x == y)
            .count()
    }

    candidates
        .iter()
        .max_by_key(|(_, mod_path)| {
            (
                shared_prefix_len(referencing_module, mod_path),
                mod_path.to_string(),
            )
        })
        .map(|(ts_name, _)| ts_name.clone())
}

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

    #[test]
    fn module_path_to_ts_name_with_middle_segments() {
        assert_eq!(
            module_path_to_ts_name("myapp::entities::user", "User"),
            "EntitiesUser"
        );
        assert_eq!(
            module_path_to_ts_name("myapp::types::user", "User"),
            "TypesUser"
        );
    }

    #[test]
    fn module_path_to_ts_name_without_middle_segments() {
        assert_eq!(module_path_to_ts_name("myapp::User", "User"), "MyappUser");
        assert_eq!(module_path_to_ts_name("my_app::User", "User"), "MyAppUser");
    }

    #[test]
    fn resolve_type_ref_with_single_candidate() {
        let mut candidates = HashMap::new();
        candidates.insert("User", vec![("UserSchema".to_string(), "myapp::types")]);

        let result = resolve_type_ref("User", "myapp::api", &candidates);
        assert_eq!(result, Some("UserSchema".to_string()));
    }

    #[test]
    fn resolve_type_ref_prefers_same_module() {
        let mut candidates = HashMap::new();
        candidates.insert(
            "User",
            vec![
                ("TypesUserSchema".to_string(), "myapp::types"),
                ("EntitiesUserSchema".to_string(), "myapp::entities"),
            ],
        );

        // Should prefer entities variant when referencing from entities
        let result = resolve_type_ref("User", "myapp::entities::profile", &candidates);
        assert_eq!(result, Some("EntitiesUserSchema".to_string()));
    }

    #[test]
    fn resolve_type_ref_returns_none_for_unknown() {
        let candidates = HashMap::new();
        let result = resolve_type_ref("Unknown", "myapp::api", &candidates);
        assert_eq!(result, None);
    }
}