indieweb 0.10.0

A collection of utilities for working with the IndieWeb.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
use crate::{
    algorithms::ptd::Type,
    http::{Client, CONTENT_TYPE_JSON},
    standards::{indieauth::AccessToken, micropub::convert_error},
    traits::as_string_or_list,
};
use serde::{Deserialize, Serialize};

use super::{
    extension::{self, PostStatus, Visibility},
    paging,
};
use microformats::types::Item;
use secrecy::ExposeSecret;
use std::collections::HashMap;

#[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(rename_all = "kebab-case")]
pub struct Query {
    /// Pagination options to modify where in the list to look
    #[serde(flatten)]
    pub pagination: paging::Query,

    /// A representation of the base querying components.
    #[serde(flatten)]
    pub kind: QueryKind,
}

#[derive(Debug, Clone, Default, Eq)]
pub struct MatchingPropertyValuesMap(HashMap<String, Vec<serde_json::Value>>);

impl std::ops::Deref for MatchingPropertyValuesMap {
    type Target = HashMap<String, Vec<serde_json::Value>>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl std::hash::Hash for MatchingPropertyValuesMap {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        serde_json::to_string(&self.0)
            .unwrap_or_default()
            .hash(state);
    }
}

impl PartialEq for MatchingPropertyValuesMap {
    fn eq(&self, other: &Self) -> bool {
        self.0.eq(&other.0)
    }
}

const KNOWN_SOURCE_QUERY_PARAMS: &[&str] = &[
    "url",
    "destination",
    "post_type",
    "post-status",
    "post_status",
    "visibility",
    "audience",
    "syndicate_to",
    "syndicate-to",
    "category",
    "exists",
    "not_exists",
    "not-exists",
    "filter",
    "limit",
    "offset",
    "before",
    "after",
    "order",
    "q",
    "h",
    "type",
    "channel",
    "mp-channel",
    "mime_type",
    "mime-type",
];

fn is_known_query_param(key: &str) -> bool {
    KNOWN_SOURCE_QUERY_PARAMS
        .iter()
        .any(|&known| key == known || key == known.replace('_', "-"))
}

struct PropertyValueVisitor;

impl<'de> serde::de::Visitor<'de> for PropertyValueVisitor {
    type Value = MatchingPropertyValuesMap;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        formatter.write_str("expecting a map of property filters (with 'property-' prefix or shorthand)")
    }

    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
    where
        A: serde::de::MapAccess<'de>,
    {
        let mut props = HashMap::<String, Vec<serde_json::Value>>::default();
        
        while let Some((key, value)) = map.next_entry::<String, serde_json::Value>()? {
            let (property_name, should_capture) = if key.starts_with("property-") {
                (key.replace("property-", ""), true)
            } else if !is_known_query_param(&key) {
                (key, true)
            } else {
                (key, false)
            };
            
            if !should_capture {
                continue;
            }
            
            let values = value
                .as_array()
                .cloned()
                .unwrap_or_else(|| vec![value.clone()]);
            if let Some(list) = props.get_mut(&property_name) {
                list.extend(values);
            } else {
                props.insert(property_name, values);
            }
        }

        Ok(MatchingPropertyValuesMap(HashMap::from_iter(
            props
                .iter()
                .map(|(name, values)| (name.to_owned(), values.to_vec()))
                .collect::<Vec<_>>()
                .into_iter()
                .rev(),
        )))
    }
}

impl From<HashMap<String, Vec<serde_json::Value>>> for MatchingPropertyValuesMap {
    fn from(v: HashMap<String, Vec<serde_json::Value>>) -> Self {
        Self(v)
    }
}

impl<'de> serde::Deserialize<'de> for MatchingPropertyValuesMap {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::de::Deserializer<'de>,
    {
        deserializer.deserialize_map(PropertyValueVisitor)
    }
}

impl serde::Serialize for MatchingPropertyValuesMap {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut map = serializer.serialize_map(Some(self.0.len()))?;
        for (k, v) in &self.0 {
            serde::ser::SerializeMap::serialize_entry(&mut map, &format!("property-{}", k), &v)?;
        }
        serde::ser::SerializeMap::end(map)
    }
}

