Cotton code
308 lines · 16.4 KB · RustRaw
use super::*;use serde_json::json;fn studio() -> Value {    json!({        "id": "studio", "name": "Invented Studio", "family": "plain",        "palette": {            "light": { "accent": "#C6534B", "ink_body": "#444444", "pencil": 0.55, "tags": { "fill": "#FAEFE1", "ink": "#2E2925" } },            "dark": { "ground": "#101010" }        },        "type": { "title": "fraunces_text", "body": "courier" },        "scale": { "tokens": { "radius": 8.0, "spacing": 12.0, "stroke": 1.0, "title_size": 17.0 } },        "texture": { "grain": false, "shadow": "none", "tilt": false },        "cap": { "colour": "navy", "texture": "enamel" }    })}/// RULE: Every built-in theme is authored: it parses, validates, names only what this build draws, and the default theme ships.#[test]fn every_builtin_theme_is_strict_and_the_default_ships() {    for (id, json) in BUILTIN_THEME_FILES {        let raw: Value = serde_json::from_str(json).unwrap();        let theme = ThemeDefinition::strict(&raw).unwrap_or_else(|error| panic!("{id}.json: {error}"));        assert_eq!(&theme.id, id);        assert_eq!(serde_json::to_value(&theme).unwrap(), raw, "{id}.json round-trips");    }    assert!(ThemeDefinition::builtin(DEFAULT_THEME).is_some());    for family in THEME_FAMILIES {        assert!(BUILTIN_THEME_FILES.iter().any(|(id, _)| id == family), "{family} ships its own theme");    }}/// RULE: A business's brand faces are faces a theme row may name: a database keeps a look in Montserrat as its own row, drawn without a fallback.#[test]fn a_row_in_the_brand_faces_is_strict_and_falls_back_on_nothing() {    let mut raw = studio();    raw["type"] = json!({ "display": "montserrat_semibold", "title": "montserrat_semibold", "body": "montserrat", "meta": "montserrat" });    let theme = ThemeDefinition::strict(&raw).expect("Montserrat is a face this build draws");    let resolved = theme.resolved();    assert_eq!((&resolved["type"]["title"], &resolved["type"]["body"]), (&json!("montserrat_semibold"), &json!("montserrat")));    assert!(resolved.get("fallbacks").is_none_or(|went| went.as_array().is_some_and(Vec::is_empty)), "{resolved}");}#[test]fn a_full_row_in_the_apps_shape_is_strict_and_round_trips() {    let theme = ThemeDefinition::strict(&studio()).expect("the shape ThemeRow.swift decodes");    assert_eq!(serde_json::to_value(&theme).unwrap(), studio());}#[test]fn a_newer_family_role_or_key_is_read_and_refused_only_when_authored() {    let mut raw = studio();    raw["family"] = json!("velvet");    raw["motion"] = json!({"springs": true});    raw["palette"]["light"]["glow"] = json!("#FFFFFF");    raw["type"]["caption"] = json!("serif_new");    raw["cap"]["colour"] = json!("violet");    raw["texture"]["sheen"] = json!(true);    let read: ThemeDefinition = serde_json::from_value(raw.clone()).unwrap();    read.validate().expect("well formed here");    assert_eq!(serde_json::to_value(&read).unwrap(), raw, "relayed whole");    let Err(DefinitionError::UnknownKeys(named)) = ThemeDefinition::strict(&raw) else { panic!("authored") };    for word in ["family velvet", "motion", "palette.light glow", "type caption", "cap.colour violet", "texture sheen"] {        assert!(named.iter().any(|name| name == word), "{word} in {named:?}");    }}#[test]fn a_malformed_theme_is_refused() {    let cases: Vec<fn(&mut Value)> = vec![        |t| t["palette"]["light"]["accent"] = json!("red"),        |t| t["palette"]["light"]["tags"]["fill"] = json!("#FFF"),        |t| t["palette"]["light"]["pencil"] = json!(2),        |t| t["palette"]["dark"]["tags"] = json!("#FFFFFF"),        |t| t["scale"]["tokens"]["radius"] = json!(-1),        |t| t["scale"]["tokens"]["spacing"] = json!(true),        |t| t["scale"]["tokens"]["stroke"] = json!("1"),        |t| t["type"]["body"] = json!("Courier Prime"),        |t| t["name"] = json!(" "),        |t| t["id"] = json!("Studio"),        |t| t["cap"]["colour"] = json!("Navy Blue"),    ];    for mutate in cases {        let mut raw = studio();        mutate(&mut raw);        let refused = serde_json::from_value::<ThemeDefinition>(raw.clone())            .map_err(|error| DefinitionError::Parse(error.to_string()))            .and_then(|theme| theme.validate());        assert!(refused.is_err(), "{raw}");    }}/// RULE: Missing theme keys inherit the shipped family in Rust, so every reader shares one source of defaults and explicit overrides survive.#[test]fn missing_keys_resolve_from_the_shipped_family() {    let raw = json!({"id":"database", "family":"plain", "acts":{"destroys":{"stock":"tan"}}, "scale":{"tokens":{"radius":6}}});    let theme = ThemeDefinition::strict(&raw).unwrap();    let resolved = theme.resolved();    let shipped = ThemeDefinition::builtin("plain").unwrap().resolved();    assert_eq!(resolved["acts"]["destroys"]["stock"], "tan");    assert_eq!(resolved["acts"]["completes"], shipped["acts"]["completes"]);    assert_eq!(resolved["scale"]["tokens"]["radius"], 6);    assert_eq!(resolved["scale"]["tokens"]["spacing"], shipped["scale"]["tokens"]["spacing"]);    assert_eq!(resolved["type"], shipped["type"]);    assert_eq!(serde_json::to_value(theme).unwrap(), raw, "resolution never rewrites the person's overrides");}/// RULE: Every shipped theme key keeps its JSON type on writes; otherwise a malformed edit could silently hide a value from readers.#[test]fn shipped_theme_keys_refuse_wrong_types() {    fn visit(raw: &Value, path: &mut Vec<String>, cases: &mut Vec<Vec<String>>) {        if let Some(object) = raw.as_object() {            for (key, value) in object {                path.push(key.clone());                cases.push(path.clone());                visit(value, path, cases);                path.pop();            }        }    }    let shipped: Value = serde_json::from_str(BUILTIN_THEME_FILES[0].1).unwrap();    let mut paths = Vec::new();    visit(&shipped, &mut Vec::new(), &mut paths);    for path in paths {        let mut raw = shipped.clone();        let mut slot = &mut raw;        for key in &path { slot = &mut slot[key]; }        *slot = if slot.is_boolean() { json!("wrong") } else { json!(false) };        assert!(ThemeDefinition::from_json(&raw.to_string()).and_then(|theme| theme.validate()).is_err(), "{} must keep its type", path.join("."));        let mut raw = shipped.clone();        let mut slot = &mut raw;        for key in &path { slot = &mut slot[key]; }        *slot = Value::Null;        assert!(ThemeDefinition::strict(&raw).is_err(), "{} cannot silently treat null as absent", path.join("."));    }}/// RULE: Every shipped theme family exposes the same token keys, so switching families cannot leave a renderer lookup without a value.#[test]fn shipped_theme_families_carry_the_same_token_keys() {    fn leaves(value: &Value, prefix: &str, keys: &mut Vec<String>) {        if let Some(object) = value.as_object() {            for (key, value) in object { leaves(value, &format!("{prefix}.{key}"), keys); }        } else { keys.push(prefix.into()); }    }    let mut previous = None;    for (_, raw) in BUILTIN_THEME_FILES {        let mut keys = Vec::new();        leaves(&serde_json::from_str::<Value>(raw).unwrap(), "theme", &mut keys);        keys.sort();        if let Some(previous) = &previous { assert_eq!(&keys, previous); }        previous = Some(keys);    }}/// RULE: A theme sets only its tokens: an authored theme naming a scale knob outside `scale.tokens`, or a token outside THEME_SCALE_TOKENS, is refused — every other size is Swift's, beside its reader (architect, 14 Oct 2026), so a knob an agent invents for a theme is an error it sees, never a value nothing reads.#[test]fn a_theme_sets_only_its_tokens() {    for scale in [json!({"card_aspect": 1.4}), json!({"tokens": {"card_hand_columns": 3}}), json!({"radius": 8})] {        let raw = json!({"id": "studio", "family": "paper", "scale": scale});        assert!(matches!(ThemeDefinition::strict(&raw), Err(DefinitionError::UnknownKeys(_))), "{raw}");    }    ThemeDefinition::strict(&json!({"id": "studio", "family": "paper", "scale": {"tokens": {"radius": 8, "type_body_size": 16}}})).unwrap();    for (id, json) in BUILTIN_THEME_FILES {        let raw: Value = serde_json::from_str(json).unwrap();        let tokens: std::collections::BTreeSet<&str> = raw["scale"]["tokens"].as_object().unwrap().keys().map(String::as_str).collect();        assert_eq!(tokens, THEME_SCALE_TOKENS.iter().map(|(token, _)| *token).collect(), "{id}.json carries every token and nothing else");        assert_eq!(raw["scale"].as_object().unwrap().len(), 1, "{id}.json's scale is its tokens");    }}/// RULE: Stocks and object names must be drawable, and array tokens keep their element types, so a saved theme cannot disappear in a typed reader.#[test]fn malformed_new_tokens_are_refused() {    for patch in [        json!({"acts":{"destroys":{"stock":"purple"}}}),        json!({"cards":{"field_default_stock":"purple"}}),        json!({"cards":{"empty_outline_dash":["four"]}}),        json!({"cards":{"tray_stack_stocks":[false]}}),        json!({"objects":{"date":"Not an object"}}),    ] {        let mut raw = patch;        raw["id"] = json!("database");        assert!(ThemeDefinition::strict(&raw).is_err(), "{raw}");    }}/// RULE: Drawn object names may contain hyphen-separated lowercase words, like device-phone, but never path separators or empty segments that could name another resource.#[test]fn theme_objects_accept_safe_asset_names_and_refuse_paths() {    for name in ["phone","device-phone","mac","linux"] {        ThemeDefinition::strict(&json!({"id":"studio","family":"paper","objects":{"phone":name}})).unwrap();    }    for name in ["","../phone","device/phone","Device-phone","device--phone","-phone","phone-"] {        assert!(ThemeDefinition::strict(&json!({"id":"studio","family":"paper","objects":{"phone":name}})).is_err(), "{name}");    }}/// RULE: Every number an authored theme sets has a range beside its key in the core, the shipped themes sit inside them, and a value outside is refused naming key, value and range — so an assistant's theme cannot make a page unusable and the refusal says what to send instead.#[test]fn every_theme_number_has_a_range_and_the_shipped_themes_sit_inside() {    for (key, range) in THEME_SCALE_TOKENS.iter().chain(THEME_NUMBER_RANGES) {        assert!(range.min <= range.max, "{key}");    }    let mut names: Vec<&str> = THEME_SCALE_TOKENS.iter().map(|(token, _)| *token).collect();    names.sort_unstable();    names.dedup();    assert_eq!(names.len(), THEME_SCALE_TOKENS.len(), "a token is named once");    for (id, json) in BUILTIN_THEME_FILES {        let raw: Value = serde_json::from_str(json).unwrap();        assert_eq!(ThemeDefinition::out_of_range(&raw), vec![], "{id}.json sits inside every range");        fn numbers(value: &Value, path: String, out: &mut Vec<String>) {            match value {                Value::Object(object) => for (key, value) in object {                    numbers(value, if path.is_empty() { key.clone() } else { format!("{path}.{key}") }, out);                },                Value::Array(values) if values.iter().any(Value::is_number) => out.push(path),                Value::Number(_) => out.push(path),                _ => {}            }        }        let mut all = Vec::new();        numbers(&raw, String::new(), &mut all);        // The file's format is not a theme number: it is refused or read        // whole (`format::check_file`), never ranged.        for path in all.into_iter().filter(|path| path != "format_version") {            let ranged = path.strip_prefix("scale.tokens.").is_some_and(|key| theme_token_range(key).is_some())                || THEME_NUMBER_RANGES.iter().any(|(known, _)| *known == path);            assert!(ranged, "{id}.json's number {path} has a range in the core");        }    }}/// RULE: An authored theme with any number outside its range is refused whole and every such key is named with its value and range, so nothing partial is saved and one refusal lists every fix.#[test]fn out_of_range_numbers_are_each_named_and_refuse_the_theme() {    let raw = json!({"id": "database", "family": "paper",        "palette": {"light": {"accent": "#112233"}},        "scale": {"tokens": {"radius": 400, "spacing": 12, "type_weight_bold": 50}},        "cards": {"empty_outline_dash": [4, 0]}});    let found = ThemeDefinition::out_of_range(&raw);    let keys: Vec<&str> = found.iter().map(|o| o.key.as_str()).collect();    assert_eq!(keys, ["cards.empty_outline_dash.1", "scale.tokens.radius", "scale.tokens.type_weight_bold"]);    assert_eq!(found[1].to_string(), "scale.tokens.radius is 400, outside 0 to 40");    let Err(DefinitionError::OutOfRange(lines)) = ThemeDefinition::strict(&raw) else { panic!("refused") };    assert_eq!(lines.len(), 3);    let read: ThemeDefinition = serde_json::from_value(raw).unwrap();    read.validate().expect("a row read from the file is drawn as it came");}/// RULE: A theme word this build cannot draw — a family it does not ship, a face, a shadow, a cap or a card stock it does not name — never fails the read: it reads as the family's own and the resolved theme names each path in `fallbacks`; only an authored theme is refused for it.#[test]fn an_unknown_theme_word_draws_the_familys_own_and_is_named() {    let raw = json!({"id": "studio", "family": "zzz", "type": {"title": "zzz", "body": "courier"},        "texture": {"shadow": "zzz"}, "cap": {"colour": "zzz", "texture": "zzz"}, "acts": {"completes": {"stock": "zzz"}}});    let theme = ThemeDefinition::from_json(&raw.to_string()).expect("a newer build's theme reads");    theme.validate().expect("and is well formed here");    let resolved = theme.resolved();    let paper = ThemeDefinition::builtin(DEFAULT_THEME).unwrap().resolved();    assert_eq!(resolved["family"], json!(DEFAULT_THEME));    assert_eq!(resolved["type"]["title"], paper["type"]["title"]);    assert_eq!(resolved["type"]["body"], json!("courier"));    assert_eq!(resolved["texture"]["shadow"], paper["texture"]["shadow"]);    assert_eq!(resolved["acts"]["completes"]["stock"], paper["acts"]["completes"]["stock"]);    assert_eq!(resolved["fallbacks"], json!(["acts.completes.stock", "cap.colour", "cap.texture", "family", "texture.shadow", "type.title"]));    assert!(paper.get("fallbacks").is_none(), "the shipped theme falls back on nothing");    assert!(ThemeDefinition::strict(&raw).is_err());}/// RULE: A database's old full theme inherits newly shipped keys while its explicit values win, so a build can add theme capabilities without rewriting user data.#[test]fn an_old_full_copy_inherits_shipped_additions_and_keeps_owner_values() {    let mut old: Value = serde_json::from_str(BUILTIN_THEME_FILES[0].1).unwrap();    let value = old["scale"]["tokens"].as_object_mut().unwrap().remove("spacing").unwrap();    old["scale"]["tokens"]["radius"] = json!(9);    let resolved = ThemeDefinition::from_json(&old.to_string()).unwrap().resolved();    assert_eq!(resolved["scale"]["tokens"]["spacing"], value);    assert_eq!(resolved["scale"]["tokens"]["radius"], json!(9));}/// RULE: Retired theme keys are absent from resolved output but remain stored for other builds, so readers cannot freeze shipped capabilities or destroy synced edits.#[test]fn obsolete_keys_are_only_dropped_from_the_resolution() {    let raw = json!({"id":"paper","retired":true,"scale":{"tokens":{"retired_knob":7}}});    let theme = ThemeDefinition::from_json(&raw.to_string()).unwrap();    let resolved = theme.resolved();    assert!(resolved.get("retired").is_none());    assert!(resolved["scale"]["tokens"].get("retired_knob").is_none());    assert_eq!(serde_json::to_value(theme).unwrap(), raw);}/// RULE: A named shipped theme inherits its own defaults even without a family, so a sparse plain row cannot accidentally wear paper's values.#[test]fn a_named_theme_uses_the_same_id_as_its_base() {    let theme = ThemeDefinition::strict(&json!({"id":"plain"})).unwrap();    assert_eq!(theme.resolved(), ThemeDefinition::builtin("plain").unwrap().resolved());}/// Precise authored inks must move into tokens without eight-bit rounding.#[test]fn precise_srgb_inks_are_colours_and_invalid_channels_are_refused() {    for value in ["color(srgb 0.13 0.12 0.09)", "color(srgb 0 1 0.5)", "#123456", "#12345678"] {        assert!(is_colour(value), "{value}");    }    for value in ["color(srgb NaN 0 0)", "color(srgb inf 0 0)", "color(srgb 1.1 0 0)", "color(srgb -0.1 0 0)", "color(srgb 0 0)", "color(srgb 0 0 0 1)"] {        assert!(!is_colour(value), "{value}");    }}