calmlens 0.46.0

Rust SDK for CalmLens moderation, storage and CDN delivery
Documentation
//! The API's validation messages for the mock's `validation/invalid-request` refusals, read from
//! the generated table (`validation_messages.rs`) as every SDK's mock reads it.

use serde_json::Value;

use super::validation_messages::{
    MOCK_VALIDATION_COERCED, MOCK_VALIDATION_MESSAGES, MOCK_VALIDATION_MESSAGE_INDEX,
};

/// The message the API gives for an issue `code` (such as `validation/invalid-type`) at `path`
/// (`.`-separated, array indexes as numbers, empty for the whole request) of `operation`'s request
/// (an SDK operation as a JavaScript method path, such as `assets.decide`), where `value` was sent
/// (`None` when the field is missing), `key` is an unknown field's name (or the field a sort lists
/// twice) and `variant` the reason for a refusal the table words by reason (such as `too-long`).
/// A field the API coerces to a number has its value read as JavaScript's `Number` reads it.
/// "Invalid input" when the table has no message for it.
pub(crate) fn issue_message(
    operation: &str,
    path: &str,
    code: &str,
    value: Option<&Value>,
    key: Option<&str>,
    variant: Option<&str>,
) -> String {
    let pattern = path
        .split('.')
        .filter(|_| !path.is_empty())
        .map(|segment| {
            if !segment.is_empty() && segment.bytes().all(|byte| byte.is_ascii_digit()) {
                "*"
            } else {
                segment
            }
        })
        .collect::<Vec<_>>()
        .join(".");
    let field = format!("{operation} {pattern}");
    let base = format!("{field} {code}");
    let found = variant
        .and_then(|variant| lookup(&format!("{base} {variant}")))
        .or_else(|| lookup(&base));
    let Some(message) = found else {
        return "Invalid input".to_owned();
    };
    let (received, fractional) = if MOCK_VALIDATION_COERCED.binary_search(&&*field).is_ok() {
        let number = coerced_number(value);
        let received = if number.is_nan() { "NaN" } else { "number" };
        (received, number.is_finite() && number.fract() != 0.0)
    } else {
        let fractional = value
            .and_then(Value::as_f64)
            .is_some_and(|number| number.fract() != 0.0);
        (received_type(value), fractional)
    };
    message
        .replace("{received}", received)
        .replace("{number}", if fractional { "int" } else { "number" })
        .replace("{key}", key.unwrap_or(""))
}

fn lookup(key: &str) -> Option<&'static str> {
    MOCK_VALIDATION_MESSAGE_INDEX
        .binary_search_by(|(candidate, _)| candidate.cmp(&key))
        .ok()
        .map(|found| MOCK_VALIDATION_MESSAGES[MOCK_VALIDATION_MESSAGE_INDEX[found].1])
}

/// A value as `z.coerce.number()` reads it (JavaScript's `Number`): text as [`js_number`] reads
/// it, `true` 1, `false` and `null` 0, a number as it is and anything else (or nothing) NaN.
pub(crate) fn coerced_number(value: Option<&Value>) -> f64 {
    match value {
        Some(Value::String(text)) => js_number(text),
        Some(Value::Bool(flag)) => f64::from(u8::from(*flag)),
        Some(Value::Null) => 0.0,
        Some(Value::Number(number)) => number.as_f64().unwrap_or(f64::NAN),
        _ => f64::NAN,
    }
}

/// Text as JavaScript's `Number` reads it: surrounding whitespace is ignored, empty text is 0, a
/// decimal (or `0x`, `0o`, `0b`) number or `Infinity` is that number and anything else is NaN.
pub(crate) fn js_number(text: &str) -> f64 {
    let text = text.trim();
    if text.is_empty() {
        return 0.0;
    }
    for (prefix, radix) in [
        ("0x", 16),
        ("0X", 16),
        ("0o", 8),
        ("0O", 8),
        ("0b", 2),
        ("0B", 2),
    ] {
        if let Some(digits) = text.strip_prefix(prefix) {
            return u64::from_str_radix(digits, radix).map_or(f64::NAN, |number| number as f64);
        }
    }
    let unsigned = text.strip_prefix(['+', '-']).unwrap_or(text);
    if unsigned == "Infinity" {
        return if text.starts_with('-') {
            f64::NEG_INFINITY
        } else {
            f64::INFINITY
        };
    }
    // Rust also reads `inf` and `NaN`, which JavaScript doesn't.
    if !unsigned
        .bytes()
        .all(|byte| byte.is_ascii_digit() || matches!(byte, b'.' | b'e' | b'E' | b'+' | b'-'))
    {
        return f64::NAN;
    }
    text.parse().unwrap_or(f64::NAN)
}

/// zod's name for the type of a JSON value, `undefined` for a missing one.
fn received_type(value: Option<&Value>) -> &'static str {
    match value {
        None => "undefined",
        Some(Value::Null) => "null",
        Some(Value::Bool(_)) => "boolean",
        Some(Value::Number(_)) => "number",
        Some(Value::String(_)) => "string",
        Some(Value::Array(_)) => "array",
        Some(Value::Object(_)) => "object",
    }
}

/// A query parameter's value as the API's query schemas see it: a numeric string is that number,
/// anything else stays a string.
pub(crate) fn query_value(value: &str) -> Value {
    value
        .trim()
        .parse::<f64>()
        .ok()
        .filter(|number| number.is_finite() && !value.trim().is_empty())
        .and_then(serde_json::Number::from_f64)
        .map_or_else(|| Value::String(value.to_owned()), Value::Number)
}

#[cfg(test)]
mod tests {
    use super::issue_message;
    use serde_json::Value;

    /// Every SDK resolves the table's messages the same way: these cases' messages are the
    /// API's own, from parsing each input with the real schema.
    #[test]
    fn resolves_the_api_messages() {
        let fixture: Value =
            serde_json::from_str(include_str!("../../testdata/mock-validation.json")).unwrap();
        let cases = fixture["cases"].as_array().unwrap();
        assert!(!cases.is_empty());
        for case in cases {
            let message = issue_message(
                case["operation"].as_str().unwrap(),
                case["path"].as_str().unwrap(),
                case["code"].as_str().unwrap(),
                case.get("value"),
                case["key"].as_str(),
                case["variant"].as_str(),
            );
            assert_eq!(message, case["message"].as_str().unwrap(), "{case}");
        }
    }
}