impl TryFrom<serde_json::Value> for MatchingPropertyValuesMap {
    type Error = serde_json::Error;

    fn try_from(value: serde_json::Value) -> Result<Self, Self::Error> {
        serde_json::from_value(value)
    }
}

impl FromIterator<(String, Vec<serde_json::Value>)> for MatchingPropertyValuesMap {
    fn from_iter<T: IntoIterator<Item = (String, Vec<serde_json::Value>)>>(iter: T) -> Self {
        Self(HashMap::from_iter(iter))
    }
}

impl IntoIterator for MatchingPropertyValuesMap {
    type Item = (String, Vec<serde_json::Value>);
    type IntoIter = std::collections::hash_map::IntoIter<String, Vec<serde_json::Value>>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

#[test]
fn matching_property_values_map() {
    assert_eq!(
        serde_json::from_str::<MatchingPropertyValuesMap>(
            r#"
    {
        "property-foo": null,
        "property-bar": [3, "jump"]
    }
    "#
        )
        .map_err(|e| e.to_string()),
        Ok(MatchingPropertyValuesMap(HashMap::from_iter([
            ("foo".to_string(), vec![serde_json::Value::Null]),
            (
                "bar".to_string(),
                vec![
                    serde_json::Value::Number(3.into()),
                    serde_json::Value::String("jump".to_string())
                ]
            )
        ])))
        .map_err(|e: serde_json::Error| e.to_string()),
        "deserializing from JSON with property- prefix"
    );

    assert_eq!(
        serde_qs::from_str::<MatchingPropertyValuesMap>(
            "property-foo=kick&property-bar[]=jump&property-bar[]=high"
        )
        .map_err(|e: serde_qs::Error| e.to_string()),
        Ok(MatchingPropertyValuesMap(HashMap::from_iter([
            (
                "foo".to_string(),
                vec![serde_json::Value::String("kick".to_string())]
            ),
            (
                "bar".to_string(),
                vec![
                    serde_json::Value::String("jump".to_string()),
                    serde_json::Value::String("high".to_string()),
                ]
            )
        ]))),
        "deserializing from query string with property- prefix"
    );
}

#[test]
fn matching_property_values_map_shorthand() {
    assert_eq!(
        serde_json::from_str::<MatchingPropertyValuesMap>(
            r#"{ "rsvp": "yes" }"#
        )
        .map_err(|e| e.to_string()),
        Ok(MatchingPropertyValuesMap(HashMap::from_iter([
            ("rsvp".to_string(), vec![serde_json::Value::String("yes".to_string())])
        ]))),
        "deserializing shorthand property from JSON"
    );

    assert_eq!(
        serde_qs::from_str::<MatchingPropertyValuesMap>("rsvp=yes")
            .map_err(|e: serde_qs::Error| e.to_string()),
        Ok(MatchingPropertyValuesMap(HashMap::from_iter([
            ("rsvp".to_string(), vec![serde_json::Value::String("yes".to_string())])
        ]))),
        "deserializing shorthand property from query string"
    );

    assert_eq!(
        serde_json::from_str::<MatchingPropertyValuesMap>(
            r#"{ "property-foo": "bar", "rsvp": "yes" }"#
        )
        .map_err(|e| e.to_string()),
        Ok(MatchingPropertyValuesMap(HashMap::from_iter([
            ("foo".to_string(), vec![serde_json::Value::String("bar".to_string())]),
            ("rsvp".to_string(), vec![serde_json::Value::String("yes".to_string())])
        ]))),
        "deserializing mixed explicit and shorthand properties from JSON"
    );

    assert_eq!(
        serde_json::from_str::<MatchingPropertyValuesMap>(
            r#"{ "url": "https://example.com" }"#
        )
        .map_err(|e| e.to_string()),
        Ok(MatchingPropertyValuesMap(HashMap::new())),
        "known query params should not be captured as property filters"
    );
}

#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, Hash)]
#[serde(rename_all = "kebab-case")]
pub struct SourceQuery {
    /// Properties to match in this query.
    #[serde(flatten)]
    pub matching_properties: MatchingPropertyValuesMap,

