~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
1536 lines · 56.8 KB Raw History
//! The methods the server serves, read from their lexicons in `spec/lexicons`,
//! the MCP tool and CLI command each one is (`spec/COMMANDS.md`), how a
//! call's parameters and input are checked against its lexicon, and how a
//! record is checked against its type's (`spec/VALIDATION.md`).

#![forbid(unsafe_code)]

mod format;

pub use format::{valid as valid_format, valid_at_uri};
use serde_json::{Map, Value as Json, json};
use std::collections::HashMap;
use std::sync::LazyLock;
use unicode_segmentation::UnicodeSegmentation;

include!(concat!(env!("OUT_DIR"), "/lexicons.rs"));

/// The encoding of a JSON answer.
pub const JSON: &str = "application/json";

/// What kind of method a lexicon defines.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Kind {
    Query,
    Procedure,
    Subscription,
}

/// The type of an argument's value: `String`, `Integer` and `Boolean` are
/// written as text on the command line, the rest as JSON.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Type {
    String,
    Integer,
    Boolean,
    Array,
    /// An `object`, `ref` or `union`.
    Object,
    /// `unknown`, `bytes`, `cid-link` or `blob`: JSON with no constraint.
    Unknown,
}

impl Type {
    /// How a command's help names the value of a flag of this type.
    pub fn placeholder(self) -> &'static str {
        match self {
            Type::String => "<string>",
            Type::Integer => "<integer>",
            Type::Boolean => "[true|false]",
            Type::Array | Type::Object | Type::Unknown => "<json>",
        }
    }
}

/// One argument of a method: a query parameter or an input property.
#[derive(Debug)]
pub struct Arg {
    /// As the lexicon names it, and as the method's MCP tool takes it.
    pub name: String,
    pub ty: Type,
    /// Whether the lexicon requires it.
    pub required: bool,
    pub description: Option<String>,
    /// The JSON Schema of its value in the method's MCP tool's `inputSchema`.
    pub schema: Json,
    /// Its lexicon definition.
    pub def: Json,
}

impl Arg {
    /// Whether it names the account the method is about, and so may be left
    /// out, with a token, for the token's account's DID: a `repo` or `did` the
    /// lexicon requires. `createAccount`'s optional `did`, an account to
    /// import, names none here.
    pub fn names_account(&self) -> bool {
        self.required && (self.name == "repo" || self.name == "did")
    }

    /// Whether the method's MCP tool and CLI command require it.
    pub fn needed(&self) -> bool {
        self.required && !self.names_account()
    }

    /// Its CLI flag, without the leading `--`.
    pub fn flag(&self) -> String {
        split_case(&self.name, '-')
    }
}

/// One method the server serves.
#[derive(Debug)]
pub struct Method {
    pub nsid: String,
    /// The NSID's second-to-last segment.
    pub group: String,
    /// The NSID's last segment, as written.
    pub name: String,
    pub kind: Kind,
    pub description: Option<String>,
    /// Its parameters (a query's or a subscription's) or its input's properties
    /// (a procedure's), by name.
    pub args: Vec<Arg>,
    /// The encoding of its input, if it is a procedure that takes one.
    pub input: Option<String>,
    /// The encoding of its answer, if it has one.
    pub output: Option<String>,
    /// The `params` or input schema the arguments are the properties of.
    schema: Json,
    /// The schema of its JSON answer, if it has one.
    output_schema: Json,
}

impl Method {
    /// Its MCP tool's name, if it has a tool: every method whose answer is
    /// JSON, or that answers nothing, and whose input, if it has one, is JSON too.
    pub fn tool(&self) -> Option<String> {
        (self.kind != Kind::Subscription
            && self.output.as_deref().is_none_or(|o| o == JSON)
            && self.input.as_deref().is_none_or(|i| i == JSON))
        .then(|| format!("{}_{}", self.group, split_case(&self.name, '_')))
    }

    /// Whether its input is the request's body as it is, of any type, rather
    /// than JSON: its command sends standard input, with `--encoding` as its type.
    pub fn raw_input(&self) -> bool {
        self.input.as_deref().is_some_and(|i| i != JSON)
    }

    /// Its CLI command's name within its group, if it has one: every method but a subscription.
    pub fn command(&self) -> Option<String> {
        (self.kind != Kind::Subscription).then(|| split_case(&self.name, '-'))
    }

    pub fn arg(&self, name: &str) -> Option<&Arg> {
        self.args.iter().find(|a| a.name == name)
    }

    /// Its MCP tool's `inputSchema`.
    pub fn input_schema(&self) -> Json {
        let properties: Map<String, Json> = self
            .args
            .iter()
            .map(|a| (a.name.clone(), a.schema.clone()))
            .collect();
        let required: Vec<&str> = self
            .args
            .iter()
            .filter(|a| a.needed())
            .map(|a| a.name.as_str())
            .collect();
        json!({ "type": "object", "properties": properties, "required": required })
    }

    /// Its MCP tool's `title`: its command's name in words, then its group
    /// (`spec/COMMANDS.md`, "Names").
    pub fn title(&self) -> String {
        title(&self.group, &split_case(&self.name, '-'))
    }

    /// Its MCP tool's annotations, by what it does (`spec/COMMANDS.md`,
    /// "Hints"): a query only reads, but for those that sign a token for the
    /// account; a procedure writes, and destroys unless it only adds.
    pub fn annotations(&self) -> Option<Json> {
        let nsid = self.nsid.as_str();
        match self.kind {
            Kind::Query if SIGNS.contains(&nsid) => {
                Some(json!({ "readOnlyHint": false, "destructiveHint": false }))
            }
            Kind::Query => Some(json!({ "readOnlyHint": true })),
            Kind::Procedure => {
                Some(json!({ "readOnlyHint": false, "destructiveHint": !ADDITIVE.contains(&nsid) }))
            }
            Kind::Subscription => None,
        }
    }
}

/// A tool's `title` from its command's group and kebab-case name:
/// `create-record` of `repo` as `Create record (repo)`.
pub fn title(group: &str, command: &str) -> String {
    let mut words = command.replace('-', " ");
    if let Some(first) = words.get_mut(..1) {
        first.make_ascii_uppercase();
    }
    format!("{words} ({group})")
}

/// The queries that sign a token for the account, and so are no mere reads,
/// as `spec/COMMANDS.md`, "Hints", lists them.
const SIGNS: &[&str] = &[
    "com.atproto.server.getServiceAuth",
    "com.atproto.space.getDelegationToken",
];

/// The procedures that only add, as `spec/COMMANDS.md`, "Hints", lists
/// them: every other may delete, replace or end something, and so a
/// procedure the server comes to serve is destructive until it is listed.
const ADDITIVE: &[&str] = &[
    "com.atproto.server.createAccount",
    "com.atproto.server.createSession",
    "com.atproto.server.createAppPassword",
    "com.atproto.server.createInviteCode",
    "com.atproto.server.createInviteCodes",
    "com.atproto.server.requestEmailConfirmation",
    "com.atproto.server.confirmEmail",
    "com.atproto.server.requestEmailUpdate",
    "com.atproto.server.requestPasswordReset",
    "com.atproto.server.requestAccountDelete",
    "com.atproto.server.activateAccount",
    "com.atproto.identity.requestPlcOperationSignature",
    "com.atproto.identity.signPlcOperation",
    "com.atproto.repo.createRecord",
    "app.bsky.notification.registerPush",
    "com.atproto.space.createSpace",
    "com.atproto.space.createRecord",
    "com.atproto.space.authorizeSpaceSync",
    "com.atproto.space.notifyRepoUpdate",
];

