Skip to main content

jmap_types/
i18n.rs

1//! Localized display text (draft-atwood-jmap-updates-00 §3–§5).
2//!
3//! The `urn:ietf:params:jmap:i18n` capability adds two properties to
4//! every data type that has localizable properties, modelled on
5//! JSCalendar (RFC 8984 §4.2.8 and §4.6.1):
6//!
7//! - `locale` (`String|null`): the [`LanguageTag`] of the base values;
8//! - `localizations` (`String[PatchObject]|null`): a [`Localizations`]
9//!   map from language tag to a [`PatchObject`] over the localizable
10//!   properties.
11//!
12//! It also adds a `language` argument (a list of [`LanguageRange`]s) to
13//! `/get`, `/query` and `/queryChanges`; [`lookup`] implements the
14//! RFC 4647 §3.4 Lookup that picks one tag per object, and
15//! [`localized_view`] builds the single-language `/get` view.
16//!
17//! The `/set` side is [`parse_locale`] and [`check_localizations`],
18//! which turn wire values into the validated types or an
19//! `invalidProperties` [`SetError`], and [`prune_stale_localizations`],
20//! which drops translations of a base value that an update changed.
21//!
22//! A data type declares its localizable properties with
23//! [`JmapObject::LOCALIZABLE`](crate::JmapObject::LOCALIZABLE).
24//! Design: `docs/design/updates.md` (decisions 27 to 31).
25
26use crate::{PatchObject, SetError, SetErrorType};
27use serde::de::{self, MapAccess, Visitor};
28use serde::{Deserialize, Deserializer, Serialize, Serializer};
29use serde_json::{Map, Value};
30use std::collections::BTreeMap;
31use std::fmt;
32use std::str::FromStr;
33
34/// The capability URI (draft-atwood-jmap-updates-00 §3, §10).
35pub const JMAP_I18N_URI: &str = "urn:ietf:params:jmap:i18n";
36
37/// The Session `capabilities` value of [`JMAP_I18N_URI`]: an empty
38/// object (draft-atwood-jmap-updates-00 §3).
39#[non_exhaustive]
40#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
41pub struct I18nCapability {
42    /// Catch-all for vendor / site / private extension fields.
43    #[serde(flatten, default, skip_serializing_if = "Map::is_empty")]
44    pub extra: Map<String, Value>,
45}
46
47/// The `accountCapabilities` value of [`JMAP_I18N_URI`]: an empty object
48/// (draft-atwood-jmap-updates-00 §3).
49///
50/// Present on an account only when the server supports localizations
51/// for it. The draft defines no account-level language preference.
52#[non_exhaustive]
53#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
54pub struct I18nAccountCapability {
55    /// Catch-all for vendor / site / private extension fields.
56    #[serde(flatten, default, skip_serializing_if = "Map::is_empty")]
57    pub extra: Map<String, Value>,
58}
59
60// ---------------------------------------------------------------------------
61// Language tags and ranges
62// ---------------------------------------------------------------------------
63
64/// Why a string is not a well-formed [`LanguageTag`] or
65/// [`LanguageRange`].
66#[non_exhaustive]
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub enum LanguageTagError {
69    /// The string is empty, or has an empty subtag (`"en--US"`, `"en-"`).
70    EmptySubtag,
71    /// A subtag has a character other than an ASCII letter or digit, or
72    /// is longer than eight characters.
73    InvalidSubtag,
74    /// Every subtag is well-formed but their sequence matches no
75    /// production of the grammar (RFC 5646 §2.1 or RFC 4647 §2.1).
76    IllFormed,
77}
78
79impl fmt::Display for LanguageTagError {
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        f.write_str(match self {
82            Self::EmptySubtag => "language tag has an empty subtag",
83            Self::InvalidSubtag => "language tag subtag is not 1 to 8 ASCII letters or digits",
84            Self::IllFormed => "language tag does not match the RFC 5646 grammar",
85        })
86    }
87}
88
89impl std::error::Error for LanguageTagError {}
90
91/// An RFC 5646 language tag, checked to be well-formed (§2.2.9) and
92/// held in the canonical case of §2.1.1.
93///
94/// Tags are case-insensitive (§2.1.1), so parsing folds the case:
95/// `"EN-us"` and `"en-US"` give equal values, both rendered `"en-US"`.
96/// Equality, ordering and hashing therefore ignore the case of the
97/// input. The check is well-formedness only: subtags are not looked up
98/// in the IANA registry, so `"qq-Zzzz"` is accepted.
99///
100/// ```rust
101/// use jmap_types::i18n::LanguageTag;
102///
103/// let tag: LanguageTag = "sr-latn-rs".parse().unwrap();
104/// assert_eq!(tag.as_str(), "sr-Latn-RS");
105/// assert!("en--US".parse::<LanguageTag>().is_err());
106/// ```
107#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
108pub struct LanguageTag(String);
109
110/// RFC 5646 §2.1 `irregular` grandfathered tags, lowercase. They are the
111/// only well-formed tags that the `langtag` production does not match;
112/// the `regular` ones (`zh-min-nan`, `art-lojban`, ...) match it.
113const IRREGULAR: &[&str] = &[
114    "en-gb-oed",
115    "i-ami",
116    "i-bnn",
117    "i-default",
118    "i-enochian",
119    "i-hak",
120    "i-klingon",
121    "i-lux",
122    "i-mingo",
123    "i-navajo",
124    "i-pwn",
125    "i-tao",
126    "i-tay",
127    "i-tsu",
128    "sgn-be-fr",
129    "sgn-be-nl",
130    "sgn-ch-de",
131];
132
133/// Split on `-` and check each subtag is 1 to 8 ASCII alphanumerics.
134fn subtags(s: &str) -> Result<Vec<&str>, LanguageTagError> {
135    let parts: Vec<&str> = s.split('-').collect();
136    for p in &parts {
137        if p.is_empty() {
138            return Err(LanguageTagError::EmptySubtag);
139        }
140        if p.len() > 8 || !p.bytes().all(|b| b.is_ascii_alphanumeric()) {
141            return Err(LanguageTagError::InvalidSubtag);
142        }
143    }
144    Ok(parts)
145}
146
147fn is_alpha(s: &str) -> bool {
148    s.bytes().all(|b| b.is_ascii_alphabetic())
149}
150
151fn is_digit(s: &str) -> bool {
152    s.bytes().all(|b| b.is_ascii_digit())
153}
154
155/// RFC 5646 §2.1 `variant = 5*8alphanum / (DIGIT 3alphanum)`.
156fn is_variant(s: &str) -> bool {
157    (5..=8).contains(&s.len()) || (s.len() == 4 && s.as_bytes()[0].is_ascii_digit())
158}
159
160/// `true` when `parts` (already 1*8alphanum each) match the RFC 5646
161/// `langtag` production.
162fn is_langtag(parts: &[&str]) -> bool {
163    let mut i = 0;
164    let n = parts.len();
165    // language = 2*3ALPHA ["-" extlang] / 4ALPHA / 5*8ALPHA
166    let lang = parts[0];
167    if !is_alpha(lang) || lang.len() < 2 {
168        return false;
169    }
170    i += 1;
171    if lang.len() <= 3 {
172        // extlang = 3ALPHA *2("-" 3ALPHA)
173        let mut ext = 0;
174        while ext < 3 && i < n && parts[i].len() == 3 && is_alpha(parts[i]) {
175            ext += 1;
176            i += 1;
177        }
178    }
179    // script = 4ALPHA
180    if i < n && parts[i].len() == 4 && is_alpha(parts[i]) {
181        i += 1;
182    }
183    // region = 2ALPHA / 3DIGIT
184    if i < n
185        && ((parts[i].len() == 2 && is_alpha(parts[i]))
186            || (parts[i].len() == 3 && is_digit(parts[i])))
187    {
188        i += 1;
189    }
190    // *("-" variant)
191    while i < n && is_variant(parts[i]) {
192        i += 1;
193    }
194    // *("-" extension); extension = singleton 1*("-" (2*8alphanum))
195    while i < n && parts[i].len() == 1 && !parts[i].eq_ignore_ascii_case("x") {
196        i += 1;
197        let start = i;
198        while i < n && parts[i].len() >= 2 {
199            i += 1;
200        }
201        if i == start {
202            return false;
203        }
204    }
205    // ["-" privateuse]
206    if i < n && parts[i].eq_ignore_ascii_case("x") {
207        return is_privateuse(&parts[i..]);
208    }
209    i == n
210}
211
212/// RFC 5646 §2.1 `privateuse = "x" 1*("-" (1*8alphanum))`; `parts[0]`
213/// is the `x`.
214fn is_privateuse(parts: &[&str]) -> bool {
215    parts.len() >= 2
216}
217
218/// RFC 5646 §2.1.1 canonical case: lowercase, except that a two-letter
219/// subtag is uppercase and a four-letter subtag titlecase when it is not
220/// the first subtag and no singleton precedes it.
221fn canonical_case(parts: &[&str]) -> String {
222    let mut out = String::new();
223    let mut after_singleton = false;
224    for (i, p) in parts.iter().enumerate() {
225        if i > 0 {
226            out.push('-');
227        }
228        if i > 0 && !after_singleton && p.len() == 2 {
229            out.push_str(&p.to_ascii_uppercase());
230        } else if i > 0 && !after_singleton && p.len() == 4 {
231            let lower = p.to_ascii_lowercase();
232            let mut chars = lower.chars();
233            if let Some(c) = chars.next() {
234                out.push(c.to_ascii_uppercase());
235                out.push_str(chars.as_str());
236            }
237        } else {
238            out.push_str(&p.to_ascii_lowercase());
239        }
240        if p.len() == 1 {
241            after_singleton = true;
242        }
243    }
244    out
245}
246
247impl LanguageTag {
248    /// Parse `s` as an RFC 5646 `Language-Tag` and fold it to canonical
249    /// case.
250    ///
251    /// # Errors
252    ///
253    /// [`LanguageTagError`] when `s` is not well-formed.
254    pub fn parse(s: &str) -> Result<Self, LanguageTagError> {
255        let parts = subtags(s)?;
256        let lower = s.to_ascii_lowercase();
257        let ok = if parts[0].eq_ignore_ascii_case("x") {
258            is_privateuse(&parts)
259        } else {
260            IRREGULAR.contains(&lower.as_str()) || is_langtag(&parts)
261        };
262        if ok {
263            Ok(Self(canonical_case(&parts)))
264        } else {
265            Err(LanguageTagError::IllFormed)
266        }
267    }
268
269    /// The tag in canonical case.
270    pub fn as_str(&self) -> &str {
271        &self.0
272    }
273}
274
275impl FromStr for LanguageTag {
276    type Err = LanguageTagError;
277    fn from_str(s: &str) -> Result<Self, Self::Err> {
278        Self::parse(s)
279    }
280}
281
282impl fmt::Display for LanguageTag {
283    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
284        f.write_str(&self.0)
285    }
286}
287
288impl AsRef<str> for LanguageTag {
289    fn as_ref(&self) -> &str {
290        &self.0
291    }
292}
293
294impl Serialize for LanguageTag {
295    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
296        s.serialize_str(&self.0)
297    }
298}
299
300impl<'de> Deserialize<'de> for LanguageTag {
301    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
302        let s = String::deserialize(d)?;
303        Self::parse(&s).map_err(de::Error::custom)
304    }
305}
306
307/// An RFC 4647 §2.1 basic language range: `"*"`, or a primary subtag
308/// of 1 to 8 letters followed by subtags of 1 to 8 letters or digits.
309///
310/// Held in the canonical case of a [`LanguageTag`] (RFC 5646 §2.1.1),
311/// so that equal ranges render equally; matching ignores case either
312/// way (RFC 4647 §2).
313///
314/// ```rust
315/// use jmap_types::i18n::LanguageRange;
316///
317/// let r: LanguageRange = "DE-ch".parse().unwrap();
318/// assert_eq!(r.as_str(), "de-CH");
319/// assert!("*".parse::<LanguageRange>().unwrap().is_wildcard());
320/// ```
321#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
322pub struct LanguageRange(String);
323
324impl LanguageRange {
325    /// Parse `s` as an RFC 4647 §2.1 `language-range`.
326    ///
327    /// # Errors
328    ///
329    /// [`LanguageTagError`] when `s` is not a basic language range.
330    pub fn parse(s: &str) -> Result<Self, LanguageTagError> {
331        if s == "*" {
332            return Ok(Self(s.to_owned()));
333        }
334        let parts = subtags(s)?;
335        if !is_alpha(parts[0]) {
336            return Err(LanguageTagError::IllFormed);
337        }
338        Ok(Self(canonical_case(&parts)))
339    }
340
341    /// The range in canonical case.
342    pub fn as_str(&self) -> &str {
343        &self.0
344    }
345
346    /// `true` for the wildcard range `"*"`.
347    pub fn is_wildcard(&self) -> bool {
348        self.0 == "*"
349    }
350}
351
352impl FromStr for LanguageRange {
353    type Err = LanguageTagError;
354    fn from_str(s: &str) -> Result<Self, Self::Err> {
355        Self::parse(s)
356    }
357}
358
359impl fmt::Display for LanguageRange {
360    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
361        f.write_str(&self.0)
362    }
363}
364
365impl Serialize for LanguageRange {
366    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
367        s.serialize_str(&self.0)
368    }
369}
370
371impl<'de> Deserialize<'de> for LanguageRange {
372    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
373        let s = String::deserialize(d)?;
374        Self::parse(&s).map_err(de::Error::custom)
375    }
376}
377
378/// The language ranges of an `Accept-Language` field value (RFC 9110
379/// §12.5.4), most preferred first: ordered by quality value, ties kept in
380/// header order, with `q=0` ranges ("not acceptable") and malformed items
381/// left out. The result is a priority list for [`lookup`].
382///
383/// ```rust
384/// use jmap_types::i18n::accept_language_ranges;
385///
386/// let ranges = accept_language_ranges("fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5");
387/// let tags: Vec<&str> = ranges.iter().map(|r| r.as_str()).collect();
388/// assert_eq!(tags, ["fr-CH", "fr", "en", "de", "*"]);
389/// ```
390pub fn accept_language_ranges(value: &str) -> Vec<LanguageRange> {
391    let mut weighted: Vec<(u16, usize, LanguageRange)> = value
392        .split(',')
393        .enumerate()
394        .filter_map(|(i, item)| {
395            let mut parts = item.split(';');
396            let range = LanguageRange::parse(parts.next()?.trim()).ok()?;
397            // The parameter name is case-insensitive (RFC 9110 §12.4.2).
398            let q = match parts.find_map(|p| {
399                let p = p.trim();
400                (p.len() >= 2 && p[..2].eq_ignore_ascii_case("q=")).then(|| &p[2..])
401            }) {
402                None => 1000,
403                Some(q) => qvalue(q.trim())?,
404            };
405            (q > 0).then_some((q, i, range))
406        })
407        .collect();
408    weighted.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
409    weighted.into_iter().map(|(_, _, r)| r).collect()
410}
411
412/// An RFC 9110 §12.4.2 `qvalue` in thousandths: `0` to `1`, with at
413/// most three decimal places.
414fn qvalue(s: &str) -> Option<u16> {
415    let (int, frac) = s.split_once('.').unwrap_or((s, ""));
416    if frac.len() > 3 || !frac.bytes().all(|b| b.is_ascii_digit()) {
417        return None;
418    }
419    let frac_val: u16 = format!("{frac:0<3}").parse().ok()?;
420    match int {
421        "0" => Some(frac_val),
422        "1" if frac_val == 0 => Some(1000),
423        _ => None,
424    }
425}
426
427/// RFC 4647 §3.4 Lookup: the tag in `available` that best matches the
428/// priority list `ranges`, or `None` when nothing matches and the
429/// default applies.
430///
431/// Each range is tried in order. A range that matches no tag is
432/// shortened by its last subtag, and also by a single-letter subtag left
433/// at its end, until it matches or is empty; ranges are never widened,
434/// so `"de"` does not match `"de-CH"`. A `"*"` that other ranges follow
435/// is skipped; a `"*"` with no range after it ends the search with the
436/// default. Matching ignores case.
437///
438/// draft-atwood-jmap-updates-00 §4.2.1 passes the `localizations` keys
439/// plus the object's `locale` as `available`, and uses the object's
440/// `locale` as the default.
441///
442/// ```rust
443/// use jmap_types::i18n::{LanguageRange, LanguageTag, lookup};
444///
445/// let tags: Vec<LanguageTag> = ["fr", "de"].iter().map(|t| t.parse().unwrap()).collect();
446/// let ranges: Vec<LanguageRange> = ["fr-CH", "de"].iter().map(|r| r.parse().unwrap()).collect();
447/// assert_eq!(lookup(&ranges, &tags).map(|t| t.as_str()), Some("fr"));
448/// ```
449pub fn lookup<'a, I>(ranges: &[LanguageRange], available: I) -> Option<&'a LanguageTag>
450where
451    I: IntoIterator<Item = &'a LanguageTag>,
452    I::IntoIter: Clone,
453{
454    let available = available.into_iter();
455    for (i, range) in ranges.iter().enumerate() {
456        if range.is_wildcard() {
457            if i + 1 == ranges.len() {
458                return None;
459            }
460            continue;
461        }
462        let mut candidate = range.as_str();
463        loop {
464            if let Some(tag) = available
465                .clone()
466                .find(|t| t.as_str().eq_ignore_ascii_case(candidate))
467            {
468                return Some(tag);
469            }
470            let Some(cut) = candidate.rfind('-') else {
471                break;
472            };
473            candidate = &candidate[..cut];
474            // Drop a singleton left at the end ("en-a-bbb" -> "en-a" -> "en").
475            if let Some(cut) = candidate.rfind('-')
476                && candidate.len() - cut == 2
477            {
478                candidate = &candidate[..cut];
479            }
480        }
481    }
482    None
483}
484
485// ---------------------------------------------------------------------------
486// Localizable properties and the localizations map
487// ---------------------------------------------------------------------------
488
489/// One localizable property of a data type: its wire name and whether
490/// its type allows `null` (draft-atwood-jmap-updates-00 §4.1).
491///
492/// Every localizable property in the draft is a `String` or a
493/// `String|null`.
494#[non_exhaustive]
495#[derive(Debug, Clone, Copy, PartialEq, Eq)]
496pub struct LocalizableProperty {
497    /// Wire name, e.g. `"name"`.
498    pub name: &'static str,
499    /// `true` for a `String|null` property, whose localized value may be
500    /// `null` ("no value in that language").
501    pub nullable: bool,
502}
503
504impl LocalizableProperty {
505    /// A property named `name`, nullable when `nullable`.
506    pub const fn new(name: &'static str, nullable: bool) -> Self {
507        Self { name, nullable }
508    }
509}
510
511/// The `localizations` property: a map from [`LanguageTag`] to a
512/// [`PatchObject`] that gives the localizable properties in that
513/// language (draft-atwood-jmap-updates-00 §4.1).
514///
515/// Deserializing parses each key as a tag in canonical case and rejects
516/// two keys that differ only in case. It does not check the patches;
517/// [`check_localizations`] does that against the data type's
518/// [`LocalizableProperty`] list.
519#[non_exhaustive]
520#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
521#[serde(transparent)]
522pub struct Localizations(BTreeMap<LanguageTag, PatchObject>);
523
524impl Localizations {
525    /// The patch for `tag`, if any.
526    pub fn get(&self, tag: &LanguageTag) -> Option<&PatchObject> {
527        self.0.get(tag)
528    }
529
530    /// The localizations, in canonical tag order.
531    pub fn iter(&self) -> impl Iterator<Item = (&LanguageTag, &PatchObject)> {
532        self.0.iter()
533    }
534
535    /// The language tags, in canonical order.
536    pub fn tags(&self) -> impl Iterator<Item = &LanguageTag> + Clone {
537        self.0.keys()
538    }
539
540    /// `true` when there is no localization.
541    pub fn is_empty(&self) -> bool {
542        self.0.is_empty()
543    }
544
545    /// Number of localizations.
546    pub fn len(&self) -> usize {
547        self.0.len()
548    }
549}
550
551impl<'de> Deserialize<'de> for Localizations {
552    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
553        struct V;
554        impl<'de> Visitor<'de> for V {
555            type Value = Localizations;
556            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
557                f.write_str("a map from language tag to PatchObject")
558            }
559            fn visit_map<A: MapAccess<'de>>(self, mut m: A) -> Result<Localizations, A::Error> {
560                let mut out = BTreeMap::new();
561                while let Some((k, v)) = m.next_entry::<String, PatchObject>()? {
562                    let tag = LanguageTag::parse(&k).map_err(de::Error::custom)?;
563                    if out.insert(tag, v).is_some() {
564                        return Err(de::Error::custom(format!(
565                            "duplicate localizations key (ignoring case): {k}"
566                        )));
567                    }
568                }
569                Ok(Localizations(out))
570            }
571        }
572        d.deserialize_map(V)
573    }
574}
575
576// ---------------------------------------------------------------------------
577// /set: validation and pruning
578// ---------------------------------------------------------------------------
579
580fn invalid(property: &str, description: String) -> Box<SetError> {
581    Box::new(
582        SetError::new(SetErrorType::InvalidProperties)
583            .with_properties([property])
584            .with_description(description),
585    )
586}
587
588/// Parse a `/set` `locale` value: `null` or a language tag.
589///
590/// # Errors
591///
592/// An `invalidProperties` [`SetError`] naming `locale` when `value` is
593/// neither `null` nor a well-formed language tag.
594pub fn parse_locale(value: &Value) -> Result<Option<LanguageTag>, Box<SetError>> {
595    match value {
596        Value::Null => Ok(None),
597        Value::String(s) => LanguageTag::parse(s)
598            .map(Some)
599            .map_err(|e| invalid("locale", format!("locale {s:?}: {e}"))),
600        other => Err(invalid(
601            "locale",
602            format!(
603                "locale must be a String or null, not {}",
604                crate::json_type_name(other)
605            ),
606        )),
607    }
608}
609
610/// Check a `/set` `localizations` value against the restrictions of
611/// draft-atwood-jmap-updates-00 §4.1 and return it with its keys in
612/// canonical case (which servers SHOULD store).
613///
614/// `locale` is the object's `locale` after the same create or update.
615/// `null` gives `Ok(None)`. Otherwise the value must be an object whose
616/// keys are language tags, no two equal ignoring case and none equal to
617/// `locale`, and whose values are objects naming only properties in
618/// `properties`, each a String, or `null` when that property is
619/// nullable. The defining specification's length and syntax limits on
620/// localized values are the caller's to apply.
621///
622/// # Errors
623///
624/// An `invalidProperties` [`SetError`] naming `localizations`, whose
625/// description says which rule failed.
626pub fn check_localizations(
627    locale: Option<&LanguageTag>,
628    value: &Value,
629    properties: &[LocalizableProperty],
630) -> Result<Option<Localizations>, Box<SetError>> {
631    let bad = |d: String| invalid("localizations", d);
632    let obj = match value {
633        Value::Null => return Ok(None),
634        Value::Object(o) => o,
635        other => {
636            return Err(bad(format!(
637                "localizations must be an object or null, not {}",
638                crate::json_type_name(other)
639            )));
640        }
641    };
642    let mut out = BTreeMap::new();
643    for (key, patch) in obj {
644        let tag = LanguageTag::parse(key).map_err(|e| bad(format!("key {key:?}: {e}")))?;
645        if locale == Some(&tag) {
646            return Err(bad(format!("key {key:?} equals locale")));
647        }
648        let Value::Object(patch) = patch else {
649            return Err(bad(format!("value for {key:?} is not a PatchObject")));
650        };
651        for (prop, v) in patch {
652            let Some(p) = properties.iter().find(|p| p.name == prop) else {
653                return Err(bad(format!(
654                    "{key:?}: {prop:?} is not a localizable property"
655                )));
656            };
657            match v {
658                Value::String(_) => {}
659                Value::Null if p.nullable => {}
660                Value::Null => {
661                    return Err(bad(format!("{key:?}: {prop:?} cannot be null")));
662                }
663                other => {
664                    return Err(bad(format!(
665                        "{key:?}: {prop:?} must be a String, not {}",
666                        crate::json_type_name(other)
667                    )));
668                }
669            }
670        }
671        if out
672            .insert(tag, PatchObject::from_map(patch.clone()))
673            .is_some()
674        {
675            return Err(bad(format!(
676                "key {key:?} duplicates another key ignoring case"
677            )));
678        }
679    }
680    Ok(Some(Localizations(out)))
681}
682
683/// What a `/set` update `patch` sets inside `localizations`
684/// (draft-atwood-jmap-updates-00 §4.1).
685enum Touched {
686    /// `localizations` as a whole.
687    All,
688    /// Per language: `None` for the whole PatchObject of that language,
689    /// `Some(props)` for those properties inside it.
690    Some(BTreeMap<LanguageTag, Option<Vec<String>>>),
691}
692
693fn touched(patch: &PatchObject) -> Touched {
694    let mut out: BTreeMap<LanguageTag, Option<Vec<String>>> = BTreeMap::new();
695    for key in patch.as_map().keys() {
696        let mut segs = key.splitn(3, '/');
697        if segs.next() != Some("localizations") {
698            continue;
699        }
700        let Some(tag) = segs.next() else {
701            return Touched::All;
702        };
703        let Ok(tag) = LanguageTag::parse(tag) else {
704            continue;
705        };
706        match segs.next() {
707            None => {
708                out.insert(tag, None);
709            }
710            Some(prop) => {
711                // JSON Pointer unescaping (RFC 6901 §4) of the property name.
712                let prop = prop.replace("~1", "/").replace("~0", "~");
713                let entry = out.entry(tag).or_insert_with(|| Some(Vec::new()));
714                if let Some(props) = entry {
715                    props.push(prop);
716                }
717            }
718        }
719    }
720    Touched::Some(out)
721}
722
723/// Drop translations made stale by a `/set` update
724/// (draft-atwood-jmap-updates-00 §4.1).
725///
726/// `old` and `new` are the serialized object before and after `patch`
727/// was applied. For each property of `properties` whose base value
728/// differs between them, and each language whose PatchObject the patch
729/// did not set (not `localizations` as a whole, not
730/// `localizations/<tag>`, and not `localizations/<tag>/<property>`),
731/// the property is removed from that language's PatchObject in `new`,
732/// and a PatchObject left empty is removed. A `localizations` left
733/// empty becomes `null`.
734///
735/// Returns `true` when anything was removed: the caller then includes
736/// `localizations` in the `updated` entry it returns to clients that use
737/// the capability. Malformed stored keys are left as they are.
738///
739/// ```rust
740/// use jmap_types::PatchObject;
741/// use jmap_types::i18n::{LocalizableProperty, prune_stale_localizations};
742/// use serde_json::json;
743///
744/// const PROPS: &[LocalizableProperty] = &[LocalizableProperty::new("name", false)];
745/// let old = json!({"name": "Team", "localizations": {"fr": {"name": "Équipe"}}});
746/// let mut new = json!({"name": "Staff", "localizations": {"fr": {"name": "Équipe"}}});
747/// let patch: PatchObject = serde_json::from_value(json!({"name": "Staff"})).unwrap();
748/// let removed = prune_stale_localizations(
749///     old.as_object().unwrap(), new.as_object_mut().unwrap(), &patch, PROPS);
750/// assert!(removed);
751/// assert_eq!(new["localizations"], json!(null));
752/// ```
753pub fn prune_stale_localizations(
754    old: &Map<String, Value>,
755    new: &mut Map<String, Value>,
756    patch: &PatchObject,
757    properties: &[LocalizableProperty],
758) -> bool {
759    let changed: Vec<&str> = properties
760        .iter()
761        .map(|p| p.name)
762        .filter(|n| old.get(*n) != new.get(*n))
763        .collect();
764    if changed.is_empty() {
765        return false;
766    }
767    let touched = match touched(patch) {
768        Touched::All => return false,
769        Touched::Some(t) => t,
770    };
771    let Some(Value::Object(locs)) = new.get_mut("localizations") else {
772        return false;
773    };
774    let mut removed = false;
775    locs.retain(|key, entry| {
776        let Ok(tag) = LanguageTag::parse(key) else {
777            return true;
778        };
779        let set_here = touched.get(&tag);
780        if matches!(set_here, Some(None)) {
781            return true;
782        }
783        let Value::Object(p) = entry else {
784            return true;
785        };
786        for name in &changed {
787            let protected =
788                matches!(set_here, Some(Some(props)) if props.iter().any(|q| q == name));
789            if !protected && p.remove(*name).is_some() {
790                removed = true;
791            }
792        }
793        !p.is_empty()
794    });
795    if locs.is_empty() {
796        new.insert("localizations".to_owned(), Value::Null);
797    }
798    removed
799}
800
801// ---------------------------------------------------------------------------
802// /get: the single-language view
803// ---------------------------------------------------------------------------
804
805/// The tag that §4.2.1 chooses for `obj` under `ranges`, and the
806/// PatchObject stored for it when it is a key of `localizations`.
807fn choose(
808    obj: &Map<String, Value>,
809    ranges: &[LanguageRange],
810) -> (Option<LanguageTag>, Option<Map<String, Value>>) {
811    let locale = obj
812        .get("locale")
813        .and_then(Value::as_str)
814        .and_then(|s| LanguageTag::parse(s).ok());
815    let mut localizations: BTreeMap<LanguageTag, Map<String, Value>> =
816        match obj.get("localizations") {
817            Some(Value::Object(m)) => m
818                .iter()
819                .filter_map(|(k, v)| Some((LanguageTag::parse(k).ok()?, v.as_object()?.clone())))
820                .collect(),
821            _ => BTreeMap::new(),
822        };
823    let available: Vec<&LanguageTag> = localizations.keys().chain(locale.as_ref()).collect();
824    let chosen = lookup(ranges, available.iter().copied())
825        .or(locale.as_ref())
826        .cloned();
827    let patch = chosen.as_ref().and_then(|t| localizations.remove(t));
828    (chosen, patch)
829}
830
831/// The value that the `/get` view under `ranges` ([`localized_view`])
832/// gives `property` of the serialized object `obj`, for sorting and
833/// filtering a `/query` with `language` (draft-atwood-jmap-updates-00
834/// §4.2.2). `None` when the property is absent; `Some(&Value::Null)` when
835/// the chosen language has no value for it.
836///
837/// ```rust
838/// use jmap_types::i18n::{LanguageRange, localized_value};
839/// use serde_json::json;
840///
841/// let obj = json!({"name": "Inbox", "locale": "en",
842///                  "localizations": {"de": {"name": "Posteingang"}}});
843/// let de: Vec<LanguageRange> = vec!["de-AT".parse().unwrap()];
844/// assert_eq!(localized_value(obj.as_object().unwrap(), "name", &de), Some(json!("Posteingang")));
845/// ```
846pub fn localized_value(
847    obj: &Map<String, Value>,
848    property: &str,
849    ranges: &[LanguageRange],
850) -> Option<Value> {
851    match choose(obj, ranges).1.and_then(|mut p| p.remove(property)) {
852        Some(v) => Some(v),
853        None => obj.get(property).cloned(),
854    }
855}
856
857/// Turn the serialized object `obj` into its view in one language
858/// (draft-atwood-jmap-updates-00 §4.2.1).
859///
860/// The tag is chosen by [`lookup`] over the keys of `localizations` and
861/// the object's `locale`, falling back to `locale` (which may be
862/// `null`). When the chosen tag is a key of `localizations`, its
863/// PatchObject is applied to the properties in `properties`; a `null`
864/// value there sets the property to `null`. `locale` is set to the
865/// chosen tag, and `localizations` to `null`, since the view holds one
866/// language only (decision 30).
867///
868/// Call it before filtering the object to the requested `properties`.
869/// Stored values that do not parse (a malformed `locale` or key) are
870/// treated as absent.
871///
872/// ```rust
873/// use jmap_types::i18n::{LanguageRange, LocalizableProperty, localized_view};
874/// use serde_json::json;
875///
876/// const PROPS: &[LocalizableProperty] = &[LocalizableProperty::new("name", false)];
877/// let mut obj = json!({
878///     "name": "Team contacts", "locale": "en",
879///     "localizations": {"fr": {"name": "Contacts du groupe"}, "de": {"name": "Team-Kontakte"}},
880/// });
881/// let ranges: Vec<LanguageRange> = ["fr-CH", "de"].iter().map(|r| r.parse().unwrap()).collect();
882/// localized_view(obj.as_object_mut().unwrap(), PROPS, &ranges);
883/// assert_eq!(obj, json!({"name": "Contacts du groupe", "locale": "fr", "localizations": null}));
884/// ```
885pub fn localized_view(
886    obj: &mut Map<String, Value>,
887    properties: &[LocalizableProperty],
888    ranges: &[LanguageRange],
889) {
890    let (chosen, patch) = choose(obj, ranges);
891    if let Some(patch) = patch {
892        for p in properties {
893            if let Some(v) = patch.get(p.name) {
894                obj.insert(p.name.to_owned(), v.clone());
895            }
896        }
897    }
898    obj.insert(
899        "locale".to_owned(),
900        chosen.map_or(Value::Null, |t| Value::String(t.0)),
901    );
902    obj.insert("localizations".to_owned(), Value::Null);
903}
904
905#[cfg(test)]
906mod tests {
907    use super::*;
908    use serde_json::json;
909
910    fn tag(s: &str) -> LanguageTag {
911        LanguageTag::parse(s).unwrap()
912    }
913
914    /// RFC 9110 §12.5.4 and §12.4.2: quality ordering, `q=0` excluded,
915    /// malformed qvalues and ranges dropped.
916    #[test]
917    fn accept_language_quality_order() {
918        let tags = |v: &str| -> Vec<String> {
919            accept_language_ranges(v)
920                .iter()
921                .map(|r| r.as_str().to_owned())
922                .collect()
923        };
924        assert_eq!(tags("da, en-gb;q=0.8, en;q=0.7"), ["da", "en-GB", "en"]);
925        assert_eq!(tags("en;q=0.5, de"), ["de", "en"]);
926        assert_eq!(tags("de;q=0, en"), ["en"]);
927        assert_eq!(tags("en;q=1.5, de;q=0.1234, fr;q=0.123"), ["fr"]);
928        assert_eq!(tags("a b, ;q=1, de;Q=0.5, en;q=0.6"), ["en", "de"]);
929        assert!(tags("").is_empty());
930    }
931
932    #[test]
933    fn canonical_case_follows_rfc5646_2_1_1() {
934        // The examples of RFC 5646 §2.1.1.
935        assert_eq!(tag("mn-cyrl-mn").as_str(), "mn-Cyrl-MN");
936        assert_eq!(tag("MN-cYRL-mn").as_str(), "mn-Cyrl-MN");
937        assert_eq!(tag("en-ca-x-ca").as_str(), "en-CA-x-ca");
938        assert_eq!(tag("SGN-BE-FR").as_str(), "sgn-BE-FR");
939        assert_eq!(tag("az-latn-x-latn").as_str(), "az-Latn-x-latn");
940        assert_eq!(tag("I-KLINGON").as_str(), "i-klingon");
941    }
942
943    #[test]
944    fn case_variants_are_equal() {
945        assert_eq!(tag("EN-us"), tag("en-US"));
946    }
947
948    #[test]
949    fn range_rejects_digit_primary_and_accepts_wildcard() {
950        assert_eq!(
951            LanguageRange::parse("1de"),
952            Err(LanguageTagError::IllFormed)
953        );
954        assert!(LanguageRange::parse("*").unwrap().is_wildcard());
955        assert_eq!(
956            LanguageRange::parse("de--ch"),
957            Err(LanguageTagError::EmptySubtag)
958        );
959    }
960
961    #[test]
962    fn localizations_rejects_case_duplicate_keys_on_deserialize() {
963        let r: Result<Localizations, _> = serde_json::from_value(json!({"de-CH": {}, "de-ch": {}}));
964        assert!(r.is_err());
965    }
966
967    #[test]
968    fn touched_reads_each_path_form() {
969        let p: PatchObject = serde_json::from_value(json!({
970            "localizations/FR": {"name": "x"},
971            "localizations/de/description": null,
972            "name": "y",
973        }))
974        .unwrap();
975        let Touched::Some(t) = touched(&p) else {
976            panic!("whole-map set reported for per-language paths");
977        };
978        assert_eq!(t.get(&tag("fr")), Some(&None));
979        assert_eq!(
980            t.get(&tag("de")),
981            Some(&Some(vec!["description".to_owned()]))
982        );
983    }
984}