saola-kit 0.1.4

Saola core toolkit for Laravel for Rust (contexts, envelope protocol, i18n, masks, modules, Sanctum-compatible tokens)
Documentation
use std::collections::BTreeMap;

use super::route_index::ContextSpec;

#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum ContextError {
    #[error("Host «{host}» is claimed by both context «{first}» and «{second}».")]
    DuplicateHost {
        host: String,
        first: String,
        second: String,
    },
    #[error("href(«{name}»): no request and no 'context' option, so only full route names are accepted.")]
    MissingContext { name: String },
    #[error("href(«{name}») is ambiguous: {}. Use the full name.", .matches.join(", "))]
    AmbiguousRoute { name: String, matches: Vec<String> },
    #[error("href(«{name}»): route not defined.")]
    RouteNotFound { name: String },
    #[error("href(«{name}»): Missing required parameter «{param}».")]
    MissingParameter { name: String, param: String },
}

/// Normalizes and maps declared hosts across Saola contexts.
pub struct ContextHosts;

impl ContextHosts {
    /// Normalizes a list of host/URL declarations: lowercased, without scheme, port, or path,
    /// skipping empty entries and preserving first-seen order without duplicates.
    pub fn normalize<I, S>(domains: I) -> Vec<String>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let mut hosts = Vec::new();
        for raw in domains {
            if let Some(host) = Self::normalize_one(raw.as_ref())
                && !hosts.contains(&host)
            {
                hosts.push(host);
            }
        }
        hosts
    }

    pub fn normalize_one(raw: &str) -> Option<String> {
        let trimmed = raw.trim();
        if trimmed.is_empty() {
            return None;
        }
        let lower = trimmed.to_ascii_lowercase();
        let without_scheme = strip_scheme(&lower);
        let without_path = without_scheme.split('/').next().unwrap_or("");
        let host = strip_port(without_path);
        if host.is_empty() {
            None
        } else {
            Some(host.to_owned())
        }
    }

    /// Maps every claimed host to its owning context slug. Two different contexts cannot claim the same host.
    pub fn table<'a>(
        contexts: impl IntoIterator<Item = &'a ContextSpec>,
    ) -> Result<BTreeMap<String, String>, ContextError> {
        let mut table: BTreeMap<String, String> = BTreeMap::new();
        for context in contexts {
            for host in &context.hosts {
                if let Some(existing) = table.get(host)
                    && existing != &context.slug
                {
                    return Err(ContextError::DuplicateHost {
                        host: host.clone(),
                        first: existing.clone(),
                        second: context.slug.clone(),
                    });
                }
                table.insert(host.clone(), context.slug.clone());
            }
        }
        Ok(table)
    }
}

fn strip_scheme(s: &str) -> &str {
    if let Some(pos) = s.find("://") {
        let scheme = &s[..pos];
        let mut chars = scheme.chars();
        if chars.next().is_some_and(|c| c.is_ascii_alphabetic())
            && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '.' | '-'))
        {
            return &s[pos + 3..];
        }
    }
    s
}

fn strip_port(s: &str) -> &str {
    if let Some(rest) = s.strip_prefix('[') {
        if let Some(end) = rest.find(']') {
            return &s[..=end + 1];
        }
        return s;
    }
    s.split(':').next().unwrap_or("")
}