Something went wrong. Try again.
A human-friendly DSL for ATProto Lexicons forked from stavola.xyz/mlf
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311//! JSON message envelope shared by host and plugin.//!//! Every exchange is one line of JSON per message://!//! - Host → Plugin: a [`Request`] — `{"op": "...", ...params}`.//! - Plugin → Host (non-terminal): an [`Ask`] — `{"ask": "...", ...}`//! asking the host to render a UI element and reply with an//! [`Answer`] or [`Ack`].//! - Plugin → Host (terminal): a [`Terminal`] — either//! `{"ok": true, "data": ...}` or `{"ok": false, "error": {...}}`.
use serde::{Deserialize, Serialize};use serde_json::Value;
// ---------------------------------------------------------------------------// Handshake// ---------------------------------------------------------------------------
/// The handshake request. Always the first message the host sends.#[derive(Debug, Clone, Serialize, Deserialize)]pub struct Hello { pub op: HelloOp, pub protocol_version: u32,}
impl Hello { pub fn new(protocol_version: u32) -> Self { Self { op: HelloOp::Hello, protocol_version, } }}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]#[serde(rename_all = "snake_case")]pub enum HelloOp { Hello,}
/// Plugin's response to `hello`: its identity, protocol version, what/// ops it can service, and the schema of options (credentials +/// configuration) the host should collect before calling authed ops.#[derive(Debug, Clone, Serialize, Deserialize)]pub struct HelloData { pub name: String, pub protocol_version: u32, #[serde(default)] pub kind: Option<String>, #[serde(default)] pub capabilities: Vec<String>, #[serde(default)] pub options_schema: Vec<OptionField>,}
/// One field in a plugin's options schema.#[derive(Debug, Clone, Serialize, Deserialize)]pub struct OptionField { pub name: String, pub label: String, #[serde(default)] pub help: Option<String>, /// `true` → mask on input, store in credentials file. #[serde(default)] pub secret: bool, /// `true` → prompt/flag must produce a value; the host refuses to /// call authed ops with a missing required field. #[serde(default)] pub required: bool, /// Optional default value for non-secret convenience options. #[serde(default)] pub default: Option<Value>,}
// ---------------------------------------------------------------------------// Host → plugin messages// ---------------------------------------------------------------------------
/// A request the host sends to the plugin after the handshake.////// The shape is `{"op": "<name>", ...per-op params}`. Responses to/// non-terminal `ask` messages use [`Answer`] / [`Ack`] instead —/// they're not `Request`s and don't carry an `op`.#[derive(Debug, Clone, Serialize, Deserialize)]pub struct Request { pub op: String, #[serde(flatten)] pub params: Value,}
/// Convenience wrapper for a host request carrying the currently-/// assembled credentials for the session. The plugin is expected to/// have consumed this via the `init` op before any authed call.#[derive(Debug, Clone, Serialize, Deserialize)]pub struct Credentials(pub Value);
impl Credentials { pub fn object(obj: serde_json::Map<String, Value>) -> Self { Self(Value::Object(obj)) } pub fn empty() -> Self { Self(Value::Object(serde_json::Map::new())) }}
// ---------------------------------------------------------------------------// Plugin → host messages// ---------------------------------------------------------------------------
/// Anything the plugin can send back for a given op: a terminal `ok`/// / `error`, or a non-terminal `ask` that waits on the host.#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(untagged)]pub enum Response { Terminal(Terminal), Ask(Ask),}
/// Terminal plugin response.#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(untagged)]pub enum Terminal { Ok { ok: OkTrue, #[serde(default)] data: Value, }, Err { ok: OkFalse, error: ErrorBody, },}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]#[serde(try_from = "bool", into = "bool")]pub struct OkTrue;impl TryFrom<bool> for OkTrue { type Error = &'static str; fn try_from(v: bool) -> Result<Self, Self::Error> { if v { Ok(Self) } else { Err("expected true") } }}impl From<OkTrue> for bool { fn from(_: OkTrue) -> Self { true }}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]#[serde(try_from = "bool", into = "bool")]pub struct OkFalse;impl TryFrom<bool> for OkFalse { type Error = &'static str; fn try_from(v: bool) -> Result<Self, Self::Error> { if !v { Ok(Self) } else { Err("expected false") } }}impl From<OkFalse> for bool { fn from(_: OkFalse) -> Self { false }}
#[derive(Debug, Clone, Serialize, Deserialize)]pub struct ErrorBody { pub code: String, pub message: String, #[serde(default)] pub retryable: bool,}
/// Non-terminal "I need something from the human" message.#[derive(Debug, Clone, Serialize, Deserialize)]pub struct Ask { #[serde(flatten)] pub kind: AskKind,}
#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(tag = "ask", rename_all = "snake_case")]pub enum AskKind { Prompt { name: String, label: String, #[serde(default)] secret: bool, }, Select { name: String, label: String, options: Vec<String>, }, Confirm { name: String, label: String, }, OpenUrl { url: String, }, Info { text: String, },}
/// Host's response to a [`AskKind::Prompt`] / [`AskKind::Select`] //// [`AskKind::Confirm`]. Keyed by the `name` of the ask, mirroring the/// plugin's field names.#[derive(Debug, Clone, Serialize, Deserialize)]pub struct Answer { pub answer: Value,}
/// Host's acknowledgement for a [`AskKind::OpenUrl`] / [`AskKind::Info`].#[derive(Debug, Clone, Serialize, Deserialize)]pub struct Ack { pub ack: bool,}
/// A capability the host needs that the plugin didn't advertise.#[derive(Debug, Clone, PartialEq, Eq)]pub struct CapabilityMissing { pub capability: String,}
/// Current protocol version understood by this crate.pub const PROTOCOL_VERSION: u32 = 1;
#[cfg(test)]mod tests { use super::*; use serde_json::json;
#[test] fn hello_serialises_as_expected() { let m = Hello::new(1); let got = serde_json::to_value(&m).unwrap(); assert_eq!(got, json!({"op": "hello", "protocol_version": 1})); }
#[test] fn ok_and_err_are_disambiguated_by_untagged_ok_bool() { let ok_json = json!({"ok": true, "data": {"x": 1}}); let err_json = json!({"ok": false, "error": {"code": "x", "message": "y"}}); let ok: Terminal = serde_json::from_value(ok_json).unwrap(); let err: Terminal = serde_json::from_value(err_json).unwrap(); assert!(matches!(ok, Terminal::Ok { .. })); assert!(matches!(err, Terminal::Err { .. })); }
#[test] fn ask_prompt_round_trips() { let a = Ask { kind: AskKind::Prompt { name: "api_token".into(), label: "API token".into(), secret: true, }, }; let value = serde_json::to_value(&a).unwrap(); assert_eq!( value, json!({ "ask": "prompt", "name": "api_token", "label": "API token", "secret": true, }) ); let back: Ask = serde_json::from_value(value).unwrap(); match back.kind { AskKind::Prompt { name, label, secret, } => { assert_eq!(name, "api_token"); assert_eq!(label, "API token"); assert!(secret); } _ => panic!("expected prompt"), } }
#[test] fn response_dispatches_ask_vs_terminal() { let ask: Response = serde_json::from_value(json!({"ask": "info", "text": "hi"})).unwrap(); assert!(matches!(ask, Response::Ask(_))); let ok: Response = serde_json::from_value(json!({"ok": true, "data": {}})).unwrap(); assert!(matches!(ok, Response::Terminal(Terminal::Ok { .. }))); }
#[test] fn hello_data_parses_capabilities_and_schema() { let v = json!({ "name": "cloudflare", "protocol_version": 1, "kind": "dns", "capabilities": ["list_txt", "upsert_txt"], "options_schema": [ {"name": "api_token", "label": "API token", "secret": true, "required": true} ] }); let hd: HelloData = serde_json::from_value(v).unwrap(); assert_eq!(hd.name, "cloudflare"); assert_eq!(hd.capabilities, vec!["list_txt", "upsert_txt"]); assert_eq!(hd.options_schema.len(), 1); assert!(hd.options_schema[0].secret); assert!(hd.options_schema[0].required); }}