/// `createRecord` as `create_record` (with `_`) or `create-record` (with `-`).
pub fn split_case(name: &str, sep: char) -> String {
    let mut out = String::with_capacity(name.len() + 4);
    for c in name.chars() {
        if c.is_ascii_uppercase() {
            if !out.is_empty() {
                out.push(sep);
            }
            out.push(c.to_ascii_lowercase());
        } else {
            out.push(c);
        }
    }
    out
}

/// Every method the server serves, in NSID order.
pub fn methods() -> &'static [Method] {
    static METHODS: LazyLock<Vec<Method>> = LazyLock::new(load);
    &METHODS
}

/// The method of an NSID.
pub fn method(nsid: &str) -> Option<&'static Method> {
    methods().iter().find(|m| m.nsid == nsid)
}

/// The method whose MCP tool has this name.
pub fn by_tool(name: &str) -> Option<&'static Method> {
    methods().iter().find(|m| m.tool().as_deref() == Some(name))
}

/// The method of a CLI command.
pub fn by_command(group: &str, command: &str) -> Option<&'static Method> {
    methods()
        .iter()
        .find(|m| m.group == group && m.command().as_deref() == Some(command))
}

/// The groups with at least one CLI command, in order.
pub fn groups() -> Vec<&'static str> {
    let mut gs: Vec<&str> = methods()
        .iter()
        .filter(|m| m.command().is_some())
        .map(|m| m.group.as_str())
        .collect();
    gs.sort();
    gs.dedup();
    gs
}

/// Every lexicon, by its id.
static DOCS: LazyLock<HashMap<String, Json>> = LazyLock::new(|| {
    LEXICONS
        .iter()
        .map(|t| {
            let doc: Json = serde_json::from_str(t).expect("lexicon JSON");
            (doc["id"].as_str().expect("lexicon id").to_string(), doc)
        })
        .collect()
});

fn load() -> Vec<Method> {
    let mut methods: Vec<Method> = DOCS.values().filter_map(read_method).collect();
    methods.sort_by(|a, b| a.nsid.cmp(&b.nsid));
    for (i, m) in methods.iter().enumerate() {
        if methods[..i]
            .iter()
            .any(|o| o.group == m.group && o.name == m.name)
        {
            panic!("two methods are {} {}", m.group, m.name);
        }
        // `pds xrpc` is the CLI's own command (`spec/COMMANDS.md`, "Names").
        if m.group == "xrpc" {
            panic!("{} is of the group xrpc", m.nsid);
        }
    }
    methods
}

fn read_method(doc: &Json) -> Option<Method> {
    let nsid = doc["id"].as_str()?.to_string();
    let main = &doc["defs"]["main"];
    let kind = match main["type"].as_str()? {
        "query" => Kind::Query,
        "procedure" => Kind::Procedure,
        "subscription" => Kind::Subscription,
        _ => return None,
    };
    let mut segments = nsid.rsplit('.');
    let name = segments.next()?.to_string();
    let group = segments.next()?.to_string();
    let object = match kind {
        Kind::Procedure => main["input"]["schema"].clone(),
        _ => main["parameters"].clone(),
    };
    let object = if object.is_null() {
        json!({ "type": "params", "properties": {} })
    } else {
        object
    };
    let required: Vec<&str> = object["required"]
        .as_array()
        .map(|r| r.iter().filter_map(Json::as_str).collect())
        .unwrap_or_default();
    let nullable: Vec<&str> = object["nullable"]
        .as_array()
        .map(|r| r.iter().filter_map(Json::as_str).collect())
        .unwrap_or_default();
    let args = object["properties"]
        .as_object()
        .map(|props| {
            props
                .iter()
                .map(|(n, p)| {
                    let ty = type_of(p);
                    Arg {
                        name: n.clone(),
                        ty,
                        required: required.contains(&n.as_str()),
                        description: p["description"].as_str().map(str::to_string),
                        schema: schema_of(p, ty, nullable.contains(&n.as_str())),
                        def: p.clone(),
                    }
                })
                .collect()
        })
        .unwrap_or_default();
    Some(Method {
        nsid,
        group,
        name,
        kind,
        description: main["description"].as_str().map(str::to_string),
        args,
        input: main["input"]["encoding"].as_str().map(str::to_string),
        output: main["output"]["encoding"].as_str().map(str::to_string),
        schema: object,
        output_schema: main["output"]["schema"].clone(),
    })
}

impl Method {
    /// A query's parameters, from a URL's pairs: each typed as its lexicon
    /// says, defaults filled in, then checked. The first of a repeated
    /// parameter that is not an array counts; pairs it does not take are passed over.
    pub fn parse_params<'a>(
        &self,
        pairs: impl IntoIterator<Item = (&'a str, &'a str)>,
    ) -> Result<Map<String, Json>, Invalid> {
        let mut out = Map::new();
        for (k, v) in pairs {
            let Some(arg) = self.arg(k) else { continue };
            let array = arg.ty == Type::Array;
            let ty = if array {
                arg.def["items"]["type"].as_str()
            } else {
                arg.def["type"].as_str()
            };
            let typed = match ty {
                Some("integer") => v
                    .parse::<i64>()
                    .map(Json::from)
                    .map_err(|_| Invalid(format!("Params/{k} must be an integer")))?,
                Some("boolean") => match v {
                    "true" => Json::Bool(true),
                    "false" => Json::Bool(false),
                    _ => return Err(Invalid(format!("Params/{k} must be a boolean"))),
                },
                _ => Json::String(v.to_string()),
            };
            match out.entry(k).or_insert_with(|| {
                if array {
                    Json::Array(vec![])
                } else {
                    typed.clone()
                }
            }) {
                Json::Array(items) if array => items.push(typed),
                _ => {}
            }
        }
        for arg in &self.args {
            if let (false, Some(d)) = (out.contains_key(&arg.name), arg.def.get("default")) {
                out.insert(arg.name.clone(), d.clone());
            }
        }
        let value = Json::Object(out);
        validate(&self.nsid, &self.schema, &value, "Params")?;
        let Json::Object(out) = value else {
            unreachable!("built as an object")
        };
        Ok(out)
    }

    /// Check a procedure's input against its lexicon.
    pub fn check_input(&self, input: &Json) -> Result<(), Invalid> {
        validate(&self.nsid, &self.schema, input, "Input")
    }

    /// Fill in, in a procedure's input, the values its lexicon gives a
    /// `default` where they are missing, at any depth.
    pub fn fill_input_defaults(&self, input: &mut Json) {
        fill_defaults(&self.nsid, &self.schema, input);
    }

    /// Check a JSON answer against its lexicon; a method with no output schema takes any.
    pub fn check_output(&self, output: &Json) -> Result<(), Invalid> {
        if self.output_schema.is_null() {
            return Ok(());
        }
        validate(&self.nsid, &self.output_schema, output, "Output")
    }
}

