Skip to main content

trackparse/
options.rs

1//! R12 options: the typed public options and the resolved form the pipeline reads.
2//!
3//! Two doors lead to the resolved form: the typed structs below, and loose JSON (`wire`), which
4//! is resolved with exactly the fallbacks of the JS reference (a bad value means the default,
5//! R0.8).
6
7use crate::json::Json;
8use crate::types::{string_enum, JunkKind, Mode, VersionType};
9
10string_enum! {
11    /// The mode to parse in (R2). `Auto` picks clean, youtube or filename from the string
12    /// itself, never tracklist.
13    ///
14    /// ```
15    /// use trackparse::{parse_with, Mode, ModeOption, ParseOptions};
16    ///
17    /// let input = "Noisia - Stigma (Official Video)";
18    /// assert_eq!(parse_with(input, &ParseOptions::new()).mode, Mode::Youtube);
19    /// let clean = ParseOptions::new().mode(ModeOption::Clean);
20    /// assert_eq!(parse_with(input, &clean).mode, Mode::Clean);
21    /// assert_eq!(ModeOption::default(), ModeOption::Auto);
22    /// ```
23    #[non_exhaustive]
24    ModeOption {
25        Auto => "auto", Clean => "clean", Youtube => "youtube", Filename => "filename",
26        Tracklist => "tracklist",
27    }
28}
29
30string_enum! {
31    /// When the word `and` splits a credit list (R7.3). `&` and the other joiners always split.
32    ///
33    /// ```
34    /// use trackparse::{parse_artists_with, ParseOptions, SplitAnd};
35    ///
36    /// let count = |split_and| {
37    ///     let options = ParseOptions::new().split_and(split_and);
38    ///     parse_artists_with("Above and Beyond", &options).len()
39    /// };
40    /// assert_eq!(count(SplitAnd::Auto), 1);
41    /// assert_eq!(count(SplitAnd::Always), 2);
42    /// assert_eq!(count(SplitAnd::Never), 1);
43    /// ```
44    #[non_exhaustive]
45    SplitAnd { Auto => "auto", Always => "always", Never => "never" }
46}
47
48string_enum! {
49    /// Where [`format_track_with`](crate::format_track_with) writes featured artists (R11.2).
50    ///
51    /// ```
52    /// use trackparse::{format_track_with, parse, FeatPlacement, FormatOptions};
53    ///
54    /// let track = parse("Sub Focus - Out the Blue ft. Alice Gold");
55    /// let with = |feat| format_track_with(&track, &FormatOptions::new().feat(feat));
56    /// assert_eq!(with(FeatPlacement::Source), "Sub Focus - Out the Blue (ft. Alice Gold)");
57    /// assert_eq!(with(FeatPlacement::Artist), "Sub Focus ft. Alice Gold - Out the Blue");
58    /// assert_eq!(with(FeatPlacement::Title), "Sub Focus - Out the Blue (ft. Alice Gold)");
59    /// assert_eq!(with(FeatPlacement::Omit), "Sub Focus - Out the Blue");
60    /// ```
61    #[non_exhaustive]
62    FeatPlacement { Source => "source", Artist => "artist", Title => "title", Omit => "omit" }
63}
64
65string_enum! {
66    /// Joiners as written, or mapped to their canonical form (R11.5).
67    ///
68    /// ```
69    /// use trackparse::{format_track_with, parse, FormatOptions, JoinerStyle};
70    ///
71    /// let track = parse("Noisia & The Upbeats ft Tasha Baxter - Dead Limit");
72/// assert_eq!(format_track_with(&track, &FormatOptions::new()), track.input);
73    /// let options = FormatOptions::new().joiners(JoinerStyle::Canonical);
74    /// assert_eq!(
75    ///     format_track_with(&track, &options),
76    ///     "Noisia & The Upbeats feat. Tasha Baxter - Dead Limit"
77    /// );
78    /// ```
79    #[non_exhaustive]
80    JoinerStyle { Original => "original", Canonical => "canonical" }
81}
82
83string_enum! {
84    /// Whether [`format_track_with`](crate::format_track_with) writes the versions (R11.3).
85    ///
86    /// ```
87    /// use trackparse::{format_track_with, parse, FormatOptions, VersionsOption};
88    ///
89    /// let track = parse("Fox Stevenson - Bruises (Magnetude Remix)");
90    /// let options = FormatOptions::new().versions(VersionsOption::None);
91    /// assert_eq!(format_track_with(&track, &options), "Fox Stevenson - Bruises");
92    /// ```
93    #[non_exhaustive]
94    VersionsOption { All => "all", None => "none" }
95}
96
97#[allow(clippy::derivable_impls)] // the enum comes from a macro
98impl Default for ModeOption {
99    fn default() -> Self {
100        ModeOption::Auto
101    }
102}
103
104#[allow(clippy::derivable_impls)] // the enum comes from a macro
105impl Default for SplitAnd {
106    fn default() -> Self {
107        SplitAnd::Auto
108    }
109}
110
111#[allow(clippy::derivable_impls)] // the enum comes from a macro
112impl Default for FeatPlacement {
113    fn default() -> Self {
114        FeatPlacement::Source
115    }
116}
117
118#[allow(clippy::derivable_impls)] // the enum comes from a macro
119impl Default for JoinerStyle {
120    fn default() -> Self {
121        JoinerStyle::Original
122    }
123}
124
125#[allow(clippy::derivable_impls)] // the enum comes from a macro
126impl Default for VersionsOption {
127    fn default() -> Self {
128        VersionsOption::All
129    }
130}
131
132/// Extra vocabulary, added to the built-in word lists (R12). Keys are matched with ASCII
133/// lowercasing.
134///
135/// ```
136/// use trackparse::{parse_with, JunkKind, KeywordOptions, ParseOptions, VersionType};
137///
138/// let keywords = KeywordOptions::new()
139///     .version_head("rerub", VersionType::Remix)
140///     .junk("out now", JunkKind::Promo);
141/// let options = ParseOptions::new().keywords(keywords);
142/// let track = parse_with("Noisia - Stigma (Phace Rerub) [Out Now]", &options);
143/// assert_eq!(track.versions[0].version_type, VersionType::Remix);
144/// assert_eq!(track.versions[0].artists[0].name, "Phace");
145/// assert_eq!(track.junk[0].kind, JunkKind::Promo);
146/// ```
147#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
148#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
149#[cfg_attr(feature = "serde", serde(default, rename_all = "camelCase"))]
150#[non_exhaustive]
151pub struct KeywordOptions {
152    /// Extra version heads: word and the version type it means. A JSON object (`versionHeads`).
153    #[cfg_attr(feature = "serde", serde(with = "crate::serde_support::pairs"))]
154    pub version_heads: Vec<(String, VersionType)>,
155    /// Extra descriptor words (`Extended`, `Deluxe`).
156    pub descriptors: Vec<String>,
157    /// Extra genre names.
158    pub genres: Vec<String>,
159    /// Extra junk phrases: phrase and its kind. A JSON object.
160    #[cfg_attr(feature = "serde", serde(with = "crate::serde_support::pairs"))]
161    pub junk: Vec<(String, JunkKind)>,
162    /// Extra markers that introduce featured artists (`featMarkers` in JSON).
163    pub feat_markers: Vec<String>,
164}
165
166impl KeywordOptions {
167    /// No extra words.
168    pub fn new() -> Self {
169        Self::default()
170    }
171
172    /// Add a version head (`"rerub"` means [`VersionType::Remix`]).
173    pub fn version_head(mut self, key: impl Into<String>, version_type: VersionType) -> Self {
174        self.version_heads.push((key.into(), version_type));
175        self
176    }
177
178    /// Add a descriptor word.
179    pub fn descriptor(mut self, word: impl Into<String>) -> Self {
180        self.descriptors.push(word.into());
181        self
182    }
183
184    /// Add a genre name.
185    pub fn genre(mut self, word: impl Into<String>) -> Self {
186        self.genres.push(word.into());
187        self
188    }
189
190    /// Add a junk phrase (`"free download"` is [`JunkKind::Promo`]).
191    pub fn junk(mut self, phrase: impl Into<String>, kind: JunkKind) -> Self {
192        self.junk.push((phrase.into(), kind));
193        self
194    }
195
196    /// Add a marker that introduces featured artists.
197    pub fn feat_marker(mut self, marker: impl Into<String>) -> Self {
198        self.feat_markers.push(marker.into());
199        self
200    }
201}
202
203/// Options of [`parse_with`](crate::parse_with), [`parse_artists_with`](crate::parse_artists_with)
204/// and [`Parser`](crate::Parser) (R12). The default is what [`parse`](crate::parse) uses.
205///
206/// Build one with the chained setters, or set the public fields on a default value.
207///
208/// ```
209/// use trackparse::{parse_with, ModeOption, ParseOptions, SplitAnd};
210///
211/// let options = ParseOptions::new()
212///     .mode(ModeOption::Youtube)
213///     .uploader("Noisia")
214///     .known_artists(["Chase & Status"])
215///     .split_and(SplitAnd::Never);
216/// let track = parse_with("Stigma (Official Video)", &options);
217/// assert_eq!(track.artists[0].name, "Noisia");
218/// assert_eq!(track.title, "Stigma");
219///
220/// let mut same = ParseOptions::default();
221/// same.mode = ModeOption::Youtube;
222/// same.uploader = Some("Noisia".into());
223/// same.known_artists = vec!["Chase & Status".into()];
224/// same.split_and = SplitAnd::Never;
225/// assert_eq!(same, options);
226/// ```
227#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
228#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
229#[cfg_attr(feature = "serde", serde(default, rename_all = "camelCase"))]
230#[non_exhaustive]
231pub struct ParseOptions {
232    /// The mode; default [`ModeOption::Auto`].
233    pub mode: ModeOption,
234    /// youtube mode: the channel name, used as the artist when the title has no separator
235    /// (R6.8).
236    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
237    pub uploader: Option<String>,
238    /// Names that must never be split (R7.3a): `Chase & Status`, `Above & Beyond`.
239    pub known_artists: Vec<String>,
240    /// When `and` splits a credit list; default [`SplitAnd::Auto`].
241    pub split_and: SplitAnd,
242    /// Extra vocabulary.
243    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
244    pub keywords: Option<KeywordOptions>,
245}
246
247impl ParseOptions {
248    /// The default options.
249    pub fn new() -> Self {
250        Self::default()
251    }
252
253    /// Set the mode.
254    pub fn mode(mut self, mode: ModeOption) -> Self {
255        self.mode = mode;
256        self
257    }
258
259    /// Set the uploader (the channel name, for youtube mode).
260    pub fn uploader(mut self, uploader: impl Into<String>) -> Self {
261        self.uploader = Some(uploader.into());
262        self
263    }
264
265    /// Set the names that must never be split.
266    pub fn known_artists<I, S>(mut self, names: I) -> Self
267    where
268        I: IntoIterator<Item = S>,
269        S: Into<String>,
270    {
271        self.known_artists = names.into_iter().map(Into::into).collect();
272        self
273    }
274
275    /// Set when `and` splits a credit list.
276    pub fn split_and(mut self, split_and: SplitAnd) -> Self {
277        self.split_and = split_and;
278        self
279    }
280
281    /// Set the extra vocabulary.
282    pub fn keywords(mut self, keywords: KeywordOptions) -> Self {
283        self.keywords = Some(keywords);
284        self
285    }
286}
287
288/// Options of [`format_track_with`](crate::format_track_with) (R11).
289///
290/// ```
291/// use trackparse::{format_track_with, parse, FeatPlacement, FormatOptions};
292///
293/// let track = parse("03. Sub Focus - Out the Blue ft. Alice Gold (Wilkinson Remix)");
294/// let options = FormatOptions::new()
295///     .feat(FeatPlacement::Artist)
296///     .feat_marker("feat.")
297///     .position(true);
298/// assert_eq!(
299///     format_track_with(&track, &options),
300///     "03. Sub Focus feat. Alice Gold - Out the Blue (Wilkinson Remix)"
301/// );
302/// ```
303#[derive(Debug, Clone, PartialEq, Eq, Hash)]
304#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
305#[cfg_attr(feature = "serde", serde(default, rename_all = "camelCase"))]
306#[non_exhaustive]
307pub struct FormatOptions {
308    /// Where featured artists go; default [`FeatPlacement::Source`] (where they were found).
309    pub feat: FeatPlacement,
310    /// Marker written in front of featured lists instead of the one in the input.
311    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
312    pub feat_marker: Option<String>,
313    /// Joiners as written or canonical; default [`JoinerStyle::Original`].
314    pub joiners: JoinerStyle,
315    /// Write the versions or not; default [`VersionsOption::All`].
316    pub versions: VersionsOption,
317    /// Write `prod.` credits; default `true`.
318    pub producers: bool,
319    /// Write the position in front; default `false`.
320    pub position: bool,
321    /// Write `" • " + label` after the title part (R11.3); default `true`.
322    pub label: bool,
323}
324
325impl Default for FormatOptions {
326    fn default() -> Self {
327        FormatOptions {
328            feat: FeatPlacement::Source,
329            feat_marker: None,
330            joiners: JoinerStyle::Original,
331            versions: VersionsOption::All,
332            producers: true,
333            position: false,
334            label: true,
335        }
336    }
337}
338
339impl FormatOptions {
340    /// The default options.
341    pub fn new() -> Self {
342        Self::default()
343    }
344
345    /// Set where featured artists go.
346    pub fn feat(mut self, feat: FeatPlacement) -> Self {
347        self.feat = feat;
348        self
349    }
350
351    /// Set the marker written in front of featured lists.
352    pub fn feat_marker(mut self, marker: impl Into<String>) -> Self {
353        self.feat_marker = Some(marker.into());
354        self
355    }
356
357    /// Set the joiner style.
358    pub fn joiners(mut self, joiners: JoinerStyle) -> Self {
359        self.joiners = joiners;
360        self
361    }
362
363    /// Set whether versions are written.
364    pub fn versions(mut self, versions: VersionsOption) -> Self {
365        self.versions = versions;
366        self
367    }
368
369    /// Set whether `prod.` credits are written.
370    pub fn producers(mut self, producers: bool) -> Self {
371        self.producers = producers;
372        self
373    }
374
375    /// Set whether the position is written in front.
376    pub fn position(mut self, position: bool) -> Self {
377        self.position = position;
378        self
379    }
380
381    /// Set whether the label (R8.7) is written after a spaced bullet.
382    pub fn label(mut self, label: bool) -> Self {
383        self.label = label;
384        self
385    }
386}
387
388// ---------------------------------------------------------------------------
389// Resolved forms
390
391/// `options.mode` as the pipeline sees it. `Other` is any value that is neither missing nor one
392/// of the five names: JS then skips the R2.1 youtube detection but still detects filenames.
393#[derive(Debug, Clone, Copy, PartialEq, Eq)]
394pub(crate) enum Requested {
395    Auto,
396    Mode(Mode),
397    Other,
398}
399
400/// `options.splitAnd`: anything but `auto` / `never` (or missing) behaves as `always` in JS.
401#[derive(Debug, Clone, Copy, PartialEq, Eq)]
402pub(crate) enum SplitAndMode {
403    Auto,
404    Always,
405    Never,
406}
407
408/// `options.keywords` with the maps in JS `Object.entries` order. Types and kinds stay strings:
409/// JS passes any string value through to the output.
410#[derive(Debug, Clone, Default, PartialEq, Eq)]
411pub(crate) struct Keywords {
412    pub version_heads: Vec<(String, String)>,
413    pub descriptors: Vec<String>,
414    pub genres: Vec<String>,
415    pub junk: Vec<(String, String)>,
416    pub feat_markers: Vec<String>,
417}
418
419#[derive(Debug, Clone, PartialEq, Eq)]
420pub(crate) struct Resolved {
421    pub mode: Requested,
422    pub uploader: Option<String>,
423    pub known_artists: Vec<String>,
424    pub split_and: SplitAndMode,
425    /// `None`: the default tables.
426    pub keywords: Option<Keywords>,
427}
428
429impl Default for Resolved {
430    fn default() -> Self {
431        Resolved {
432            mode: Requested::Auto,
433            uploader: None,
434            known_artists: Vec::new(),
435            split_and: SplitAndMode::Auto,
436            keywords: None,
437        }
438    }
439}
440
441/// A canonical array index (`"0"`, `"17"`; not `"01"`): JS lists such keys first, ascending.
442fn array_index(key: &str) -> Option<u64> {
443    if key.is_empty() || key.len() > 10 || !key.bytes().all(|b| b.is_ascii_digit()) {
444        return None;
445    }
446    if key.len() > 1 && key.starts_with('0') {
447        return None;
448    }
449    key.parse::<u64>().ok().filter(|n| *n <= 0xffff_fffe)
450}
451
452/// `Object.entries` order of an object built from `pairs`: a repeated key keeps its first place
453/// and takes the last value; integer-like keys come first in ascending order, then the others in
454/// insertion order.
455pub(crate) fn js_entries<V: Clone>(pairs: &[(String, V)]) -> Vec<(String, V)> {
456    let mut unique: Vec<(String, V)> = Vec::with_capacity(pairs.len());
457    let mut index: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
458    for (k, v) in pairs {
459        match index.get(k.as_str()).and_then(|&i| unique.get_mut(i)) {
460            Some(slot) => slot.1 = v.clone(),
461            None => {
462                index.insert(k.as_str(), unique.len());
463                unique.push((k.clone(), v.clone()));
464            }
465        }
466    }
467    let mut ints: Vec<(u64, (String, V))> = Vec::new();
468    let mut rest: Vec<(String, V)> = Vec::new();
469    for pair in unique {
470        match array_index(&pair.0) {
471            Some(n) => ints.push((n, pair)),
472            None => rest.push(pair),
473        }
474    }
475    ints.sort_by_key(|(n, _)| *n);
476    ints.into_iter().map(|(_, p)| p).chain(rest).collect()
477}
478
479/// R0.8: option lists may be anything at runtime; only arrays of strings count.
480pub(crate) fn string_list(value: Option<&Json>) -> Vec<String> {
481    match value {
482        Some(Json::Arr(items)) => {
483            items.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()
484        }
485        _ => Vec::new(),
486    }
487}
488
489/// R0.8: option maps may be anything at runtime; only plain objects' string values count.
490pub(crate) fn string_entries(value: Option<&Json>) -> Vec<(String, String)> {
491    match value {
492        Some(Json::Obj(entries)) => js_entries(entries)
493            .into_iter()
494            .filter_map(|(k, v)| v.as_str().map(|s| (k, s.to_string())))
495            .collect(),
496        _ => Vec::new(),
497    }
498}
499
500impl Keywords {
501    fn from_json(value: &Json) -> Keywords {
502        Keywords {
503            version_heads: string_entries(value.get("versionHeads")),
504            descriptors: string_list(value.get("descriptors")),
505            genres: string_list(value.get("genres")),
506            junk: string_entries(value.get("junk")),
507            feat_markers: string_list(value.get("featMarkers")),
508        }
509    }
510
511    fn from_typed(k: &KeywordOptions) -> Keywords {
512        let heads: Vec<(String, String)> =
513            k.version_heads.iter().map(|(key, t)| (key.clone(), t.as_str().to_string())).collect();
514        let junk: Vec<(String, String)> =
515            k.junk.iter().map(|(key, kind)| (key.clone(), kind.as_str().to_string())).collect();
516        Keywords {
517            version_heads: js_entries(&heads),
518            descriptors: k.descriptors.clone(),
519            genres: k.genres.clone(),
520            junk: js_entries(&junk),
521            feat_markers: k.feat_markers.clone(),
522        }
523    }
524}
525
526impl Resolved {
527    /// Loose JSON options, with the JS fallbacks.
528    pub(crate) fn from_json(options: &Json) -> Resolved {
529        if options.as_object().is_none() {
530            return Resolved::default(); // safeOptions: not an object
531        }
532        let mode = match options.get("mode") {
533            None | Some(Json::Null) => Requested::Auto, // `options.mode ?? "auto"`
534            Some(Json::Str(s)) if s == "auto" => Requested::Auto,
535            Some(Json::Str(s)) => Mode::from_name(s).map_or(Requested::Other, Requested::Mode),
536            Some(_) => Requested::Other,
537        };
538        let split_and = match options.get("splitAnd") {
539            None | Some(Json::Null) => SplitAndMode::Auto, // `options?.splitAnd ?? "auto"`
540            Some(Json::Str(s)) if s == "auto" => SplitAndMode::Auto,
541            Some(Json::Str(s)) if s == "never" => SplitAndMode::Never,
542            Some(_) => SplitAndMode::Always,
543        };
544        // `options?.keywords ? … : baseTables`, then `isRecord`: only a plain object adds words.
545        let keywords = match options.get("keywords") {
546            Some(k @ Json::Obj(_)) => Some(Keywords::from_json(k)),
547            _ => None,
548        };
549        Resolved {
550            mode,
551            uploader: options.get("uploader").and_then(Json::as_str).map(str::to_string),
552            known_artists: string_list(options.get("knownArtists")),
553            split_and,
554            keywords,
555        }
556    }
557
558    pub(crate) fn from_typed(options: &ParseOptions) -> Resolved {
559        Resolved {
560            mode: match options.mode {
561                ModeOption::Auto => Requested::Auto,
562                ModeOption::Clean => Requested::Mode(Mode::Clean),
563                ModeOption::Youtube => Requested::Mode(Mode::Youtube),
564                ModeOption::Filename => Requested::Mode(Mode::Filename),
565                ModeOption::Tracklist => Requested::Mode(Mode::Tracklist),
566            },
567            uploader: options.uploader.clone(),
568            known_artists: options.known_artists.clone(),
569            split_and: match options.split_and {
570                SplitAnd::Auto => SplitAndMode::Auto,
571                SplitAnd::Always => SplitAndMode::Always,
572                SplitAnd::Never => SplitAndMode::Never,
573            },
574            keywords: options.keywords.as_ref().map(Keywords::from_typed),
575        }
576    }
577}
578
579/// `options.feat` as R11 reads it: an unknown value places featured artists nowhere.
580#[derive(Debug, Clone, Copy, PartialEq, Eq)]
581pub(crate) enum FeatMode {
582    Source,
583    Artist,
584    Title,
585    Omit,
586}
587
588#[derive(Debug, Clone, PartialEq, Eq)]
589pub(crate) struct ResolvedFormat {
590    pub feat: FeatMode,
591    pub feat_marker: Option<String>,
592    pub canonical: bool,
593    pub versions: bool,
594    pub producers: bool,
595    pub position: bool,
596    pub label: bool,
597}
598
599/// JS truthiness of a JSON value.
600fn truthy(v: &Json) -> bool {
601    match v {
602        Json::Null => false,
603        Json::Bool(b) => *b,
604        Json::Num(n) => *n != 0.0 && !n.is_nan(),
605        Json::Str(s) => !s.is_empty(),
606        Json::Arr(_) | Json::Obj(_) => true,
607    }
608}
609
610/// JS `String(value)` (what a template literal does with a non-string `featMarker`).
611fn js_string(v: &Json) -> String {
612    match v {
613        Json::Null => "null".to_string(),
614        Json::Bool(b) => b.to_string(),
615        Json::Num(n) if n.is_nan() => "NaN".to_string(),
616        Json::Num(n) if n.is_infinite() => {
617            (if *n > 0.0 { "Infinity" } else { "-Infinity" }).to_string()
618        }
619        Json::Num(_) => v.write(),
620        Json::Str(s) => s.clone(),
621        // Array.prototype.join: null elements are empty.
622        Json::Arr(items) => items
623            .iter()
624            .map(|i| if matches!(i, Json::Null) { String::new() } else { js_string(i) })
625            .collect::<Vec<_>>()
626            .join(","),
627        Json::Obj(_) => "[object Object]".to_string(),
628    }
629}
630
631impl ResolvedFormat {
632    /// Loose JSON format options, with the JS fallbacks (`??` for missing and `null`).
633    pub(crate) fn from_json(o: &Json) -> ResolvedFormat {
634        let get = |key: &str| match o.get(key) {
635            Some(Json::Null) | None => None,
636            Some(v) => Some(v),
637        };
638        ResolvedFormat {
639            feat: match get("feat") {
640                None => FeatMode::Source,
641                Some(Json::Str(s)) if s == "source" => FeatMode::Source,
642                Some(Json::Str(s)) if s == "artist" => FeatMode::Artist,
643                Some(Json::Str(s)) if s == "title" => FeatMode::Title,
644                Some(_) => FeatMode::Omit,
645            },
646            // `o.featMarker !== undefined`: an explicit null is rendered as "null".
647            feat_marker: o.get("featMarker").map(js_string),
648            canonical: get("joiners").and_then(Json::as_str) == Some("canonical"),
649            versions: get("versions").map_or(true, |v| v.as_str() == Some("all")),
650            producers: get("producers").map_or(true, truthy),
651            position: get("position").is_some_and(truthy),
652            label: get("label").map_or(true, truthy),
653        }
654    }
655
656    pub(crate) fn from_typed(o: &FormatOptions) -> ResolvedFormat {
657        ResolvedFormat {
658            feat: match o.feat {
659                FeatPlacement::Source => FeatMode::Source,
660                FeatPlacement::Artist => FeatMode::Artist,
661                FeatPlacement::Title => FeatMode::Title,
662                FeatPlacement::Omit => FeatMode::Omit,
663            },
664            feat_marker: o.feat_marker.clone(),
665            canonical: o.joiners == JoinerStyle::Canonical,
666            versions: o.versions == VersionsOption::All,
667            producers: o.producers,
668            position: o.position,
669            label: o.label,
670        }
671    }
672}