    /// The URL of the resource being discovered.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub url: Option<url::Url>,

    /// Represents the destination of this item when filtering this query.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub destination: Option<url::Url>,

    /// Represents one or many post types to ask for when filtering this query.
    #[serde(
        with = "as_string_or_list",
        skip_serializing_if = "Vec::is_empty",
        default
    )]
    pub post_type: Vec<crate::algorithms::ptd::Type>,

    /// Represents the expected post status of the items returned when filtering this query.
    #[serde(
        default,
        skip_serializing_if = "SourceQuery::is_non_serializable_status"
    )]
    pub post_status: Option<PostStatus>,

    /// Provides a list of the associated audiences to look for when filtering this query.
    #[serde(
        with = "as_string_or_list",
        default,
        skip_serializing_if = "Vec::is_empty"
    )]
    pub audience: Vec<String>,

    /// Represents the expected visibilities of the items returned when filtering this query.
    #[serde(
        default,
        skip_serializing_if = "SourceQuery::is_non_serializable_visibility"
    )]
    pub visibility: Option<Visibility>,

    /// Represents one or many channels to ask for when filtering this query.
    #[serde(
        skip_serializing_if = "Vec::is_empty",
        default,
        with = "as_string_or_list"
    )]
    #[cfg(feature = "experimental_channels")]
    pub channel: Vec<extension::channel::Form>,

    /// Represents one or many targets used for syndication when filtering this query.
    #[serde(
        skip_serializing_if = "Vec::is_empty",
        default,
        with = "as_string_or_list"
    )]
    pub syndicate_to: Vec<String>,

    /// Represents one or many categories when filtering this query.
    #[serde(
        skip_serializing_if = "Vec::is_empty",
        default,
        with = "as_string_or_list"
    )]
    pub category: Vec<String>,

    /// Represents one or many properties to check for the presence of.
    #[serde(
        skip_serializing_if = "Vec::is_empty",
        default,
        with = "as_string_or_list"
    )]
    pub exists: Vec<String>,

    /// Represents one or many properties to check for the lack of a presence of.
    #[serde(
        skip_serializing_if = "Vec::is_empty",
        default,
        with = "as_string_or_list"
    )]
    pub not_exists: Vec<String>,

    /// Represents a value to filter against.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub filter: Option<String>,

    /// Filter media by MIME type (e.g., "image", "image/jpeg", "image/*").
    ///
    /// Supports:
    /// - Full MIME type: "image/jpeg"
    /// - Type only: "image" (matches any subtype)
    /// - Wildcard: "image/*" or "*/*"
    ///
    /// See <https://github.com/indieweb/micropub-extensions/issues/45>
    #[cfg(feature = "experimental_media_query")]
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub mime_type: Option<extension::MimeType>,
}

impl SourceQuery {
    pub fn post_status_is_published_by_default() -> PostStatus {
        PostStatus::Published
    }

    pub fn visibility_is_public_by_default() -> Visibility {
        Visibility::Public
    }

    pub fn is_non_serializable_visibility(visibility: &Option<Visibility>) -> bool {
        visibility.is_none() || *visibility != Some(Visibility::Public)
    }

    pub fn is_default_post_type(post_types: &Vec<Type>) -> bool {
        *post_types == vec![Type::default()]
    }

    pub fn is_non_serializable_status(post_status: &Option<PostStatus>) -> bool {
        post_status.is_none() || *post_status != Some(PostStatus::default())
    }
}

#[derive(Serialize, Deserialize, Debug, Eq)]
#[serde(rename_all = "kebab-case", tag = "q", deny_unknown_fields)]
#[non_exhaustive]
pub enum QueryKind {
    /// Pulls the configuration of the Micropub server.
    #[serde(rename = "config")]
    Configuration,

    /// Represents a call to `?q=source` for post information
    Source(Box<SourceQuery>),

    /// Represents a call to `?q=channel` to fetch channels.
    /// To learn about channels, view <https://github.com/indieweb/micropub-extensions/issues/40>
    #[cfg(feature = "experimental_channels")]
    Channel,