/// Why a value does not match its lexicon.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Invalid(pub String);

/// The definition a reference made in lexicon `nsid` names (`#name` there,
/// `id` for its main, or `id#name`), and the lexicon it is in.
fn resolve<'a>(nsid: &'a str, r: &'a str) -> Option<(&'static Json, &'a str)> {
    let (id, name) = match r.split_once('#') {
        Some(("", name)) => (nsid, name),
        Some((id, name)) => (id, name),
        None => (r, "main"),
    };
    Some((DOCS.get(id)?["defs"].get(name)?, id))
}

/// A union's ref in full, as a `$type` names it.
fn full_ref(nsid: &str, r: &str) -> String {
    match r.split_once('#') {
        Some(("", name)) => format!("{nsid}#{name}"),
        _ => r.to_string(),
    }
}

/// A `$type` as it names a definition: a lexicon's main by its NSID alone.
fn main_stripped(t: &str) -> &str {
    t.strip_suffix("#main").unwrap_or(t)
}

/// Whether a blob's `mimeType` is one `accept` takes: one of its entries,
/// or under `<type>/` for an entry `<type>/*`, case and all.
fn accepts(accept: &[Json], mime: &str) -> bool {
    accept.iter().filter_map(Json::as_str).any(|a| {
        a == mime
            || a == "*/*"
            || a.strip_suffix('*')
                .is_some_and(|prefix| prefix.ends_with('/') && mime.starts_with(prefix))
    })
}

/// The blob ref a JSON value is: exactly `$type` `blob`, a `ref` linking a
/// CIDv1 of the `raw` codec, a `mimeType` with a `/` and a `size` of 0 or
/// more. Answers its `mimeType` and `size`.
fn blob_ref(value: &Json) -> Option<(&str, u64)> {
    let o = value.as_object().filter(|o| o.len() == 4)?;
    let link = o
        .get("ref")?
        .as_object()
        .filter(|l| l.len() == 1)?
        .get("$link")?
        .as_str()?;
    let raw = pds_repo::data::parse_cid(link).is_some_and(|c| c[1] == 0x55);
    let mime = o.get("mimeType")?.as_str().filter(|m| m.contains('/'))?;
    (o.get("$type")? == "blob" && raw).then_some((mime, o.get("size")?.as_u64()?))
}

/// Check `value`, at `path`, against the definition `def` in lexicon `nsid`.
pub fn validate(nsid: &str, def: &Json, value: &Json, path: &str) -> Result<(), Invalid> {
    let bad = |what: &str| Err(Invalid(format!("{path} must be {what}")));
    let strings = |k: &str| {
        def[k]
            .as_array()
            .into_iter()
            .flatten()
            .filter_map(Json::as_str)
    };
    if def.get("const").is_some_and(|c| c != value) {
        return bad(&format!("{}", def["const"]));
    }
    if let Some(e) = def["enum"].as_array().filter(|e| !e.contains(value)) {
        return bad(&format!("one of {}", Json::Array(e.clone())));
    }
    match def["type"].as_str().unwrap_or("unknown") {
        "record" => validate(nsid, &def["record"], value, path),
        "object" | "params" => {
            let Some(obj) = value.as_object() else {
                return bad("an object");
            };
            let nullable = |k: &str| strings("nullable").any(|n| n == k);
            for r in strings("required") {
                match obj.get(r) {
                    Some(Json::Null) if nullable(r) => {}
                    None | Some(Json::Null) => {
                        return Err(Invalid(format!("{path} must have the property \"{r}\"")));
                    }
                    _ => {}
                }
            }
            for (k, pdef) in def["properties"].as_object().into_iter().flatten() {
                match obj.get(k) {
                    None => {}
                    Some(Json::Null) if nullable(k) => {}
                    Some(v) => validate(nsid, pdef, v, &format!("{path}/{k}"))?,
                }
            }
            Ok(())
        }
        "string" => {
            let Some(s) = value.as_str() else {
                return bad("a string");
            };
            if def["maxLength"]
                .as_u64()
                .is_some_and(|m| s.len() as u64 > m)
            {
                return bad(&format!("no longer than {} characters", def["maxLength"]));
            }
            if def["minLength"]
                .as_u64()
                .is_some_and(|m| (s.len() as u64) < m)
            {
                return bad(&format!("no shorter than {} characters", def["minLength"]));
            }
            let (max_g, min_g) = (def["maxGraphemes"].as_u64(), def["minGraphemes"].as_u64());
            if max_g.is_some() || min_g.is_some() {
                let n = s.graphemes(true).count() as u64;
                if max_g.is_some_and(|m| n > m) {
                    return bad(&format!("no longer than {} graphemes", def["maxGraphemes"]));
                }
                if min_g.is_some_and(|m| n < m) {
                    return bad(&format!(
                        "no shorter than {} graphemes",
                        def["minGraphemes"]
                    ));
                }
            }
            match def["format"].as_str() {
                Some(f) if !valid_format(f, s) => bad(&format!("a valid {f}")),
                _ => Ok(()),
            }
        }
        "integer" => {
            let Some(n) = value.as_i64() else {
                return bad("an integer");
            };
            if def["minimum"].as_i64().is_some_and(|m| n < m)
                || def["maximum"].as_i64().is_some_and(|m| n > m)
            {
                return bad(&format!(
                    "in the range {}..={}",
                    def["minimum"], def["maximum"]
                ));
            }
            Ok(())
        }
        "boolean" if value.is_boolean() => Ok(()),
        "boolean" => bad("a boolean"),
        "array" => {
            let Some(items) = value.as_array() else {
                return bad("an array");
            };
            if def["maxLength"]
                .as_u64()
                .is_some_and(|m| items.len() as u64 > m)
            {
                return bad(&format!("no more than {} elements", def["maxLength"]));
            }
            if def["minLength"]
                .as_u64()
                .is_some_and(|m| (items.len() as u64) < m)
            {
                return bad(&format!("no fewer than {} elements", def["minLength"]));
            }
            for (i, v) in items.iter().enumerate() {
                validate(nsid, &def["items"], v, &format!("{path}/{i}"))?;
            }
            Ok(())
        }
        "ref" => {
            let r = def["ref"].as_str().unwrap_or_default();
            let (target, id) = resolve(nsid, r)
                .ok_or_else(|| Invalid(format!("{path}: no lexicon defines {r}")))?;
            // An object a ref names may leave out its `$type`, but may not name another.
            let full = full_ref(nsid, r);
            if target["type"] == "object"
                && value
                    .get("$type")
                    .is_some_and(|t| t.as_str().map(main_stripped) != Some(main_stripped(&full)))
            {
                return bad(&format!("an object of type {}", main_stripped(&full)));
            }
            validate(id, target, value, path)
        }
        "union" => {
            let Some(t) = value.get("$type").and_then(Json::as_str) else {
                return bad("an object which includes the \"$type\" property");
            };
            let t = main_stripped(t);
            match strings("refs").find(|r| main_stripped(&full_ref(nsid, r)) == t) {
                Some(r) => {
                    let (target, id) = resolve(nsid, r)
                        .ok_or_else(|| Invalid(format!("{path}: no lexicon defines {r}")))?;
                    validate(id, target, value, path)
                }
                None if def["closed"].as_bool() == Some(true) => bad(&format!(
                    "an object of type {}",
                    strings("refs")
                        .map(|r| full_ref(nsid, r))
                        .collect::<Vec<_>>()
                        .join(", ")
                )),
                None => Ok(()),
            }
        }
        "blob" => {
            let Some((mime, size)) = blob_ref(value) else {
                return bad("a blob ref");
            };
            if def["accept"].as_array().is_some_and(|a| !accepts(a, mime)) {
                return bad(&format!("a blob of a type in {}", def["accept"]));
            }
            if def["maxSize"].as_u64().is_some_and(|m| size > m) {
                return bad(&format!("a blob of at most {} bytes", def["maxSize"]));
            }
            Ok(())
        }
        "unknown" if value.is_object() => Ok(()),
        "unknown" => bad("an object"),
        "cid-link"
            if value
                .get("$link")
                .and_then(Json::as_str)
                .is_some_and(pds_repo::data::valid_cid_string) =>
        {
            Ok(())
        }
        "cid-link" => bad("a CID link"),
        "bytes"
            if value
                .as_object()
                .is_some_and(|o| o.len() == 1 && o.get("$bytes").is_some_and(Json::is_string)) =>
        {
            Ok(())
        }
        "bytes" => bad("bytes"),
        _ => Ok(()),
    }
}

