Skip to main content

jev_client/
content.rs

1//! Free-form JSON content: the shape shared by `state`, `instructions` and criteria values.
2
3use std::borrow::Cow;
4
5use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8
9/// Free-form JSON that Jev reads as content: a string, an object, an array, or `null`.
10///
11/// The API accepts this shape for a request's `state`, for a question's `instructions`, and for
12/// every criteria value. Field names inside an object (`question`, `focus`, `examples`, ...) are
13/// not reserved: the model sees them as labels.
14///
15/// Deserialisation is deliberately permissive. A number or a boolean parses successfully so that
16/// offline validation can report it with a useful message instead of a parse error; the generated
17/// JSON Schema is the precise contract. Object key order is preserved, so content is sent to the
18/// API exactly as it was written.
19///
20/// ```
21/// use jev_client::Content;
22///
23/// let text = Content::from("Help! My payouts have been failing for 3 days.");
24/// assert_eq!(text.as_str(), Some("Help! My payouts have been failing for 3 days."));
25///
26/// let structured = Content::from(serde_json::json!({ "ticket": { "plan": "pro" } }));
27/// assert_eq!(structured.as_str(), None);
28/// ```
29#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
30#[serde(transparent)]
31pub struct Content(Value);
32
33impl Content {
34    /// Content that is JSON `null`, used for a choice option that needs no description.
35    #[must_use]
36    pub const fn null() -> Self {
37        Self(Value::Null)
38    }
39
40    /// Returns `true` when the content is JSON `null`.
41    #[must_use]
42    pub fn is_null(&self) -> bool {
43        self.0.is_null()
44    }
45
46    /// The text, when the content is a plain string.
47    #[must_use]
48    pub fn as_str(&self) -> Option<&str> {
49        self.0.as_str()
50    }
51
52    /// Borrows the underlying JSON value.
53    #[must_use]
54    pub const fn as_value(&self) -> &Value {
55        &self.0
56    }
57
58    /// Consumes the content and returns the underlying JSON value.
59    #[must_use]
60    pub fn into_value(self) -> Value {
61        self.0
62    }
63}
64
65impl From<Value> for Content {
66    fn from(value: Value) -> Self {
67        Self(value)
68    }
69}
70
71impl From<Content> for Value {
72    fn from(content: Content) -> Self {
73        content.0
74    }
75}
76
77impl From<String> for Content {
78    fn from(text: String) -> Self {
79        Self(Value::String(text))
80    }
81}
82
83impl From<&str> for Content {
84    fn from(text: &str) -> Self {
85        Self(Value::String(text.to_owned()))
86    }
87}
88
89impl JsonSchema for Content {
90    fn inline_schema() -> bool {
91        true
92    }
93
94    fn schema_name() -> Cow<'static, str> {
95        "Content".into()
96    }
97
98    fn schema_id() -> Cow<'static, str> {
99        concat!(module_path!(), "::Content").into()
100    }
101
102    fn json_schema(_: &mut SchemaGenerator) -> Schema {
103        json_schema!({
104            "description": "Free-form content: a string, an object, an array, or null.",
105            "type": ["string", "object", "array", "null"]
106        })
107    }
108}
109
110/// Schema for content that may not be `null`: a request's `state` and each score level.
111///
112/// Live testing showed the API rejects `null` in both places with a 422, even though the upstream
113/// documentation lists `null` as accepted for score levels.
114pub(crate) fn non_null_schema(_: &mut SchemaGenerator) -> Schema {
115    json_schema!({
116        "description": "Free-form content: a string, an object, or an array.",
117        "type": ["string", "object", "array"]
118    })
119}
120
121#[cfg(test)]
122mod tests {
123    use serde_json::json;
124
125    use super::Content;
126
127    #[test]
128    fn serialises_transparently_as_the_wrapped_value() {
129        let content = Content::from(json!({ "b": 1, "a": [true, null] }));
130
131        assert_eq!(
132            serde_json::to_string(&content).unwrap(),
133            r#"{"b":1,"a":[true,null]}"#
134        );
135    }
136
137    #[test]
138    fn accepts_scalars_so_that_validation_can_report_them() {
139        let content: Content = serde_json::from_str("42").unwrap();
140
141        assert_eq!(content.as_value(), &json!(42));
142        assert_eq!(content.as_str(), None);
143    }
144
145    #[test]
146    fn distinguishes_null_from_text() {
147        assert!(Content::null().is_null());
148        assert!(Content::default().is_null());
149        assert!(!Content::from("").is_null());
150    }
151
152    #[test]
153    fn converts_to_and_from_json_values() {
154        let value = json!(["a", { "k": "v" }]);
155
156        assert_eq!(Content::from(value.clone()).into_value(), value);
157        assert_eq!(serde_json::Value::from(Content::from("x")), json!("x"));
158        assert_eq!(Content::from(String::from("x")), Content::from("x"));
159    }
160}