Skip to main content

jmap_types/
methods.rs

1//! RFC 8620 §5 generic method-response shapes shared by all JMAP method types.
2//!
3//! These wire types are normative — every JMAP `/get`, `/set`, `/changes`,
4//! `/copy`, `/query`, and `/queryChanges` method (across mail, calendars, contacts,
5//! chat, etc.) returns one of these shapes. Centralising them here avoids
6//! drift between the seven `jmap-*-client` crates that previously each
7//! defined their own copies. [`SetResponse`] carries [`SetError`] values,
8//! defined in `set_error`.
9//!
10//! All types use camelCase JSON via `#[serde(rename_all = "camelCase")]` and
11//! are marked `#[non_exhaustive]` so future RFC errata or extensions can add
12//! fields without a semver break.
13//!
14//! # Spec references
15//!
16//! | Type | Spec |
17//! |---|---|
18//! | [`GetResponse`] | RFC 8620 §5.1 |
19//! | [`ChangesResponse`] | RFC 8620 §5.2 |
20//! | [`SetResponse`], [`PartialObject`] | RFC 8620 §5.3 |
21//! | [`CopyResponse`] | RFC 8620 §5.4 |
22//! | [`QueryResponse`] | RFC 8620 §5.5 |
23//! | [`QueryChangesResponse`], [`AddedItem`] | RFC 8620 §5.6 |
24
25use std::collections::BTreeMap;
26
27use serde::{Deserialize, Serialize};
28
29use crate::{Id, SetError, State};
30
31// ---------------------------------------------------------------------------
32// /get
33// ---------------------------------------------------------------------------
34
35/// RFC 8620 §5.1 — `Foo/get` response shape.
36///
37/// `T` is the type of object being fetched (e.g. `Mailbox`, `CalendarEvent`).
38/// `state` is the opaque state token the server returns alongside the result;
39/// it advances every time any object of the requested type changes in the
40/// account. `not_found` lists ids the client requested that the server could
41/// not find — `null` is treated as an empty list per RFC 8620 §5.1.
42#[non_exhaustive]
43#[derive(Debug, Clone, Serialize, Deserialize)]
44#[serde(rename_all = "camelCase")]
45pub struct GetResponse<T> {
46    /// The account the response refers to.
47    pub account_id: Id,
48    /// Opaque state token for this object type at the time of the response.
49    pub state: State,
50    /// The fetched objects, one per id that was found.
51    pub list: Vec<T>,
52    /// Ids that were requested but not found (RFC 8620 §5.1 `notFound:
53    /// Id[]`). A peer that sends `null` or omits it decodes as empty.
54    #[serde(default, deserialize_with = "null_as_empty")]
55    pub not_found: Vec<Id>,
56    /// Catch-all for vendor / site / private extension fields not covered
57    /// by the typed fields above. Preserves unknown fields across
58    /// deserialize/serialize round-trip per workspace extras-preservation
59    /// policy (see workspace AGENTS.md).
60    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
61    pub extra: serde_json::Map<String, serde_json::Value>,
62}
63
64/// Deserialize a `null` collection as empty: for fields RFC 8620 types as
65/// a plain array that lenient peers still send as `null`, and for the
66/// `/set` and `/copy` result fields it defines as "null if none".
67fn null_as_empty<'de, D, C>(d: D) -> Result<C, D::Error>
68where
69    D: serde::Deserializer<'de>,
70    C: Deserialize<'de> + Default,
71{
72    Ok(Option::<C>::deserialize(d)?.unwrap_or_default())
73}
74
75/// Serialize an empty collection as `null`, the RFC 8620 §5.3 / §5.4 wire
76/// form for a `/set` or `/copy` result field with no entries.
77fn empty_as_null<S, C>(c: &C, s: S) -> Result<S::Ok, S::Error>
78where
79    S: serde::Serializer,
80    C: Serialize,
81    for<'a> &'a C: IntoIterator,
82{
83    if c.into_iter().next().is_none() {
84        s.serialize_none()
85    } else {
86        s.serialize_some(c)
87    }
88}
89
90// ---------------------------------------------------------------------------
91// /changes
92// ---------------------------------------------------------------------------
93
94/// RFC 8620 §5.2 — `Foo/changes` response shape.
95///
96/// Reports the ids of objects created, updated, or destroyed since
97/// `old_state`. If `has_more_changes` is `true`, the client should call
98/// `/changes` again with `since_state = new_state` to retrieve the next
99/// page; otherwise `new_state` is the current state.
100///
101/// # Extension fields and the foundation-coupling trade-off
102///
103/// Some JMAP data-type extensions add an `updatedProperties` field to
104/// their `/changes` response shape:
105///
106/// - RFC 8621 §2.2 (`Mailbox/changes`): set when only `totalEmails` /
107///   `unreadEmails` / `totalThreads` / `unreadThreads` changed.
108/// - RFC 9425 §5 (`Quota/changes`): set when only the `used` property
109///   changed.
110///
111/// - draft-ietf-jmap-metadata-05 §3.3: every data type the metadata
112///   capability lists, when the request's `using` includes
113///   `urn:ietf:params:jmap:metadata`. The field is then always present,
114///   `null` unless every updated id changed only in `metadata` and/or
115///   `privateMetadata` (plus the Mailbox counts).
116///
117/// For all other `/changes` methods (RFC 8621 §3.2 `Thread/changes`,
118/// §4.3 `Email/changes`, plus every extension `/changes` method not
119/// listed above) the server omits the field, and clients deserialize
120/// it as `None`.
121///
122/// **Architectural decision (bd:JMAP-6xs8.5).** Carrying
123/// `updatedProperties` on this base type, rather than on per-extension
124/// `MailboxChangesResponse` / `QuotaChangesResponse` newtypes, is a
125/// deliberate workspace trade-off:
126///
127/// - **Chosen shape**: one foundation `ChangesResponse` with an
128///   `Option<Option<Vec<String>>>` field that extensions populate.
129/// - **Alternative (a)**: `ChangesResponse<Ext = ()>` generic with a
130///   per-type extension struct. Rejected: would force every
131///   `/changes` handler in every extension server to thread the `Ext`
132///   type parameter, and the 30-crate canonical-template family would
133///   have to settle on a single way to express "no extension" vs
134///   "Mailbox extension" vs "Quota extension".
135/// - **Alternative (b)**: `MailboxChangesResponse` and
136///   `QuotaChangesResponse` as separate types in `jmap-mail-types` and
137///   a future `jmap-quota-types`, delegating to a shared base via
138///   composition. Rejected: would duplicate the seven base fields
139///   (`accountId`, `oldState`, `newState`, `hasMoreChanges`, three
140///   id vectors) at every extension type, and require parallel
141///   handler / parse / dispatch code.
142/// - **Alternative (c)**: leave `updatedProperties` as an extras
143///   flatten entry that mail/quota types explicitly read via
144///   `resp.extra.get("updatedProperties")`. Rejected: loses typed
145///   access, and the field is RFC-defined (not vendor / site), so the
146///   extras pattern (workspace AGENTS.md "Extras-preservation policy")
147///   is the wrong tool.
148///
149/// **Drift risk acknowledged**: every future `/changes` extension
150/// (`jmap-sharing`, `jmap-tasks`, etc.) will face pressure to add its
151/// own typed field here "for parity". Each such field would extend
152/// this foundation type by one more extension-specific column.
153/// Cautionary precedent: bd:JMAP-kt5k removed eight cap-advertising
154/// fields from the chat capability after they accreted there for the
155/// same parity-pressure reason. New `/changes` extension fields land
156/// here only when the field is RFC-defined and the alternative shapes
157/// above have been re-evaluated against the new use case; a vendor
158/// extension belongs in the extras catch-all, not on the typed
159/// surface.
160#[non_exhaustive]
161#[derive(Debug, Clone, Serialize, Deserialize)]
162#[serde(rename_all = "camelCase")]
163pub struct ChangesResponse {
164    /// The account the response refers to.
165    pub account_id: Id,
166    /// The state token the client passed in.
167    pub old_state: State,
168    /// The current (or next-page) state token.
169    pub new_state: State,
170    /// `true` if there are more changes the client must page through.
171    pub has_more_changes: bool,
172    /// Ids of objects created since `old_state`.
173    pub created: Vec<Id>,
174    /// Ids of objects updated since `old_state`.
175    pub updated: Vec<Id>,
176    /// Ids of objects destroyed since `old_state`.
177    pub destroyed: Vec<Id>,
178    /// Property names that changed (RFC 8621 §2.2, RFC 9425 §5,
179    /// draft-ietf-jmap-metadata-05 §3.3), in three states: `None` when
180    /// absent, `Some(None)` for `null` and `Some(Some(names))` for a
181    /// list. Each state round-trips.
182    ///
183    /// `Mailbox/changes` and `Quota/changes` may list the properties
184    /// that changed, and clients can back-reference
185    /// `/updatedProperties` into a follow-up `/get`. When the request's
186    /// `using` includes `urn:ietf:params:jmap:metadata`, -05 §3.3 says
187    /// for every listed data type that the argument "is always present,
188    /// and is null when updated is empty", so a server sets `Some(None)`
189    /// rather than `None` there. Other responses leave it `None` unless
190    /// their type defines it, and it is then omitted.
191    #[serde(
192        default,
193        deserialize_with = "present",
194        skip_serializing_if = "Option::is_none"
195    )]
196    pub updated_properties: Option<Option<Vec<String>>>,
197    /// Catch-all for vendor / site / private extension fields not covered
198    /// by the typed fields above. Preserves unknown fields across
199    /// deserialize/serialize round-trip per workspace extras-preservation
200    /// policy (see workspace AGENTS.md).
201    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
202    pub extra: serde_json::Map<String, serde_json::Value>,
203}
204
205/// Deserialize a property that may be absent, `null` or a value into
206/// `Option<Option<T>>`: absent is `None` (via `#[serde(default)]`), `null`
207/// is `Some(None)` and a value is `Some(Some(v))`.
208fn present<'de, D, T>(d: D) -> Result<Option<Option<T>>, D::Error>
209where
210    D: serde::Deserializer<'de>,
211    T: Deserialize<'de>,
212{
213    Option::<T>::deserialize(d).map(Some)
214}
215
216// ---------------------------------------------------------------------------
217// /set
218// ---------------------------------------------------------------------------
219
220/// RFC 8620 §5.3 — `Foo/set` response shape.
221///
222/// Wire shape per RFC 8620 §5.3 (rfc8620.txt §5.3 around line 2033):
223///
224/// ```text
225/// created       Id[Foo]      | null
226/// updated       Id[Foo|null] | null   ← inner null is REQUIRED
227/// destroyed     Id[]         | null
228/// notCreated    Id[SetError] | null
229/// notUpdated    Id[SetError] | null
230/// notDestroyed  Id[SetError] | null
231/// ```
232///
233/// The inner `null` in `updated` is the server's signal that the patch was
234/// applied verbatim with no server-set property deltas to report; a typed
235/// `SetResponse<Foo>` MUST accept this rather than failing because `null`
236/// cannot become `Foo`.
237///
238/// `created` and `not_created` keys are caller-supplied creation ids
239/// (`String`); `updated`, `not_updated`, `not_destroyed` keys are
240/// server-assigned record ids ([`Id`]) — typed differently so callers can
241/// use `updated`/`destroyed` keys interchangeably with ids from any
242/// `/get` response.
243///
244/// The result maps and lists are plain collections, not `Option`s: RFC 8620
245/// defines each as "null if none", so an empty collection means none. A
246/// `null` or absent field decodes as empty and an empty one encodes as
247/// `null`.
248#[non_exhaustive]
249#[derive(Debug, Clone, Serialize, Deserialize)]
250#[serde(rename_all = "camelCase")]
251#[serde(bound(
252    deserialize = "T: serde::de::DeserializeOwned",
253    serialize = "T: Serialize"
254))]
255pub struct SetResponse<T> {
256    /// The account the response refers to.
257    pub account_id: Id,
258    /// State token before this `/set` was applied. RFC 8620 §5.3 makes the
259    /// property `String|null`; `None` when it is `null` or, from a server
260    /// that leaves it out, absent.
261    pub old_state: Option<State>,
262    /// State token after this `/set`.
263    ///
264    /// RFC 8620 §5.3 requires `newState`, but some servers leave it out
265    /// (Stalwart 1.1.1 does when a `/set` changes nothing). Such a response
266    /// still deserializes, with `new_state` set to the **empty** state
267    /// (`""`), so that its `created` / `updated` / `destroyed` / `not*`
268    /// results are not lost (docs/design/DECISIONS.md decision 67).
269    /// `jmap-base-client`'s `extract_response` logs a `warn` event when
270    /// it decodes such a response.
271    ///
272    /// An empty `new_state` is not a real state: do not store it or pass
273    /// it as `sinceState` or `ifInState`. A `Foo/changes` from it fails
274    /// (typically `cannotCalculateChanges`). Re-fetch the current state
275    /// with `Foo/get` instead. Serializing such a response writes
276    /// `"newState": ""`. This placeholder is a recorded exception to the
277    /// workspace rule against in-band sentinels (decision 72), kept so that
278    /// tolerating such servers is not an API break.
279    #[serde(default = "absent_new_state")]
280    pub new_state: State,
281    /// Successfully created objects, keyed by caller-supplied creation id.
282    #[serde(
283        default,
284        deserialize_with = "null_as_empty",
285        serialize_with = "empty_as_null"
286    )]
287    pub created: BTreeMap<String, T>,
288    /// Successfully updated objects, keyed by record id. The value is
289    /// `Some(T)` when the server reports server-set property deltas, or
290    /// `None` when the patch was applied verbatim with nothing to echo.
291    #[serde(
292        default,
293        deserialize_with = "null_as_empty",
294        serialize_with = "empty_as_null"
295    )]
296    pub updated: BTreeMap<Id, Option<T>>,
297    /// Ids of successfully destroyed objects.
298    #[serde(
299        default,
300        deserialize_with = "null_as_empty",
301        serialize_with = "empty_as_null"
302    )]
303    pub destroyed: Vec<Id>,
304    /// Failed creates, keyed by caller-supplied creation id.
305    #[serde(
306        default,
307        deserialize_with = "null_as_empty",
308        serialize_with = "empty_as_null"
309    )]
310    pub not_created: BTreeMap<String, SetError>,
311    /// Failed updates, keyed by record id.
312    #[serde(
313        default,
314        deserialize_with = "null_as_empty",
315        serialize_with = "empty_as_null"
316    )]
317    pub not_updated: BTreeMap<Id, SetError>,
318    /// Failed destroys, keyed by record id.
319    #[serde(
320        default,
321        deserialize_with = "null_as_empty",
322        serialize_with = "empty_as_null"
323    )]
324    pub not_destroyed: BTreeMap<Id, SetError>,
325    /// Catch-all for vendor / site / private extension fields not covered
326    /// by the typed fields above. Preserves unknown fields across
327    /// deserialize/serialize round-trip per workspace extras-preservation
328    /// policy (see workspace AGENTS.md).
329    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
330    pub extra: serde_json::Map<String, serde_json::Value>,
331}
332
333/// `SetResponse::new_state` when the server leaves `newState` out: the
334/// empty state. See that field's docs (decision 67).
335fn absent_new_state() -> State {
336    State::from("")
337}
338
339/// The partial object a server echoes in `/set` `created` / `updated` and
340/// `/copy` `created` (RFC 8620 §5.3, §5.4).
341///
342/// RFC 8620 §5.3 defines each `created` value as "an object containing any
343/// properties of the created Foo object that were not sent by the client",
344/// and §5.4 defines each `/copy` `created` value as the "properties of the
345/// copied Foo object that are set by the server". Neither is a full `Foo`,
346/// so a full typed `Foo` cannot hold them: required client-sent properties
347/// are absent. This type keeps the one property nearly every object type
348/// reports, `id`, and every other returned property in [`Self::extra`].
349///
350/// Deserialize a property out of `extra` with `serde_json::from_value`
351/// when it is needed (e.g. `blobId` / `threadId` / `size` for an Email,
352/// RFC 8621 §4.6).
353#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
354pub struct PartialObject {
355    /// The server-assigned id, when the server reported one. `None` for an
356    /// `updated` entry (the id is the map key) or an object type whose id
357    /// is not server-set.
358    #[serde(default, skip_serializing_if = "Option::is_none")]
359    pub id: Option<Id>,
360    /// Every other property the server returned, keyed by wire name.
361    #[serde(flatten, default)]
362    pub extra: serde_json::Map<String, serde_json::Value>,
363}
364
365// ---------------------------------------------------------------------------
366// /copy
367// ---------------------------------------------------------------------------
368
369/// RFC 8620 §5.4 — `Foo/copy` response shape.
370///
371/// Unlike [`SetResponse`] it carries `fromAccountId` and has no `updated`
372/// / `destroyed` maps. When `onSuccessDestroyOriginal` is set the server
373/// sends a separate implicit `Foo/set` response with the same call id; that
374/// one is a [`SetResponse`].
375///
376/// The result maps and lists are plain collections, not `Option`s: RFC 8620
377/// defines each as "null if none", so an empty collection means none. A
378/// `null` or absent field decodes as empty and an empty one encodes as
379/// `null`.
380#[non_exhaustive]
381#[derive(Debug, Clone, Serialize, Deserialize)]
382#[serde(rename_all = "camelCase")]
383#[serde(bound(
384    deserialize = "T: serde::de::DeserializeOwned",
385    serialize = "T: Serialize"
386))]
387pub struct CopyResponse<T> {
388    /// The account the records were copied from.
389    pub from_account_id: Id,
390    /// The account the records were copied to.
391    pub account_id: Id,
392    /// State of the destination account before the copy, or `None` when
393    /// the server does not know it.
394    pub old_state: Option<State>,
395    /// State of the destination account after the copy.
396    pub new_state: State,
397    /// Successfully copied objects, keyed by caller-supplied creation id.
398    #[serde(
399        default,
400        deserialize_with = "null_as_empty",
401        serialize_with = "empty_as_null"
402    )]
403    pub created: BTreeMap<String, T>,
404    /// Failed copies, keyed by caller-supplied creation id.
405    #[serde(
406        default,
407        deserialize_with = "null_as_empty",
408        serialize_with = "empty_as_null"
409    )]
410    pub not_created: BTreeMap<String, SetError>,
411    /// Catch-all for vendor / site / private extension fields not covered
412    /// by the typed fields above. Preserves unknown fields across
413    /// deserialize/serialize round-trip per workspace extras-preservation
414    /// policy (see workspace AGENTS.md).
415    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
416    pub extra: serde_json::Map<String, serde_json::Value>,
417}
418
419// ---------------------------------------------------------------------------
420// /query
421// ---------------------------------------------------------------------------
422
423/// RFC 8620 §5.5 — `Foo/query` response shape.
424///
425/// Returns the ids of objects matching a filter, in sort order. The
426/// `query_state` token can be passed to `Foo/queryChanges` to retrieve only
427/// the delta against this snapshot.
428#[non_exhaustive]
429#[derive(Debug, Clone, Serialize, Deserialize)]
430#[serde(rename_all = "camelCase")]
431pub struct QueryResponse {
432    /// The account the response refers to.
433    pub account_id: Id,
434    /// Opaque state token for this query result; pass to `/queryChanges`.
435    pub query_state: State,
436    /// `true` if `/queryChanges` will give incremental updates against this
437    /// `query_state`; `false` if the client must re-run `/query` to refresh.
438    pub can_calculate_changes: bool,
439    /// Zero-based offset within the full result set of the first id in
440    /// `ids`. Per RFC 8620 §5.5, may differ from the requested `position`
441    /// when the requested offset exceeds the result count.
442    pub position: u64,
443    /// The matching ids in sort order.
444    pub ids: Vec<Id>,
445    /// Total number of matching objects, or `None` when the request did not
446    /// set `calculateTotal: true`.
447    pub total: Option<u64>,
448    /// Server's max page size; `None` when not advertised.
449    pub limit: Option<u64>,
450    /// Catch-all for vendor / site / private extension fields not covered
451    /// by the typed fields above. Preserves unknown fields across
452    /// deserialize/serialize round-trip per workspace extras-preservation
453    /// policy (see workspace AGENTS.md).
454    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
455    pub extra: serde_json::Map<String, serde_json::Value>,
456}
457
458// ---------------------------------------------------------------------------
459// /queryChanges
460// ---------------------------------------------------------------------------
461
462/// A single item added to a query result set (RFC 8620 §5.6).
463///
464/// The `index` is the position the new item occupies in the post-change
465/// result set, accounting for items also added in this batch.
466#[non_exhaustive]
467#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
468#[serde(rename_all = "camelCase")]
469pub struct AddedItem {
470    /// The id of the new item in the result set.
471    pub id: Id,
472    /// Zero-based position of the new item in the post-change result set.
473    pub index: u64,
474    /// Catch-all for vendor / site / private extension fields not covered
475    /// by the typed fields above. Preserves unknown fields across
476    /// deserialize/serialize round-trip per workspace extras-preservation
477    /// policy (see workspace AGENTS.md).
478    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
479    pub extra: serde_json::Map<String, serde_json::Value>,
480}
481
482/// RFC 8620 §5.6 — `Foo/queryChanges` response shape.
483///
484/// Reports the ids removed from and added to a query result set since
485/// `old_query_state`. Combined with the previous result, the client can
486/// reconstruct the new result without re-fetching all ids.
487#[non_exhaustive]
488#[derive(Debug, Clone, Serialize, Deserialize)]
489#[serde(rename_all = "camelCase")]
490pub struct QueryChangesResponse {
491    /// The account the response refers to.
492    pub account_id: Id,
493    /// The state token the client passed in.
494    pub old_query_state: State,
495    /// The current state token.
496    pub new_query_state: State,
497    /// Total number of matching objects (only when
498    /// `calculateTotal: true` was set in the request).
499    pub total: Option<u64>,
500    /// Ids removed from the result set since `old_query_state`.
501    pub removed: Vec<Id>,
502    /// Items added to the result set, with their new positions.
503    pub added: Vec<AddedItem>,
504    /// Catch-all for vendor / site / private extension fields not covered
505    /// by the typed fields above. Preserves unknown fields across
506    /// deserialize/serialize round-trip per workspace extras-preservation
507    /// policy (see workspace AGENTS.md).
508    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
509    pub extra: serde_json::Map<String, serde_json::Value>,
510}
511
512#[cfg(test)]
513mod tests {
514    use super::*;
515    use crate::SetErrorType;
516    use serde_json::json;
517
518    // Independent oracles: hand-written JSON shapes from the RFC 8620
519    // examples and prose descriptions, NOT derived from the types being
520    // tested. Wire round-trips ensure the serde rename rules and field
521    // shapes match the spec.
522
523    #[test]
524    fn get_response_round_trips() {
525        let raw = json!({
526            "accountId": "A1",
527            "state": "s42",
528            "list": [{"id": "x", "name": "First"}],
529            "notFound": ["missing1"]
530        });
531        let resp = GetResponse::<serde_json::Value>::deserialize(&raw).unwrap();
532        assert_eq!(resp.account_id.as_ref(), "A1");
533        assert_eq!(resp.state, "s42");
534        assert_eq!(resp.list.len(), 1);
535        assert_eq!(resp.list[0]["name"], "First");
536        assert_eq!(resp.not_found, [Id::from("missing1")]);
537        // Round-trip back to JSON and confirm the camelCase keys.
538        let back = serde_json::to_value(&resp).unwrap();
539        assert_eq!(back["accountId"], "A1");
540        assert_eq!(back["notFound"][0], "missing1");
541    }
542
543    #[test]
544    fn get_response_null_not_found() {
545        // RFC 8620 §5.1 types notFound as "Id[]": "The array is empty if all
546        // requested ids were found or if the "ids" argument passed in was
547        // either null or an empty array." A lenient peer's null decodes as
548        // that empty array and re-encodes as `[]`, never `null`.
549        let raw = json!({
550            "accountId": "A1",
551            "state": "s1",
552            "list": [],
553            "notFound": null
554        });
555        let resp: GetResponse<serde_json::Value> = serde_json::from_value(raw).unwrap();
556        assert!(resp.not_found.is_empty());
557        assert_eq!(serde_json::to_value(&resp).unwrap()["notFound"], json!([]));
558    }
559
560    #[test]
561    fn changes_response_round_trips() {
562        let raw = json!({
563            "accountId": "A1",
564            "oldState": "s0",
565            "newState": "s1",
566            "hasMoreChanges": false,
567            "created": ["a"],
568            "updated": ["b"],
569            "destroyed": ["c"]
570        });
571        let resp: ChangesResponse = serde_json::from_value(raw).unwrap();
572        assert_eq!(resp.old_state, "s0");
573        assert_eq!(resp.new_state, "s1");
574        assert!(!resp.has_more_changes);
575        assert_eq!(resp.created[0].as_ref(), "a");
576        assert_eq!(resp.updated[0].as_ref(), "b");
577        assert_eq!(resp.destroyed[0].as_ref(), "c");
578        // RFC 8620 §5.2 base `/changes` does not define `updatedProperties`;
579        // the field must default to `None` when absent from the wire.
580        assert!(resp.updated_properties.is_none());
581    }
582
583    /// Oracle: RFC 8621 §2.2 example response (lines 1015-1031 of rfc8621.txt
584    /// in this repo) — `Mailbox/changes` carries `updatedProperties` listing
585    /// `totalEmails`, `unreadEmails`, `totalThreads`, `unreadThreads`.
586    #[test]
587    fn changes_response_deserializes_mailbox_updated_properties() {
588        let raw = json!({
589            "accountId": "A1",
590            "oldState": "78541",
591            "newState": "78542",
592            "hasMoreChanges": false,
593            "updatedProperties": [
594                "totalEmails", "unreadEmails",
595                "totalThreads", "unreadThreads"
596            ],
597            "created": [],
598            "updated": ["B"],
599            "destroyed": []
600        });
601        let resp: ChangesResponse = serde_json::from_value(raw).unwrap();
602        let props = resp
603            .updated_properties
604            .expect("updatedProperties must be present")
605            .expect("updatedProperties must be a list");
606        assert_eq!(
607            props,
608            vec![
609                "totalEmails".to_string(),
610                "unreadEmails".to_string(),
611                "totalThreads".to_string(),
612                "unreadThreads".to_string()
613            ]
614        );
615    }
616
617    /// Oracle: RFC 9425 §5 example response — `Quota/changes` carries
618    /// `updatedProperties: ["used"]` when only quota usage changed.
619    #[test]
620    fn changes_response_deserializes_quota_updated_properties() {
621        let raw = json!({
622            "accountId": "A1",
623            "oldState": "78541",
624            "newState": "78542",
625            "hasMoreChanges": false,
626            "updatedProperties": ["used"],
627            "created": [],
628            "updated": ["2a06df0d-9865-4e74-a92f-74dcc814270e"],
629            "destroyed": []
630        });
631        let resp: ChangesResponse = serde_json::from_value(raw).unwrap();
632        let props = resp
633            .updated_properties
634            .expect("updatedProperties must be present")
635            .expect("updatedProperties must be a list");
636        assert_eq!(props, vec!["used".to_string()]);
637    }
638
639    /// `updatedProperties: null` on the wire (RFC 8621 §2.2: "If the server
640    /// is unable to tell if only counts have changed, it MUST just be null")
641    /// deserializes as `Some(None)`, distinct from omitted, so it can be
642    /// re-emitted (draft-ietf-jmap-metadata-05 §3.3: "It is always
643    /// present, and is null when updated is empty").
644    #[test]
645    fn changes_response_accepts_explicit_null_updated_properties() {
646        let raw = json!({
647            "accountId": "A1",
648            "oldState": "s0",
649            "newState": "s1",
650            "hasMoreChanges": false,
651            "updatedProperties": null,
652            "created": [],
653            "updated": ["B"],
654            "destroyed": []
655        });
656        let resp: ChangesResponse = serde_json::from_value(raw).unwrap();
657        assert_eq!(resp.updated_properties, Some(None));
658    }
659
660    /// Serializing a `ChangesResponse` without `updated_properties` must
661    /// NOT emit a `"updatedProperties": null` key — the
662    /// `skip_serializing_if = "Option::is_none"` attribute keeps the wire
663    /// shape minimal and matches the RFC 8620 §5.2 base envelope for
664    /// methods that don't define the extension field.
665    #[test]
666    fn changes_response_omits_updated_properties_when_none() {
667        let resp = ChangesResponse {
668            account_id: Id::from("A1"),
669            old_state: "s0".into(),
670            new_state: "s1".into(),
671            has_more_changes: false,
672            created: vec![],
673            updated: vec![],
674            destroyed: vec![],
675            updated_properties: None,
676            extra: serde_json::Map::new(),
677        };
678        let serialized = serde_json::to_value(&resp).expect("must serialize");
679        assert!(
680            serialized.get("updatedProperties").is_none(),
681            "updatedProperties must be omitted when None"
682        );
683    }
684
685    /// draft-ietf-jmap-metadata-05 §3.3: when the request's `using`
686    /// includes the metadata capability, updatedProperties "is always
687    /// present, and is null when updated is empty". `Some(None)` must
688    /// therefore serialize as an explicit `null`.
689    #[test]
690    fn changes_response_emits_null_updated_properties_when_some_none() {
691        let resp = ChangesResponse {
692            account_id: Id::from("A1"),
693            old_state: "s0".into(),
694            new_state: "s1".into(),
695            has_more_changes: false,
696            created: vec![],
697            updated: vec![],
698            destroyed: vec![],
699            updated_properties: Some(None),
700            extra: serde_json::Map::new(),
701        };
702        let serialized = serde_json::to_value(&resp).expect("must serialize");
703        assert_eq!(
704            serialized,
705            json!({
706                "accountId": "A1",
707                "oldState": "s0",
708                "newState": "s1",
709                "hasMoreChanges": false,
710                "created": [],
711                "updated": [],
712                "destroyed": [],
713                "updatedProperties": null
714            })
715        );
716    }
717
718    /// Oracle: draft-ietf-jmap-metadata-05 §6.8 example `Email/changes`
719    /// response, which reports a metadata-only change with
720    /// `"updatedProperties": ["metadata"]`. It must decode and re-encode
721    /// unchanged.
722    #[test]
723    fn changes_response_round_trips_metadata_updated_properties() {
724        let raw = json!({
725            "accountId": "A1",
726            "oldState": "e-100",
727            "newState": "e-103",
728            "hasMoreChanges": false,
729            "created": [],
730            "updated": ["EM1", "EM2"],
731            "destroyed": [],
732            "updatedProperties": ["metadata"]
733        });
734        let resp: ChangesResponse = serde_json::from_value(raw.clone()).unwrap();
735        assert_eq!(
736            resp.updated_properties,
737            Some(Some(vec!["metadata".to_string()]))
738        );
739        assert_eq!(serde_json::to_value(&resp).unwrap(), raw);
740    }
741
742    #[test]
743    fn set_response_updated_accepts_null_value() {
744        // §5.3 wire type: updated is Id[Foo|null]|null. The inner null
745        // signals "patch applied verbatim, no server-set fields to echo".
746        let raw = json!({
747            "accountId": "A1",
748            "oldState": "s1",
749            "newState": "s2",
750            "updated": { "ev1": null, "ev2": null }
751        });
752        let resp: SetResponse<serde_json::Value> = serde_json::from_value(raw).unwrap();
753        let upd = resp.updated;
754        assert!(upd.get(&Id::from("ev1")).unwrap().is_none());
755        assert!(upd.get(&Id::from("ev2")).unwrap().is_none());
756    }
757
758    #[test]
759    fn set_response_updated_accepts_object_value() {
760        let raw = json!({
761            "accountId": "A1",
762            "oldState": "s1",
763            "newState": "s2",
764            "updated": { "ev1": { "id": "ev1", "title": "Meeting" } }
765        });
766        let resp: SetResponse<serde_json::Value> = serde_json::from_value(raw).unwrap();
767        let upd = resp.updated;
768        let ev1 = upd.get(&Id::from("ev1")).unwrap().as_ref().unwrap();
769        assert_eq!(ev1["title"], "Meeting");
770    }
771
772    #[test]
773    fn set_response_not_updated_keys_are_ids() {
774        // §5.3: notUpdated is Id[SetError]|null. Keys are server-assigned
775        // ids, not creation ids — typing them as Id (not String) lets
776        // callers use the keys interchangeably with /get response ids.
777        let raw = json!({
778            "accountId": "A1",
779            "oldState": "s1",
780            "newState": "s1",
781            "notUpdated": {
782                "ev1": { "type": "stateMismatch" }
783            }
784        });
785        let resp: SetResponse<serde_json::Value> = serde_json::from_value(raw).unwrap();
786        let nu = resp.not_updated;
787        assert_eq!(
788            nu.get(&Id::from("ev1")).unwrap().error_type.to_string(),
789            "stateMismatch"
790        );
791    }
792
793    #[test]
794    fn set_error_full_8_fields_round_trip() {
795        // §5.3 + RFC 8621 §5.5/§5.7/§7.5: SetError carries up to 8 fields
796        // depending on the error type. The client side must preserve all
797        // of them on deserialize, otherwise callers cannot recover the
798        // existingId / blobNotFound / recipient-list payload that the
799        // server relied on to make the error actionable.
800        let raw = json!({
801            "type": "alreadyExists",
802            "description": "conflict",
803            "properties": ["name"],
804            "existingId": "obj-7",
805            "notFound": ["blob-1", "blob-2"],
806            "maxRecipients": 50,
807            "invalidRecipients": ["bad@", "no@no"],
808            "maxSize": 10485760
809        });
810        let err = SetError::deserialize(&raw).unwrap();
811        assert_eq!(err.error_type, SetErrorType::AlreadyExists);
812        assert_eq!(err.description.as_deref(), Some("conflict"));
813        assert_eq!(err.properties.as_ref().unwrap()[0], "name");
814        assert_eq!(err.existing_id.as_ref().unwrap().as_ref(), "obj-7");
815        assert_eq!(err.not_found.as_ref().unwrap().len(), 2);
816        assert_eq!(err.max_recipients, Some(50));
817        assert_eq!(err.invalid_recipients.as_ref().unwrap().len(), 2);
818        assert_eq!(err.max_size, Some(10_485_760));
819        // Round-trip preserves wire field names.
820        let back = serde_json::to_value(&err).unwrap();
821        assert_eq!(back, raw);
822    }
823
824    #[test]
825    fn set_error_minimal_omits_optional_fields_on_serialize() {
826        // §5.3: only `type` is required. Optional fields MUST be omitted
827        // (not serialized as `null`) so the wire matches the server's
828        // construction shape exactly.
829        let err = SetError::new("forbidden");
830        let json = serde_json::to_value(&err).unwrap();
831        assert_eq!(json["type"], "forbidden");
832        assert!(json.get("description").is_none());
833        assert!(json.get("properties").is_none());
834        assert!(json.get("existingId").is_none());
835        assert!(json.get("notFound").is_none());
836        assert!(json.get("maxRecipients").is_none());
837        assert!(json.get("invalidRecipients").is_none());
838        assert!(json.get("maxSize").is_none());
839        // Empty extra map must not appear at all in the wire output.
840        let obj = json.as_object().unwrap();
841        assert_eq!(
842            obj.len(),
843            1,
844            "minimal SetError must serialize to exactly {{type}}: {json}"
845        );
846    }
847
848    #[test]
849    fn set_error_extension_fields_round_trip_via_extra() {
850        // JMAP Chat's serverRetryAfter is a per-extension SetError field
851        // that must round-trip losslessly through extra without the base
852        // type knowing about it. Pin both directions.
853        let raw = json!({
854            "type": "rateLimited",
855            "description": "slow-mode active",
856            "serverRetryAfter": "2026-01-01T00:00:00Z"
857        });
858        let err = SetError::deserialize(&raw).unwrap();
859        assert_eq!(err.error_type.to_string(), "rateLimited");
860        assert_eq!(err.description.as_deref(), Some("slow-mode active"));
861        assert_eq!(
862            err.extra.get("serverRetryAfter").and_then(|v| v.as_str()),
863            Some("2026-01-01T00:00:00Z"),
864            "extension field must land in extra map: {err:?}"
865        );
866        let back = serde_json::to_value(&err).unwrap();
867        assert_eq!(back, raw, "round-trip must preserve extension field");
868    }
869
870    #[test]
871    fn set_error_extension_type_round_trips() {
872        // Extension errors (e.g. calendars draft §10.7.2) MUST round-trip
873        // through SetErrorType::Other without a new variant being added.
874        let err = SetError::new("noSupportedScheduleMethods");
875        let json = serde_json::to_value(&err).unwrap();
876        assert_eq!(json["type"], "noSupportedScheduleMethods");
877        let back: SetError = serde_json::from_value(json).unwrap();
878        assert_eq!(
879            back.error_type,
880            SetErrorType::Other("noSupportedScheduleMethods".to_owned())
881        );
882    }
883
884    #[test]
885    fn set_error_display_with_description() {
886        let err = SetError {
887            error_type: SetErrorType::Forbidden,
888            description: Some("not your calendar".to_owned()),
889            ..SetError::new("forbidden")
890        };
891        assert_eq!(err.to_string(), "forbidden: not your calendar");
892    }
893
894    #[test]
895    fn set_error_display_without_description() {
896        let err = SetError::new("forbidden");
897        assert_eq!(err.to_string(), "forbidden");
898    }
899
900    #[test]
901    fn query_response_round_trips() {
902        let raw = json!({
903            "accountId": "A1",
904            "queryState": "qs1",
905            "canCalculateChanges": true,
906            "position": 0,
907            "ids": ["a", "b", "c"],
908            "total": 3,
909            "limit": 100
910        });
911        let resp: QueryResponse = serde_json::from_value(raw).unwrap();
912        assert_eq!(resp.query_state, "qs1");
913        assert!(resp.can_calculate_changes);
914        assert_eq!(resp.ids.len(), 3);
915        assert_eq!(resp.total, Some(3));
916        assert_eq!(resp.limit, Some(100));
917    }
918
919    #[test]
920    fn query_response_omits_optional_total_and_limit() {
921        let raw = json!({
922            "accountId": "A1",
923            "queryState": "qs1",
924            "canCalculateChanges": false,
925            "position": 0,
926            "ids": [],
927            "total": null,
928            "limit": null
929        });
930        let resp: QueryResponse = serde_json::from_value(raw).unwrap();
931        assert!(resp.total.is_none());
932        assert!(resp.limit.is_none());
933    }
934
935    #[test]
936    fn query_changes_response_round_trips() {
937        let raw = json!({
938            "accountId": "A1",
939            "oldQueryState": "qs0",
940            "newQueryState": "qs1",
941            "total": 5,
942            "removed": ["x"],
943            "added": [
944                {"id": "y", "index": 2}
945            ]
946        });
947        let resp: QueryChangesResponse = serde_json::from_value(raw).unwrap();
948        assert_eq!(resp.old_query_state, "qs0");
949        assert_eq!(resp.new_query_state, "qs1");
950        assert_eq!(resp.total, Some(5));
951        assert_eq!(resp.removed[0].as_ref(), "x");
952        assert_eq!(resp.added.len(), 1);
953        assert_eq!(resp.added[0].id.as_ref(), "y");
954        assert_eq!(resp.added[0].index, 2);
955    }
956
957    #[test]
958    fn added_item_round_trips() {
959        let raw = json!({"id": "foo", "index": 7});
960        let item = AddedItem::deserialize(&raw).unwrap();
961        assert_eq!(item.id.as_ref(), "foo");
962        assert_eq!(item.index, 7);
963        assert_eq!(serde_json::to_value(&item).unwrap(), raw);
964    }
965
966    // ── Extras-preservation policy tests (JMAP-lbdy.1) ───────────────────
967    //
968    // One round-trip preservation test per migrated type. Each test
969    // asserts that an unknown vendor / site / private-extension field
970    // survives deserialize/serialize unchanged. Per workspace
971    // AGENTS.md "Extras-preservation policy for vendor/site fields".
972
973    /// `GetResponse.extra` captures vendor fields and preserves them on
974    /// re-serialize.
975    #[test]
976    fn get_response_preserves_vendor_extras() {
977        let raw = json!({
978            "accountId": "A1",
979            "state": "s1",
980            "list": [],
981            "notFound": null,
982            "acmeCorpAuditTrail": {"sequence": 42}
983        });
984        let resp = GetResponse::<serde_json::Value>::deserialize(&raw).unwrap();
985        assert_eq!(
986            resp.extra
987                .get("acmeCorpAuditTrail")
988                .and_then(|v| v["sequence"].as_u64()),
989            Some(42),
990            "vendor field must land in extra: {:?}",
991            resp.extra
992        );
993        let back = serde_json::to_value(&resp).unwrap();
994        assert_eq!(
995            back["acmeCorpAuditTrail"]["sequence"], 42,
996            "vendor field must survive serialize: {back}"
997        );
998    }
999
1000    /// `ChangesResponse.extra` captures vendor fields and preserves them.
1001    #[test]
1002    fn changes_response_preserves_vendor_extras() {
1003        let raw = json!({
1004            "accountId": "A1",
1005            "oldState": "s0",
1006            "newState": "s1",
1007            "hasMoreChanges": false,
1008            "created": [],
1009            "updated": [],
1010            "destroyed": [],
1011            "acmeCorpReplayToken": "rt-99"
1012        });
1013        let resp: ChangesResponse = serde_json::from_value(raw).unwrap();
1014        assert_eq!(
1015            resp.extra
1016                .get("acmeCorpReplayToken")
1017                .and_then(|v| v.as_str()),
1018            Some("rt-99")
1019        );
1020        let back = serde_json::to_value(&resp).unwrap();
1021        assert_eq!(back["acmeCorpReplayToken"], "rt-99");
1022    }
1023
1024    /// Pins the `#[serde(flatten)] extra` interaction with the typed
1025    /// `updated_properties: Option<Vec<String>>` field on `ChangesResponse`:
1026    ///
1027    /// - Wire `"updatedProperties": null` MUST be consumed by the typed
1028    ///   field (deserialized as `None`) and MUST NOT leak into `extra`.
1029    /// - Vendor fields at the top level — including ones whose value is
1030    ///   a nested object — MUST land in `extra` and survive round-trip.
1031    ///
1032    /// Without this regression test, a future serde or `#[serde(flatten)]`
1033    /// behavior change could silently move the null-valued typed key into
1034    /// `extra` (or fail to consume it from `extra` on the serialize side),
1035    /// breaking the wire-format contract for any caller relying on either
1036    /// the absence of `updatedProperties` from `extra` after parse or on
1037    /// vendor extras being preserved alongside an explicit null. Filed
1038    /// under bd:JMAP-6xs8.8.
1039    #[test]
1040    fn changes_response_null_updated_properties_and_extras_coexist() {
1041        let raw = json!({
1042            "accountId": "A1",
1043            "oldState": "s0",
1044            "newState": "s1",
1045            "hasMoreChanges": false,
1046            "created": [],
1047            "updated": ["B"],
1048            "destroyed": [],
1049            "updatedProperties": null,
1050            "acmeCorpReplayToken": "rt-99",
1051            "acmeCorpMetadata": { "requestId": "r1", "trace": "x" }
1052        });
1053
1054        let resp: ChangesResponse = serde_json::from_value(raw.clone()).expect("must deserialize");
1055
1056        // The typed field consumed the explicit null.
1057        assert_eq!(
1058            resp.updated_properties,
1059            Some(None),
1060            "explicit null updatedProperties must deserialize as Some(None)"
1061        );
1062
1063        // The typed key MUST NOT have leaked into `extra` — flatten is
1064        // supposed to visit only the keys the named fields did not
1065        // consume, regardless of whether the consumed value was null.
1066        assert!(
1067            !resp.extra.contains_key("updatedProperties"),
1068            "updatedProperties must not appear in extra after the typed \
1069             field consumed it (was: {:?})",
1070            resp.extra
1071        );
1072
1073        // Top-level vendor fields land in `extra`, including one whose
1074        // value is itself a nested object.
1075        assert_eq!(
1076            resp.extra
1077                .get("acmeCorpReplayToken")
1078                .and_then(|v| v.as_str()),
1079            Some("rt-99")
1080        );
1081        let nested = resp
1082            .extra
1083            .get("acmeCorpMetadata")
1084            .and_then(|v| v.as_object())
1085            .expect("acmeCorpMetadata must be a nested object in extra");
1086        assert_eq!(nested.get("requestId").and_then(|v| v.as_str()), Some("r1"));
1087        assert_eq!(nested.get("trace").and_then(|v| v.as_str()), Some("x"));
1088
1089        // Round-trip: serialize and reparse, all three properties
1090        // (null updatedProperties, two vendor extras) must survive.
1091        let back = serde_json::to_value(&resp).expect("must serialize");
1092
1093        // draft-ietf-jmap-metadata-05 §3.3: updatedProperties "is always
1094        // present, and is null when updated is empty", so an explicit
1095        // null is re-emitted rather than dropped.
1096        assert_eq!(
1097            back.get("updatedProperties"),
1098            Some(&serde_json::Value::Null),
1099            "explicit null updatedProperties must serialize as null: {back}"
1100        );
1101        assert_eq!(back["acmeCorpReplayToken"], "rt-99");
1102        assert_eq!(back["acmeCorpMetadata"]["requestId"], "r1");
1103        assert_eq!(back["acmeCorpMetadata"]["trace"], "x");
1104
1105        // Reparse the serialized form and confirm equivalence on the
1106        // typed surface + extras.
1107        let resp2: ChangesResponse = serde_json::from_value(back).expect("reparse must succeed");
1108        assert_eq!(resp2.updated_properties, Some(None));
1109        assert_eq!(resp2.extra, resp.extra);
1110    }
1111
1112    /// `SetResponse.extra` captures vendor fields and preserves them.
1113    #[test]
1114    fn set_response_preserves_vendor_extras() {
1115        let raw = json!({
1116            "accountId": "A1",
1117            "oldState": "s1",
1118            "newState": "s2",
1119            "acmeCorpTransactionId": "txn-abc"
1120        });
1121        let resp: SetResponse<serde_json::Value> = serde_json::from_value(raw).unwrap();
1122        assert_eq!(
1123            resp.extra
1124                .get("acmeCorpTransactionId")
1125                .and_then(|v| v.as_str()),
1126            Some("txn-abc")
1127        );
1128        let back = serde_json::to_value(&resp).unwrap();
1129        assert_eq!(back["acmeCorpTransactionId"], "txn-abc");
1130    }
1131
1132    /// `QueryResponse.extra` captures vendor fields and preserves them.
1133    #[test]
1134    fn query_response_preserves_vendor_extras() {
1135        let raw = json!({
1136            "accountId": "A1",
1137            "queryState": "qs1",
1138            "canCalculateChanges": false,
1139            "position": 0,
1140            "ids": [],
1141            "total": null,
1142            "limit": null,
1143            "acmeCorpSearchTimingMs": 17
1144        });
1145        let resp: QueryResponse = serde_json::from_value(raw).unwrap();
1146        assert_eq!(
1147            resp.extra
1148                .get("acmeCorpSearchTimingMs")
1149                .and_then(|v| v.as_u64()),
1150            Some(17)
1151        );
1152        let back = serde_json::to_value(&resp).unwrap();
1153        assert_eq!(back["acmeCorpSearchTimingMs"], 17);
1154    }
1155
1156    /// `QueryChangesResponse.extra` captures vendor fields and preserves them.
1157    #[test]
1158    fn query_changes_response_preserves_vendor_extras() {
1159        let raw = json!({
1160            "accountId": "A1",
1161            "oldQueryState": "qs0",
1162            "newQueryState": "qs1",
1163            "total": null,
1164            "removed": [],
1165            "added": [],
1166            "acmeCorpDeltaToken": "dt-2"
1167        });
1168        let resp: QueryChangesResponse = serde_json::from_value(raw).unwrap();
1169        assert_eq!(
1170            resp.extra
1171                .get("acmeCorpDeltaToken")
1172                .and_then(|v| v.as_str()),
1173            Some("dt-2")
1174        );
1175        let back = serde_json::to_value(&resp).unwrap();
1176        assert_eq!(back["acmeCorpDeltaToken"], "dt-2");
1177    }
1178
1179    /// `AddedItem.extra` captures vendor fields and preserves them.
1180    #[test]
1181    fn added_item_preserves_vendor_extras() {
1182        let raw = json!({
1183            "id": "x",
1184            "index": 0,
1185            "acmeCorpHighlight": true
1186        });
1187        let item = AddedItem::deserialize(&raw).unwrap();
1188        assert_eq!(
1189            item.extra
1190                .get("acmeCorpHighlight")
1191                .and_then(|v| v.as_bool()),
1192            Some(true)
1193        );
1194        let back = serde_json::to_value(&item).unwrap();
1195        assert_eq!(back["acmeCorpHighlight"], true);
1196    }
1197
1198    /// Empty extras must NOT serialize as a key on the wire — the
1199    /// `skip_serializing_if = "serde_json::Map::is_empty"` attribute keeps
1200    /// the wire shape byte-identical to the pre-migration form when no
1201    /// vendor fields are present.
1202    #[test]
1203    fn empty_extras_omitted_from_wire() {
1204        let resp = AddedItem {
1205            id: Id::from("z"),
1206            index: 1,
1207            extra: serde_json::Map::new(),
1208        };
1209        let serialized = serde_json::to_value(&resp).expect("must serialize");
1210        let obj = serialized.as_object().expect("must be object");
1211        assert_eq!(
1212            obj.len(),
1213            2,
1214            "empty extras must not add any wire keys; got {serialized}"
1215        );
1216        assert!(obj.contains_key("id"));
1217        assert!(obj.contains_key("index"));
1218    }
1219
1220    // Oracle: workspace map-ordering policy (bd:JMAP-pdux) — wire-format
1221    // maps serialize in sorted key order. Input keys are written out of
1222    // order; expected bytes are hand-written.
1223    #[test]
1224    fn set_response_maps_serialize_in_sorted_key_order() {
1225        let raw = r#"{
1226            "accountId": "a1",
1227            "newState": "s2",
1228            "created": {"k2": {"id": "id2"}, "k1": {"id": "id1"}},
1229            "notUpdated": {"id9": {"type": "notFound"}, "id8": {"type": "notFound"}}
1230        }"#;
1231        let resp: SetResponse<serde_json::Value> = serde_json::from_str(raw).expect("deserialize");
1232        let j = serde_json::to_string(&resp).expect("serialize");
1233        assert!(
1234            j.contains(r#""created":{"k1":{"id":"id1"},"k2":{"id":"id2"}}"#),
1235            "created keys must be sorted: {j}"
1236        );
1237        assert!(
1238            j.contains(r#""notUpdated":{"id8":{"type":"notFound"},"id9":{"type":"notFound"}}"#),
1239            "notUpdated keys must be sorted: {j}"
1240        );
1241    }
1242
1243    /// RFC 8620 §5.3: `created` holds only "properties of the created Foo
1244    /// object that were not sent by the client". Oracle: the Email/set
1245    /// response in RFC 8621 §7 (page 66), `...` elision removed. Its
1246    /// `created` entry has no `mailboxIds`, `keywords` etc., so it would
1247    /// fail to parse as a full Email; it must parse as [`PartialObject`].
1248    #[test]
1249    fn set_response_partial_object_parses_rfc8621_created() {
1250        let raw = json!({
1251            "accountId": "ue150411c",
1252            "oldState": "780839",
1253            "newState": "780842",
1254            "created": {
1255                "k1546": {
1256                    "id": "Md45b47b4877521042cec0938",
1257                    "blobId": "Ge8de6c9f6de198239b982ea214e0f3a704e4af74",
1258                    "threadId": "Td957e72e89f516dc",
1259                    "size": 11721
1260                }
1261            },
1262            "updated": { "Mabc": null, "Mdef": { "size": 12 } },
1263            "destroyed": ["Mf40b5f831efa7233b9eb1c7f"]
1264        });
1265        let resp: SetResponse<PartialObject> = serde_json::from_value(raw).unwrap();
1266        let created = &resp.created;
1267        let k = &created["k1546"];
1268        assert_eq!(
1269            k.id.as_ref().map(|i| i.as_ref()),
1270            Some("Md45b47b4877521042cec0938")
1271        );
1272        assert_eq!(k.extra["threadId"], "Td957e72e89f516dc");
1273        assert_eq!(k.extra["size"], 11721);
1274        assert!(
1275            !k.extra.contains_key("id"),
1276            "id must not be duplicated in extra"
1277        );
1278        let updated = &resp.updated;
1279        assert_eq!(updated[&Id::from("Mabc")], None);
1280        let def = updated[&Id::from("Mdef")].as_ref().unwrap();
1281        assert_eq!(def.id, None);
1282        assert_eq!(def.extra["size"], 12);
1283    }
1284
1285    /// A created entry with no `id` (RFC 8620 §5.3: "such as the id in
1286    /// most object types", so not all) and with only client-omitted
1287    /// defaults must still parse, and serialize back without an `id` key.
1288    #[test]
1289    fn partial_object_without_id_round_trips() {
1290        let raw = json!({ "isSubscribed": false, "sortOrder": 0 });
1291        let p: PartialObject = serde_json::from_value(raw.clone()).unwrap();
1292        assert_eq!(p.id, None);
1293        assert_eq!(serde_json::to_value(&p).unwrap(), raw);
1294    }
1295
1296    /// RFC 8620 §5.4 response shape. Oracle: the Email/copy response in
1297    /// RFC 8621 §7 (page 67), verbatim.
1298    #[test]
1299    fn copy_response_parses_rfc8621_example() {
1300        let raw = json!({
1301            "fromAccountId": "ue150411c",
1302            "accountId": "u6c6c41ac",
1303            "oldState": "7ee7e9263a6d",
1304            "newState": "5a0d2447ed26",
1305            "created": {
1306                "k45": {
1307                    "id": "M138f9954a5cd2423daeafa55",
1308                    "blobId": "G6b9fb047cba722c48c611e79233d057c6b0b74e8",
1309                    "threadId": "T2f242ea424a4079a",
1310                    "size": 11721
1311                }
1312            },
1313            "notCreated": null
1314        });
1315        let resp: CopyResponse<PartialObject> = serde_json::from_value(raw).unwrap();
1316        assert_eq!(resp.from_account_id.as_ref(), "ue150411c");
1317        assert_eq!(resp.account_id.as_ref(), "u6c6c41ac");
1318        assert_eq!(
1319            resp.old_state.as_ref().map(|s| s.as_ref()),
1320            Some("7ee7e9263a6d")
1321        );
1322        assert_eq!(resp.new_state.as_ref(), "5a0d2447ed26");
1323        let k45 = &resp.created["k45"];
1324        assert_eq!(
1325            k45.id.as_ref().map(|i| i.as_ref()),
1326            Some("M138f9954a5cd2423daeafa55")
1327        );
1328        assert_eq!(
1329            k45.extra["blobId"],
1330            "G6b9fb047cba722c48c611e79233d057c6b0b74e8"
1331        );
1332        assert!(resp.not_created.is_empty());
1333        assert!(resp.extra.is_empty());
1334    }
1335
1336    /// RFC 8620 §5.3: `created` "is null if no Foo objects were
1337    /// successfully created", `destroyed` is "null if none", and the
1338    /// `not*` maps are "null if none". Null and absent both mean none.
1339    #[test]
1340    fn set_response_null_and_absent_results_decode_empty() {
1341        let raw = json!({
1342            "accountId": "A1", "oldState": null, "newState": "s2",
1343            "created": null, "updated": null, "destroyed": null,
1344            "notCreated": null
1345        });
1346        let resp: SetResponse<PartialObject> = serde_json::from_value(raw).unwrap();
1347        assert!(resp.created.is_empty());
1348        assert!(resp.updated.is_empty());
1349        assert!(resp.destroyed.is_empty());
1350        assert!(resp.not_created.is_empty());
1351        assert!(resp.not_updated.is_empty());
1352        assert!(resp.not_destroyed.is_empty());
1353    }
1354
1355    /// Decision 67: a `/set` response without `newState` (which RFC 8620
1356    /// §5.3 requires) or `oldState` still decodes, keeping its results;
1357    /// `new_state` is the empty state and `old_state` is `None`.
1358    #[test]
1359    fn set_response_without_new_or_old_state_decodes() {
1360        let raw = json!({
1361            "accountId": "A1",
1362            "notDestroyed": { "X9": { "type": "notFound" } }
1363        });
1364        let resp: SetResponse<PartialObject> = serde_json::from_value(raw).unwrap();
1365        assert_eq!(resp.new_state, "");
1366        assert_eq!(resp.old_state, None);
1367        assert_eq!(
1368            resp.not_destroyed[&Id::from("X9")].error_type.as_str(),
1369            "notFound"
1370        );
1371        assert!(resp.extra.is_empty(), "no stray extras: {:?}", resp.extra);
1372    }
1373
1374    /// A `/set` response with `newState` but no `oldState` (Stalwart's
1375    /// EmailSubmission/set create) keeps the server's `newState`.
1376    #[test]
1377    fn set_response_without_old_state_keeps_new_state() {
1378        let raw = json!({ "accountId": "A1", "newState": "s2" });
1379        let resp: SetResponse<PartialObject> = serde_json::from_value(raw).unwrap();
1380        assert_eq!(resp.new_state, "s2");
1381        assert_eq!(resp.old_state, None);
1382    }
1383
1384    /// RFC 8620 §5.3 / §5.4: a result field with no entries is `null` on
1385    /// the wire, never `{}` or `[]`.
1386    #[test]
1387    fn set_and_copy_responses_encode_empty_results_as_null() {
1388        let set = json!({
1389            "accountId": "A1", "oldState": "s1", "newState": "s2",
1390            "created": null, "updated": null, "destroyed": ["X1"],
1391            "notCreated": null, "notUpdated": null, "notDestroyed": null
1392        });
1393        let resp: SetResponse<PartialObject> = serde_json::from_value(set.clone()).unwrap();
1394        assert_eq!(serde_json::to_value(&resp).unwrap(), set);
1395
1396        let copy = json!({
1397            "fromAccountId": "A0", "accountId": "A1",
1398            "oldState": null, "newState": "s2",
1399            "created": null, "notCreated": null
1400        });
1401        let resp: CopyResponse<PartialObject> = serde_json::from_value(copy.clone()).unwrap();
1402        assert_eq!(serde_json::to_value(&resp).unwrap(), copy);
1403    }
1404
1405    /// RFC 8620 §5.4: `oldState` is "String|null" and `fromAccountId` is
1406    /// required; a response without it is not a /copy response.
1407    #[test]
1408    fn copy_response_requires_from_account_id() {
1409        let ok = json!({
1410            "fromAccountId": "A0", "accountId": "A1",
1411            "oldState": null, "newState": "s2",
1412            "notCreated": { "c1": { "type": "alreadyExists" } }
1413        });
1414        let resp: CopyResponse<PartialObject> = serde_json::from_value(ok).unwrap();
1415        assert!(resp.old_state.is_none());
1416        assert_eq!(
1417            resp.not_created["c1"].error_type,
1418            SetErrorType::AlreadyExists
1419        );
1420        let missing = json!({ "accountId": "A1", "newState": "s2" });
1421        assert!(serde_json::from_value::<CopyResponse<PartialObject>>(missing).is_err());
1422    }
1423}