    /// Represents a call to `?q=syndicate-to` to fetch syndication targets.
    #[serde(rename_all = "kebab-case")]
    #[cfg(feature = "experimental_syndication")]
    SyndicateTo {
        /// Represents a single or many post types to ask for when filtering this query.
        #[serde(with = "as_string_or_list", skip_serializing_if = "Vec::is_empty")]
        post_type: Vec<Type>,
    },

    /// Represents a call to `?q=rel` to fetch relationship links.
    #[serde(alias = "rel", rename_all = "kebab-case")]
    #[cfg(feature = "experimental_relation")]
    Relation {
        /// The relations to explicitly look for.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        rel: Vec<String>,

        /// The identity to look up relationships for.
        url: url::Url,
    },

    /// Represents a call to `?q=category` to fetch tags.
    Category,
}

impl PartialEq for QueryKind {
    fn eq(&self, other: &Self) -> bool {
        use std::mem::discriminant;
        discriminant(self) == discriminant(other)
    }
}

impl Query {
    /// Sends this request over to the requested Micropub server.
    #[tracing::instrument(skip(client))]
    pub async fn send(
        &self,
        client: &impl Client,
        endpoint: &url::Url,
        access_token: &AccessToken,
    ) -> Result<Response, crate::Error> {
        let mut url = endpoint.clone();
        let self_string = serde_qs::to_string(&self).map_err(crate::Error::Qs)?;

        if url.query().is_none() {
            url.set_query(Some(self_string.as_str()));
        } else {
            url.query_pairs_mut()
                .extend_pairs(url::form_urlencoded::parse(self_string.as_bytes()));
        }

        tracing::trace!(
            endpoint = format!("{endpoint}"),
            query = self_string,
            "Sending request to Micropub server"
        );

        let req = http::Request::get(url.as_str())
            .header(http::header::ACCEPT, CONTENT_TYPE_JSON)
            .header(
                http::header::AUTHORIZATION,
                format!("Bearer {}", access_token.expose_secret()),
            )
            .body(crate::http::Body::Empty)?;

        let resp = client.send_request(req).await?;

        tracing::debug!(?resp, "Received Micropub query response");

        crate::http::from_json_value(resp)
            .and_then(|response: Response| Result::<Response, crate::Error>::from(response))
            .map_err(convert_error)
    }
}

/// A representation of what can be returned from a configuration request.
///
/// View <https://micropub.spec.indieweb.org/#configuration> for more information.
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct ConfigurationResponse {
    /// A list of the supported queries available to the querying client.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub q: Vec<String>,

    /// A list of channels available for use to the querying client.
    #[cfg(feature = "experimental_channels")]
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub channels: Vec<extension::channel::Form>,

    /// The media endpoint suggested for use with this Micropub server.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub media_endpoint: Option<url::Url>,

    /// The supported post types this Micropub server recognizes.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub post_types: Vec<PostTypeInfo>,

    /// The available syndication targets from the remote Micropub server.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[cfg(feature = "experimental_syndication")]
    pub syndicate_to: Vec<extension::syndication::Target>,

    /// The categories available to the querying client.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub category: Vec<String>,

    /// The list of Micropub extensions supported by this server.
    ///
    /// Applications can populate this field using `ExtensionRegistry::new().extensions()`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub extensions: Vec<String>,
}


/// Information about a supported post type.
///
/// Can be either a simple type identifier or an extended object with metadata.
/// This allows backward compatibility with simple type lists while supporting
/// extended metadata when available.
///
/// View <https://micropub.spec.indieweb.org/#supported-vocabulary> for more information.
#[derive(PartialEq, Debug, Clone)]
pub enum PostTypeInfo {
    /// Simple post type identifier (backward compatible)
    Simple(Type),
    /// Extended post type with metadata
    Extended {
        /// The post type
        r#type: Type,
        /// Human-readable name for the post type
        name: String,
        /// Optional list of properties this post type supports
        properties: Option<Vec<String>>,
    },
}