/// The namespaces of the spaces' lexicons (`spec/SPACES.md`): their records
/// are a space's, not a repository's, and no record type of a repository.
const SPACE_NAMESPACES: [&str; 4] = [
    "com.atproto.space.",
    "com.atproto.memberspace.",
    "com.atproto.personalspace.",
    "com.atproto.managedspace.",
];

/// The lexicon of a record type the server knows: its `main` definition, a
/// `record`, of a lexicon not the spaces'.
fn record_def(nsid: &str) -> Option<&'static Json> {
    if SPACE_NAMESPACES.iter().any(|ns| nsid.starts_with(ns)) {
        return None;
    }
    DOCS.get(nsid)
        .map(|d| &d["defs"]["main"])
        .filter(|m| m["type"] == "record")
}

/// Whether the server knows a lexicon for this record type.
pub fn knows_record(nsid: &str) -> bool {
    record_def(nsid).is_some()
}

/// Check a record of a type the server knows, and the key it is written
/// at (`None` for a TID the server makes), against the type's lexicon:
/// first the key, as its `key` says, then the record, as its JSON form.
pub fn check_record(nsid: &str, rkey: Option<&str>, record: &Json) -> Result<(), Invalid> {
    let def = record_def(nsid).ok_or_else(|| Invalid(format!("Lexicon not found: {nsid}")))?;
    let key = def["key"].as_str().unwrap_or("any");
    let key_ok = match (key, rkey) {
        ("any", _) | ("tid", None) => true,
        ("tid", Some(k)) => pds_repo::valid_tid(k),
        ("nsid", Some(k)) => pds_repo::data::valid_nsid(k),
        (literal, k) => literal
            .strip_prefix("literal:")
            .is_some_and(|l| k == Some(l)),
    };
    if !key_ok {
        return Err(Invalid(format!(
            "Record key must be a valid record key of the type {key}"
        )));
    }
    validate(nsid, def, record, "Record")
}

/// The ref of a union that a value's `$type` names, if any.
fn union_ref<'d>(nsid: &str, def: &'d Json, value: &Json) -> Option<&'d str> {
    let t = main_stripped(value.get("$type")?.as_str()?);
    def["refs"]
        .as_array()?
        .iter()
        .filter_map(Json::as_str)
        .find(|r| main_stripped(&full_ref(nsid, r)) == t)
}

/// Fill in `value`, which `def` in lexicon `nsid` defines, with the values
/// the definition gives a `default` for, where they are missing, at any depth.
pub fn fill_defaults(nsid: &str, def: &Json, value: &mut Json) {
    match def["type"].as_str() {
        Some("object" | "params") => {
            let Some(obj) = value.as_object_mut() else {
                return;
            };
            for (k, pdef) in def["properties"].as_object().into_iter().flatten() {
                if let Some(v) = obj.get_mut(k) {
                    fill_defaults(nsid, pdef, v);
                } else if let Some(d) = pdef.get("default") {
                    obj.insert(k.clone(), d.clone());
                }
            }
        }
        Some("array") => {
            for v in value.as_array_mut().into_iter().flatten() {
                fill_defaults(nsid, &def["items"], v);
            }
        }
        Some("ref") => {
            if let Some((target, id)) = resolve(nsid, def["ref"].as_str().unwrap_or_default()) {
                fill_defaults(id, target, value);
            }
        }
        Some("union") => {
            if let Some((target, id)) = union_ref(nsid, def, value).and_then(|r| resolve(nsid, r)) {
                fill_defaults(id, target, value);
            }
        }
        _ => {}
    }
}

fn type_of(p: &Json) -> Type {
    match p["type"].as_str() {
        Some("string") => Type::String,
        Some("integer") => Type::Integer,
        Some("boolean") => Type::Boolean,
        Some("array") => Type::Array,
        Some("unknown" | "bytes" | "cid-link" | "blob") => Type::Unknown,
        _ => Type::Object,
    }
}

/// The JSON Schema of a value; one the lexicon lists as `nullable` may also be `null`.
fn schema_of(p: &Json, ty: Type, nullable: bool) -> Json {
    let mut s = Map::new();
    match ty {
        Type::String => {
            s.insert("type".into(), json!("string"));
        }
        Type::Integer => {
            s.insert("type".into(), json!("integer"));
        }
        Type::Boolean => {
            s.insert("type".into(), json!("boolean"));
        }
        Type::Array => {
            s.insert("type".into(), json!("array"));
            let items = &p["items"];
            if items.is_object() {
                s.insert("items".into(), schema_of(items, type_of(items), false));
            }
            // A lexicon array's `maxLength` counts its elements.
            if let Some(n) = p.get("maxLength") {
                s.insert("maxItems".into(), n.clone());
            }
        }
        Type::Object => {
            s.insert("type".into(), json!("object"));
        }
        Type::Unknown => {}
    }
    if nullable && let Some(t) = s.remove("type") {
        s.insert("type".into(), json!([t, "null"]));
    }
    if matches!(ty, Type::String | Type::Integer) {
        for (from, to) in [
            ("minimum", "minimum"),
            ("maximum", "maximum"),
            ("maxLength", "maxLength"),
            ("enum", "enum"),
        ] {
            if let Some(v) = p.get(from) {
                s.insert(to.into(), v.clone());
            }
        }
    }
    if let Some(d) = p["description"].as_str() {
        s.insert("description".into(), json!(d));
    }
    Json::Object(s)
}

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

    #[test]
    fn names() {
        let m = method("com.atproto.repo.createRecord").unwrap();
        assert_eq!(
            (m.group.as_str(), m.name.as_str()),
            ("repo", "createRecord")
        );
        assert_eq!(m.tool().as_deref(), Some("repo_create_record"));
        assert_eq!(m.command().as_deref(), Some("create-record"));
        assert_eq!(m.arg("swapCommit").unwrap().flag(), "swap-commit");
        assert_eq!(by_command("repo", "create-record").unwrap().nsid, m.nsid);
        assert_eq!(by_tool("repo_create_record").unwrap().nsid, m.nsid);
    }

    #[test]
    fn which_methods() {
        // A method whose answer is a CAR file is a command and no tool.
        for (nsid, command) in [
            ("com.atproto.sync.getRepo", "get-repo"),
            ("com.atproto.sync.getBlocks", "get-blocks"),
            ("com.atproto.sync.getRecord", "get-record"),
        ] {
            let m = method(nsid).unwrap();
            assert_eq!(
                (m.tool(), m.command().as_deref()),
                (None, Some(command)),
                "{nsid}"
            );
        }
        let sub = method("com.atproto.sync.subscribeRepos").unwrap();
        assert_eq!((sub.tool(), sub.command()), (None, None));
        // A method that answers nothing has a tool too.
        let delete = method("com.atproto.server.deleteSession").unwrap();
        assert_eq!(
            (
                delete.tool().as_deref(),
                delete.output.as_deref(),
                delete.input.as_deref()
            ),
            (Some("server_delete_session"), None, None)
        );
        let tools: Vec<String> = methods().iter().filter_map(Method::tool).collect();
        assert_eq!(tools.len(), 79, "{tools:?}");
        // The methods of a move are tools, but `importRepo`, whose input is a CAR file.
        for t in [
            "repo_list_missing_blobs",
            "identity_submit_plc_operation",
            "identity_request_plc_operation_signature",
            "identity_sign_plc_operation",
        ] {
            assert!(tools.contains(&t.to_string()), "{t}");
        }
        assert!(
            tools.contains(&"server_delete_account".to_string())
                && tools.contains(&"admin_update_subject_status".to_string())
        );
        assert!(
            tools.contains(&"server_request_password_reset".to_string())
                && tools.contains(&"server_update_email".to_string())
        );
        assert!(tools.contains(&"space_list_blobs".to_string()));
        assert!(
            tools.contains(&"space_notify_repo_update".to_string())
                && tools.contains(&"space_list_writers".to_string())
                && tools.contains(&"space_authorize_space_sync".to_string())
                && tools.contains(&"space_notify_credentials_revoked".to_string())
        );
        assert!(
            tools.contains(&"sync_list_repos".to_string())
                && tools.contains(&"sync_get_repo_status".to_string())
        );
        assert!(
            tools.contains(&"space_create_space".to_string())
                && tools.contains(&"memberspace_put_members".to_string())
                && tools.contains(&"memberspace_remove_members".to_string())
        );
        // uploadBlob's input and getBlob's answer are bytes: neither has a tool, both a command;
        // nor have importRepo's CAR file, a space meta archive's export and import, a space
        // repo's archive and import, or a space blob.
        for nsid in [
            "com.atproto.repo.uploadBlob",
            "com.atproto.repo.importRepo",
            "com.atproto.sync.getBlob",
            "com.atproto.space.exportSpaceMeta",
            "com.atproto.space.importSpaceMeta",
            "com.atproto.space.getRepo",
            "com.atproto.space.getBlob",
            "com.atproto.space.importRepo",
        ] {
            let m = method(nsid).unwrap();
            assert_eq!((m.tool(), m.command().is_some()), (None, true), "{nsid}");
        }
        assert!(method("com.atproto.repo.uploadBlob").unwrap().raw_input());
        assert!(
            method("com.atproto.space.importSpaceMeta")
                .unwrap()
                .raw_input()
        );
        assert!(method("com.atproto.space.importRepo").unwrap().raw_input());
        assert!(!method("com.atproto.repo.createRecord").unwrap().raw_input());
        assert_eq!(
            groups(),
            [
                "actor",
                "admin",
                "feed",
                "identity",
                "memberspace",
                "notification",
                "repo",
                "server",
                "space",
                "sync"
            ]
        );
        assert!(method("com.atproto.repo.defs").is_none());
        assert!(method("com.atproto.space.policy").is_none());
    }

    #[test]
    fn space_refs_are_checked() {
        let m = method("com.atproto.space.getSpace").unwrap();
        assert!(
            m.parse_params([("space", "at://did:plc:abc/space/com.example.forum/main")])
                .is_ok()
        );
        for bad in [
            "at://did:plc:abc/space/com.example.forum",
            "at://alice.test/space/com.example.forum/main",
            "nope",
        ] {
            assert!(m.parse_params([("space", bad)]).is_err(), "{bad}");
        }
    }

    /// `deactivateAccount`'s `deleteAfter` is held to its datetime format
    /// (`format.rs`).
    #[test]
    fn delete_after_is_a_datetime() {
        let m = method("com.atproto.server.deactivateAccount").unwrap();
        assert!(
            m.check_input(&json!({ "deleteAfter": "tomorrow" }))
                .is_err()
        );
        assert!(
            m.check_input(&json!({ "deleteAfter": "2030-01-01T00:00:00.000Z" }))
                .is_ok()
        );
    }

    #[test]
    fn input_schema() {
        let m = method("com.atproto.repo.listRecords").unwrap();
        let s = m.input_schema();
        assert_eq!(s["required"], json!(["collection"]));
        assert_eq!(s["properties"]["limit"]["type"], "integer");
        assert_eq!(s["properties"]["limit"]["minimum"], 1);
        assert_eq!(s["properties"]["limit"]["maximum"], 100);
        assert_eq!(s["properties"]["reverse"]["type"], "boolean");
        assert_eq!(m.annotations(), Some(json!({ "readOnlyHint": true })));
        let w = method("com.atproto.repo.applyWrites")
            .unwrap()
            .input_schema();
        assert_eq!(w["properties"]["writes"]["type"], "array");
        assert_eq!(w["properties"]["writes"]["items"]["type"], "object");
        let c = method("com.atproto.repo.createRecord")
            .unwrap()
            .input_schema();
        assert!(c["properties"]["record"].get("type").is_none());
        assert_eq!(c["properties"]["rkey"]["maxLength"], 512);
        // An array's `maxLength` is its `maxItems`.
        let a = method("app.bsky.actor.getProfiles").unwrap().input_schema();
        assert_eq!(
            (
                a["properties"]["actors"]["maxItems"].clone(),
                a["properties"]["actors"].get("maxLength")
            ),
            (json!(25), None)
        );
        let p = method("com.atproto.repo.putRecord").unwrap().input_schema();
        assert_eq!(
            p["properties"]["swapRecord"]["type"],
            json!(["string", "null"])
        );
        assert_eq!(p["properties"]["swapCommit"]["type"], "string");
        // A required `repo` or `did` names the account, which a token may give;
        // `createAccount`'s optional `did` does not.
        assert_eq!(p["required"], json!(["collection", "record", "rkey"]));
        assert_eq!(
            method("com.atproto.sync.getRepo").unwrap().input_schema()["required"],
            json!([])
        );
        let n = method("com.atproto.space.notifyRepoUpdate")
            .unwrap()
            .input_schema();
        assert!(n["properties"]["data"].get("type").is_none());
        let create = method("com.atproto.server.createAccount").unwrap();
        assert!(!create.arg("did").unwrap().names_account());
        assert_eq!(create.input_schema()["required"], json!(["handle"]));
    }

    /// Hints by what a method does (`spec/COMMANDS.md`, "Hints"): a query
    /// reads but for the two that sign a token; a procedure destroys
    /// unless it is listed as only adding.
    #[test]
    fn hints() {
        let hints = |nsid: &str| method(nsid).unwrap().annotations();
        let destroys = Some(json!({ "readOnlyHint": false, "destructiveHint": true }));
        let adds = Some(json!({ "readOnlyHint": false, "destructiveHint": false }));
        for nsid in [
            "com.atproto.repo.deleteRecord",
            "com.atproto.repo.putRecord",
            "com.atproto.repo.applyWrites",
            "com.atproto.space.deleteRecord",
            "com.atproto.space.clearRecords",
            "com.atproto.memberspace.putMembers",
            "com.atproto.server.deleteSession",
            "com.atproto.identity.updateHandle",
            "app.bsky.actor.putPreferences",
        ] {
            assert_eq!(hints(nsid), destroys, "{nsid}");
        }
        for nsid in [
            "com.atproto.repo.createRecord",
            "com.atproto.server.createSession",
            "com.atproto.space.createRecord",
            "com.atproto.server.getServiceAuth",
            "com.atproto.space.getDelegationToken",
        ] {
            assert_eq!(hints(nsid), adds, "{nsid}");
        }
        assert_eq!(
            hints("com.atproto.repo.listRecords"),
            Some(json!({ "readOnlyHint": true }))
        );
        assert_eq!(hints("com.atproto.sync.subscribeRepos"), None);
        // Each listed is a method served, of the kind its list is for.
        for nsid in ADDITIVE {
            assert_eq!(
                method(nsid).map(|m| m.kind),
                Some(Kind::Procedure),
                "{nsid}"
            );
        }
        for nsid in SIGNS {
            assert_eq!(method(nsid).map(|m| m.kind), Some(Kind::Query), "{nsid}");
        }
    }

    /// A tool's title is its command's name in words, then its group
    /// (`spec/COMMANDS.md`, "Names"); no group is `xrpc`.
    #[test]
    fn titles() {
        let title_of = |nsid: &str| method(nsid).unwrap().title();
        assert_eq!(
            title_of("com.atproto.identity.getRecommendedDidCredentials"),
            "Get recommended did credentials (identity)"
        );
        assert_eq!(
            title_of("com.atproto.repo.createRecord"),
            "Create record (repo)"
        );
        assert_eq!(title("admin", "logs"), "Logs (admin)");
        assert_eq!(title("oauth", "revoke-session"), "Revoke session (oauth)");
        assert!(!groups().contains(&"xrpc"));
    }

    #[test]
    fn params_are_typed_and_checked() {
        let m = method("com.atproto.repo.listRecords").unwrap();
        let p = m
            .parse_params([
                ("repo", "alice.test"),
                ("collection", "com.example.note"),
                ("reverse", "true"),
                ("x", "y"),
            ])
            .unwrap();
        assert_eq!(p, json!({ "repo": "alice.test", "collection": "com.example.note", "reverse": true, "limit": 50 }).as_object().unwrap().clone());
        let list = |extra: (&'static str, &'static str)| {
            m.parse_params([
                ("repo", "alice.test"),
                ("collection", "com.example.note"),
                extra,
            ])
        };
        assert_eq!(list(("limit", "+5")).unwrap()["limit"], 5);
        for bad in [
            ("limit", "0"),
            ("limit", "101"),
            ("limit", "x"),
            ("reverse", "yes"),
            ("collection", "not an nsid"),
        ] {
            assert!(
                m.parse_params([
                    ("repo", "alice.test"),
                    bad,
                    ("collection", "com.example.note")
                ])
                .is_err(),
                "{bad:?}"
            );
        }
        assert!(m.parse_params([("repo", "alice.test")]).is_err());
        let get_repo = method("com.atproto.sync.getRepo").unwrap();
        assert!(
            get_repo
                .parse_params([("did", "did:plc:abc"), ("since", "notarev")])
                .is_err()
        );
        assert!(
            get_repo
                .parse_params([("did", "did:plc:abc"), ("since", "3jzfcijpj2z2a")])
                .is_ok()
        );
    }

    #[test]
    fn input_is_checked() {
        let m = method("com.atproto.repo.applyWrites").unwrap();
        let write = |t: &str, rkey: &str| json!({ "repo": "alice.test", "writes": [{ "$type": t, "collection": "com.example.note", "rkey": rkey }] });
        m.check_input(&write("com.atproto.repo.applyWrites#delete", "a"))
            .unwrap();
        assert!(
            m.check_input(&write("com.atproto.repo.applyWrites#delete", "a b"))
                .is_err()
        );
        assert!(
            m.check_input(&write("com.atproto.repo.applyWrites#nope", "a"))
                .is_err()
        );
        assert!(
            m.check_input(&write("com.atproto.repo.applyWrites#create", "a"))
                .is_err(),
            "a create needs its value"
        );
        let put = method("com.atproto.repo.putRecord").unwrap();
        let body = json!({ "repo": "alice.test", "collection": "com.example.note", "rkey": "a", "record": {}, "swapRecord": null });
        put.check_input(&body).unwrap();
        let del = method("com.atproto.repo.deleteRecord").unwrap();
        assert!(del.check_input(&json!({ "repo": "alice.test", "collection": "com.example.note", "rkey": "a", "swapRecord": null })).is_err());
        assert!(put.check_input(&json!({ "repo": "alice.test", "collection": "com.example.note", "rkey": "a", "record": 5 })).is_err());
        assert!(put.check_input(&json!({ "repo": "alice.test", "collection": "com.example.note", "rkey": "x".repeat(513), "record": {} })).is_err());
        let space = method("com.atproto.space.createRecord").unwrap();
        let body = |s: &str| json!({ "space": s, "repo": "did:plc:abc", "collection": "com.example.note", "record": {} });
        space
            .check_input(&body("at://did:plc:abc/space/com.example.forum/main"))
            .unwrap();
        for bad in [
            "at://alice.test/space/com.example.forum/main",
            "at://did:plc:abc/space/com.example.forum",
            "did:plc:abc",
        ] {
            assert!(space.check_input(&body(bad)).is_err(), "{bad}");
        }
    }

    #[test]
    fn preferences_are_checked_with_defaults() {
        let m = method("app.bsky.actor.putPreferences").unwrap();
        let prefs = |p: Json| json!({ "preferences": [p] });
        // A default fills in a required field left out, at depth.
        let mut input = prefs(json!({ "$type": "app.bsky.actor.defs#adultContentPref" }));
        assert!(m.check_input(&input).is_err());
        m.fill_input_defaults(&mut input);
        m.check_input(&input).unwrap();
        assert_eq!(input["preferences"][0]["enabled"], false);
        let mut feed =
            prefs(json!({ "$type": "app.bsky.actor.defs#feedViewPref", "feed": "home" }));
        m.fill_input_defaults(&mut feed);
        assert_eq!(feed["preferences"][0]["hideRepliesByUnfollowed"], true);
        // Formats, lengths and graphemes.
        let birth = |d: &str| {
            prefs(json!({ "$type": "app.bsky.actor.defs#personalDetailsPref", "birthDate": d }))
        };
        m.check_input(&birth("1990-05-01T00:00:00.000Z")).unwrap();
        assert!(m.check_input(&birth("1990-05-01")).is_err());
        let tags =
            |t: &str| prefs(json!({ "$type": "app.bsky.actor.defs#interestsPref", "tags": [t] }));
        m.check_input(&tags(&"👍🏽".repeat(64))).unwrap();
        assert!(m.check_input(&tags(&"a".repeat(65))).is_err());
        // Other types are taken as they are; an item needs a `$type`.
        m.check_input(&prefs(json!({ "$type": "app.bsky.x y", "z": 1 })))
            .unwrap();
        assert!(m.check_input(&prefs(json!({ "z": 1 }))).is_err());
        assert!(m.check_input(&prefs(json!(5))).is_err());
    }

    #[test]
    fn output_is_checked() {
        let m = method("com.atproto.repo.getRecord").unwrap();
        m.check_output(&json!({ "uri": "at://did:plc:x/a.b.c/k", "value": {} }))
            .unwrap();
        assert!(
            m.check_output(&json!({ "uri": "at://did:plc:x/a.b.c/k" }))
                .is_err()
        );
        assert!(
            m.check_output(&json!({ "uri": "http://x", "value": {} }))
                .is_err()
        );
        method("com.atproto.server.deleteSession")
            .unwrap()
            .check_output(&json!(5))
            .unwrap();
    }

    const POST: &str = "app.bsky.feed.post";

    fn post(extra: Json) -> Json {
        let mut p = json!({ "$type": POST, "text": "hi", "createdAt": "2024-01-01T00:00:00Z" });
        p.as_object_mut()
            .unwrap()
            .extend(extra.as_object().unwrap().clone());
        p
    }

    fn ok(nsid: &str, record: &Json) -> bool {
        check_record(nsid, None, record).is_ok()
    }

    /// A blob ref of `mime` and `size`, linking a CID of `codec`.
    fn blob(codec: u8, mime: &str, size: i64) -> Json {
        json!({ "$type": "blob", "ref": { "$link": pds_repo::data::cid_string(&pds_repo::data::cid_of(codec, b"x")) }, "mimeType": mime, "size": size })
    }

    #[test]
    fn which_records() {
        let known: Vec<&String> = DOCS.keys().filter(|k| knows_record(k)).collect();
        assert_eq!(known.len(), 36, "{known:?}");
        assert!(knows_record(POST) && knows_record("social.grain.photo"));
        assert!(!knows_record("com.atproto.repo.strongRef") && !knows_record("com.example.note"));
        for not_a_record in [
            "app.bsky.embed.images",
            "app.bsky.feed.defs",
            "app.bsky.feed.getTimeline",
            "app.bsky.feed.unknownthing",
            "com.atproto.space.policy",
            "com.atproto.memberspace.member",
        ] {
            assert!(!knows_record(not_a_record), "{not_a_record}");
        }
    }

    #[test]
    fn record_keys() {
        let tid = "3jzfcijpj2z2a";
        assert!(check_record(POST, Some(tid), &post(json!({}))).is_ok());
        assert!(check_record(POST, None, &post(json!({}))).is_ok());
        for bad in ["self", "3jzfcijpj2z2", "3JZFCIJPJ2Z2A", "kjzfcijpj2z2a"] {
            assert!(
                check_record(POST, Some(bad), &post(json!({}))).is_err(),
                "{bad}"
            );
        }
        let profile = json!({ "$type": "app.bsky.actor.profile" });
        assert!(check_record("app.bsky.actor.profile", Some("self"), &profile).is_ok());
        for bad in [Some("Self"), Some(tid), None] {
            assert!(
                check_record("app.bsky.actor.profile", bad, &profile).is_err(),
                "{bad:?}"
            );
        }
        let generator = json!({ "did": "did:web:x.test", "displayName": "g", "createdAt": "2024-01-01T00:00:00Z" });
        for any in [Some("anything-at:all"), Some("self"), None] {
            assert!(
                check_record("app.bsky.feed.generator", any, &generator).is_ok(),
                "{any:?}"
            );
        }
        let schema = json!({ "lexicon": 1 });
        assert!(
            check_record(
                "com.atproto.lexicon.schema",
                Some("com.example.thing"),
                &schema
            )
            .is_ok()
        );
        for bad in [Some("not-an-nsid"), Some(tid), None] {
            assert!(
                check_record("com.atproto.lexicon.schema", bad, &schema).is_err(),
                "{bad:?}"
            );
        }
    }

    #[test]
    fn objects() {
        assert!(ok(POST, &post(json!({ "unnamed": { "deep": [1, null] } }))));
        assert!(!ok(POST, &json!({ "text": "hi" })), "required createdAt");
        assert!(!ok(POST, &post(json!({ "createdAt": null }))));
        assert!(!ok(POST, &post(json!({ "text": 5 }))));
        assert!(
            !ok(POST, &post(json!({ "langs": null }))),
            "an optional field may not be null either"
        );
        assert!(!ok(POST, &post(json!({ "reply": "x" }))));
    }

    #[test]
    fn nested_types() {
        let strong = json!({ "uri": "at://did:plc:abc/app.bsky.feed.post/3jzfcijpj2z2a", "cid": pds_repo::data::cid_string(&pds_repo::data::cid_of(0x71, b"x")) });
        let reply = |t: Option<&str>, root_t: Option<&str>| {
            let mut root = strong.clone();
            if let Some(rt) = root_t {
                root["$type"] = json!(rt);
            }
            let mut r = json!({ "root": root, "parent": strong });
            if let Some(t) = t {
                r["$type"] = json!(t);
            }
            post(json!({ "reply": r }))
        };
        assert!(ok(POST, &reply(None, None)));
        assert!(ok(
            POST,
            &reply(
                Some("app.bsky.feed.post#replyRef"),
                Some("com.atproto.repo.strongRef")
            )
        ));
        assert!(!ok(POST, &reply(Some("app.bsky.feed.post#entity"), None)));
        assert!(!ok(POST, &reply(None, Some("app.bsky.feed.post#replyRef"))));
        let mut odd = reply(None, None);
        odd["reply"]["$type"] = json!({ "a": 1 });
        assert!(!ok(POST, &odd), "a nested $type that is not a string");
    }

    #[test]
    fn unions() {
        let image = json!({ "image": blob(0x55, "image/png", 10), "alt": "" });
        assert!(ok(
            POST,
            &post(json!({ "embed": { "$type": "app.bsky.embed.images", "images": [image] } }))
        ));
        assert!(
            !ok(
                POST,
                &post(
                    json!({ "embed": { "$type": "app.bsky.embed.images", "images": [{ "alt": "" }] } })
                )
            ),
            "a member broken inside"
        );
        assert!(
            !ok(POST, &post(json!({ "embed": { "images": [image] } }))),
            "no $type"
        );
        assert!(!ok(POST, &post(json!({ "embed": { "$type": 5 } }))));
        assert!(!ok(
            POST,
            &post(json!({ "embed": "app.bsky.embed.images" }))
        ));
        assert!(
            ok(
                POST,
                &post(json!({ "embed": { "$type": "app.bsky.embed.images#view", "nonsense": 1 } }))
            ),
            "a definition it does not name"
        );
        assert!(
            ok(POST, &post(json!({ "embed": { "$type": "not a type!" } }))),
            "a type that names nothing"
        );
    }

    #[test]
    fn strings() {
        let family = "\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}\u{200D}\u{1F466}";
        let flag = "\u{1F1EB}\u{1F1F7}";
        let accent = "e\u{301}";
        for (unit, n) in [
            ("a", 300),
            (family, 300),
            (flag, 300),
            (accent, 300),
            ("é", 300),
        ] {
            assert!(
                ok(POST, &post(json!({ "text": unit.repeat(n) }))) == (unit.len() * n <= 3000),
                "{unit:?}"
            );
            assert!(
                !ok(POST, &post(json!({ "text": unit.repeat(n + 1) }))),
                "{unit:?} × {}",
                n + 1
            );
        }
        assert!(
            !ok(POST, &post(json!({ "text": "é".repeat(1501) }))),
            "3002 bytes"
        );
        let germ =
            |version: &str| json!({ "version": version, "currentKey": { "$bytes": "AQID" } });
        assert!(check_record("com.germnetwork.declaration", Some("self"), &germ("1.0.0")).is_ok());
        assert!(
            check_record("com.germnetwork.declaration", Some("self"), &germ("1.0")).is_err(),
            "minLength"
        );
        let threadgate = json!({ "post": "at://did:plc:abc/app.bsky.feed.post/3jzfcijpj2z2a", "createdAt": "2024-01-01T00:00:00Z" });
        assert!(ok("app.bsky.feed.threadgate", &threadgate));
        let label = |v: &str| {
            post(
                json!({ "labels": { "$type": "com.atproto.label.defs#selfLabels", "values": [{ "val": v }] } }),
            )
        };
        assert!(
            ok(POST, &label("not one of its known values")),
            "knownValues are not enforced"
        );
        for (field, good, bad) in [
            ("createdAt", "2023-02-30T00:00:00Z", "2023-02-03T00:00:60Z"),
            (
                "createdAt",
                "1985-04-12T23:20:50.123-07:00",
                "1985-04-12T23:20:50.123-00:00",
            ),
        ] {
            assert!(ok(POST, &post(json!({ field: good }))), "{good}");
            assert!(!ok(POST, &post(json!({ field: bad }))), "{bad}");
        }
        assert!(ok(POST, &post(json!({ "langs": ["en", "pt-BR"] }))));
        assert!(!ok(POST, &post(json!({ "langs": ["de-DE-1901-1901"] }))));
        let follow = |s: &str| json!({ "subject": s, "createdAt": "2024-01-01T00:00:00Z" });
        assert!(ok("app.bsky.graph.follow", &follow("did:example:x")));
        assert!(!ok("app.bsky.graph.follow", &follow("alice.test")));
    }

    #[test]
    fn numbers_and_arrays() {
        let image = |w: i64| json!({ "image": blob(0x55, "image/png", 10), "alt": "", "aspectRatio": { "width": w, "height": 1 } });
        let embed = |images: Vec<Json>| {
            post(json!({ "embed": { "$type": "app.bsky.embed.images", "images": images } }))
        };
        assert!(ok(POST, &embed(vec![image(1)])));
        assert!(!ok(POST, &embed(vec![image(0)])), "below minimum");
        assert!(ok(POST, &embed(vec![image(1); 4])));
        assert!(!ok(POST, &embed(vec![image(1); 5])), "over maxLength");
        assert!(!ok(
            POST,
            &post(json!({ "langs": ["en", "fr", "de", "es"] }))
        ));
        let list = |purpose: Json| json!({ "purpose": purpose, "name": "n", "createdAt": "2024-01-01T00:00:00Z" });
        assert!(ok(
            "app.bsky.graph.list",
            &list(json!("app.bsky.graph.defs#curatelist"))
        ));
        assert!(!ok("app.bsky.graph.list", &list(json!(true))));
    }

    #[test]
    fn bytes() {
        let germ = |key: Json| json!({ "version": "1.0.0", "currentKey": key });
        let check =
            |k: Json| check_record("com.germnetwork.declaration", Some("self"), &germ(k)).is_ok();
        assert!(check(json!({ "$bytes": "" })), "empty bytes");
        assert!(check(json!({ "$bytes": "AQID" })));
        assert!(!check(json!("AQID")), "a string is not bytes");
        assert!(
            !check(
                json!({ "$link": pds_repo::data::cid_string(&pds_repo::data::cid_of(0x55, b"x")) })
            ),
            "nor is a link"
        );
    }

    #[test]
    fn blobs() {
        let profile = |avatar: Json| json!({ "avatar": avatar });
        let check =
            |b: Json| check_record("app.bsky.actor.profile", Some("self"), &profile(b)).is_ok();
        assert!(check(blob(0x55, "image/png", 1_000_000)));
        assert!(!check(blob(0x55, "image/png", 1_000_001)), "over maxSize");
        assert!(!check(blob(0x55, "image/gif", 10)), "not accepted");
        assert!(!check(blob(0x55, "IMAGE/PNG", 10)), "case and all");
        assert!(
            !check(blob(0x55, "image/png", -1)),
            "size -1 is no blob here"
        );
        assert!(!check(blob(0x71, "image/png", 10)), "a dag-cbor link");
        let mut no_type = blob(0x55, "image/png", 10);
        no_type.as_object_mut().unwrap().remove("$type");
        assert!(!check(no_type));
        let mut extra = blob(0x55, "image/png", 10);
        extra["x"] = json!(1);
        assert!(!check(extra));
        let legacy = json!({ "cid": pds_repo::data::cid_string(&pds_repo::data::cid_of(0x55, b"x")), "mimeType": "image/png" });
        assert!(!check(legacy), "the legacy shape");
        // `image/*` takes any `image/` type, `image/` too, but not `imagex/png`.
        let image = |mime: &str| {
            post(
                json!({ "embed": { "$type": "app.bsky.embed.images", "images": [{ "image": blob(0x55, mime, 10), "alt": "" }] } }),
            )
        };
        for (mime, want) in [
            ("image/gif", true),
            ("image/", true),
            ("IMAGE/PNG", false),
            ("imagex/png", false),
            ("text/plain", false),
        ] {
            assert_eq!(ok(POST, &image(mime)), want, "{mime}");
        }
    }
}