impl Serialize for PostTypeInfo {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            PostTypeInfo::Simple(t) => t.serialize(serializer),
            PostTypeInfo::Extended {
                r#type,
                name,
                properties,
            } => {
                use serde::ser::SerializeMap;
                let mut map =
                    serializer.serialize_map(Some(if properties.is_some() { 3 } else { 2 }))?;
                map.serialize_entry("type", r#type)?;
                map.serialize_entry("name", name)?;
                if let Some(props) = properties {
                    map.serialize_entry("properties", props)?;
                }
                map.end()
            }
        }
    }
}

impl<'de> Deserialize<'de> for PostTypeInfo {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use serde::de::Error;
        let value = serde_json::Value::deserialize(deserializer)?;

        // Try to deserialize as simple Type first (backward compatibility)
        if let Ok(t) = serde_json::from_value::<Type>(value.clone()) {
            return Ok(PostTypeInfo::Simple(t));
        }

        // Otherwise, try as extended object
        if let Some(obj) = value.as_object() {
            let r#type = obj
                .get("type")
                .ok_or_else(|| D::Error::missing_field("type"))
                .and_then(|v| serde_json::from_value(v.clone()).map_err(D::Error::custom))?;
            let name = obj
                .get("name")
                .ok_or_else(|| D::Error::missing_field("name"))
                .and_then(|v| serde_json::from_value(v.clone()).map_err(D::Error::custom))?;
            let properties = obj
                .get("properties")
                .map(|v| serde_json::from_value(v.clone()))
                .transpose()
                .map_err(D::Error::custom)?;

            return Ok(PostTypeInfo::Extended {
                r#type,
                name,
                properties,
            });
        }

        Err(D::Error::custom(
            "expected string or object for PostTypeInfo",
        ))
    }
}

impl From<Type> for PostTypeInfo {
    fn from(t: Type) -> Self {
        PostTypeInfo::Simple(t)
    }
}

#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct SourceResponse {
    /// The hinted post type.
    #[serde(
        default,
        rename = "post-type",
        with = "as_string_or_list",
        skip_serializing_if = "Vec::is_empty"
    )]
    pub post_type: Vec<Type>,

    /// The [Microformats][microformats] item returned in this request.
    #[serde(flatten)]
    pub item: Item,
}


/// Response containing a list of posts from a source query.
///
/// Returned when querying for multiple posts (e.g., `?q=source` without a specific URL).
/// View <https://micropub.spec.indieweb.org/#source-content> for more information.
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct SourceListResponse {
    /// The list of items matching the query
    pub items: Vec<SourceResponse>,

    /// Pagination information for navigating the list
    #[serde(flatten, skip_serializing_if = "paging::Fields::is_empty")]
    pub paging: paging::Fields,
}


#[derive(PartialEq, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct CategoryResponse {
    pub categories: Vec<String>,

    #[serde(flatten, skip_serializing_if = "paging::Fields::is_empty")]
    pagination: paging::Fields,
}

/// Response containing syndication targets from a syndicate-to query.
///
/// View <https://micropub.spec.indieweb.org/#syndication-targets> for more information.
#[derive(PartialEq, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
#[cfg(feature = "experimental_syndication")]
pub struct SyndicationTargetsResponse {
    /// The list of syndication targets available to the querying client.
    pub syndicate_to: Vec<extension::syndication::Target>,
}

/// Represents the response for a query.
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
#[serde(untagged, rename_all = "kebab-case")]
pub enum Response {
    Source(SourceResponse),
    SourceList(SourceListResponse),
    #[cfg(feature = "experimental_channels")]
    Channel(extension::channel::QueryResponse),
    Category(CategoryResponse),
    #[cfg(feature = "experimental_syndication")]
    SyndicateTo(SyndicationTargetsResponse),
    Configuration(ConfigurationResponse),
    Paginated(paging::Response),
    Error(super::Error),
}

impl From<Response> for Result<Response, crate::Error> {
    fn from(value: Response) -> Self {
        if let Response::Error(e) = value {
            Err(crate::Error::Micropub(e))
        } else {
            Ok(value)
        }
    }
}

#[cfg(test)]
mod test;