apollo-errors 0.7.0

Structured error handling with automatic format conversion
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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
//! Content negotiation with Accept header parsing and quality values

use std::cmp::Ordering;
use std::collections::HashMap;

use crate::metadata::{CodeCase, FieldCase, FormatConfig};

/// Supported content types for error rendering
///
/// Internal type used for content negotiation. Users should work with [`Renderer`] instead.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(super) enum ContentType {
    /// application/json
    Json,
    /// text/html
    Html,
    /// application/graphql-response+json or application/json+graphql
    GraphQL,
    /// text/plain
    Text,
    /// application/json-rpc
    JsonRpc,
}

impl ContentType {
    /// Get the MIME type string for this content type
    pub(super) fn mime_type(self) -> &'static str {
        match self {
            ContentType::Json => "application/json",
            ContentType::Html => "text/html",
            ContentType::GraphQL => "application/graphql-response+json",
            ContentType::Text => "text/plain",
            ContentType::JsonRpc => "application/json-rpc",
        }
    }
}

/// Specifies which format to use when rendering error responses.
///
/// Each renderer produces error responses in a specific format with the
/// appropriate `Content-Type` header.
///
/// # Examples
///
/// ```rust
/// use apollo_errors::tower_http::Renderer;
///
/// let renderer = Renderer::Json;
/// assert_eq!(renderer, Renderer::Json);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Renderer {
    /// JSON format (`application/json`)
    ///
    /// Produces responses in JSON format compatible with REST APIs.
    /// Defaults: `snake_case` extension field names and unmodified error codes.
    /// ```json
    /// {
    ///   "errors": [{
    ///     "message": "Error message",
    ///     "extensions": {
    ///       "code": "ERROR_CODE",
    ///       "field": "value"
    ///     }
    ///   }]
    /// }
    /// ```
    Json,

    /// HTML format (`text/html`)
    ///
    /// Produces human-readable HTML error pages suitable for browser display.
    /// Includes the error code, message, and all extension fields formatted
    /// as a definition list.
    /// Defaults: `snake_case` extension field names and unmodified error codes.
    Html,

    /// GraphQL format (`application/graphql-response+json`)
    ///
    /// Produces responses in GraphQL error format.
    /// Defaults: `camelCase` extension field names and `SCREAMING_SNAKE_CASE` error codes.
    ///
    /// ```json
    /// {
    ///   "errors": [{
    ///     "message": "Error message",
    ///     "extensions": {
    ///       "code": "SOME_ERROR_CODE",
    ///       "fieldName": "value"
    ///     }
    ///   }]
    /// }
    /// ```
    GraphQL,

    /// Plain text format (`text/plain`)
    ///
    /// Produces simple plain text error messages.
    /// Defaults: `snake_case` extension field names and unmodified error codes.
    /// ```text
    /// Error: ERROR_CODE
    /// Error message
    ///
    /// Details:
    ///   field: value
    /// ```
    Text,

    /// JSON-RPC 2.0 format (`application/json-rpc`)
    ///
    /// Produces responses in JSON-RPC 2.0 error response format.
    /// Defaults: `snake_case` extension field names and unmodified error codes.
    /// ```json
    /// {
    ///   "jsonrpc": "2.0",
    ///   "error": {
    ///     "code": -32000,
    ///     "message": "Error message",
    ///     "data": {
    ///       "diagnostic_code": "ERROR_CODE",
    ///       "field": "value"
    ///     }
    ///   },
    ///   "id": null
    /// }
    /// ```
    ///
    /// The `id` field is `null` since the request ID is not available at this layer.
    JsonRpc,
}

impl Renderer {
    /// Get the content type for this renderer
    pub(super) fn content_type(&self) -> ContentType {
        match self {
            Renderer::Json => ContentType::Json,
            Renderer::Html => ContentType::Html,
            Renderer::GraphQL => ContentType::GraphQL,
            Renderer::Text => ContentType::Text,
            Renderer::JsonRpc => ContentType::JsonRpc,
        }
    }

    fn default_format_config(self) -> FormatConfig {
        match self {
            Renderer::GraphQL => FormatConfig {
                field_case: FieldCase::CamelCase,
                code_case: CodeCase::ScreamingSnakeCase,
            },
            Renderer::Json | Renderer::Html | Renderer::Text | Renderer::JsonRpc => {
                FormatConfig::default()
            }
        }
    }
}

/// A parsed media type from an Accept header
///
/// Internal type used for parsing Accept headers during content negotiation.
#[derive(Debug, Clone)]
pub(super) struct MediaType {
    /// The type (e.g., "text", "application", "*")
    pub(super) ty: String,
    /// The subtype (e.g., "html", "json", "*")
    pub(super) subtype: String,
    /// Quality value (0.0 to 1.0, default 1.0)
    pub(super) quality: f32,
}

impl MediaType {
    /// Parse a single media type from an Accept header segment
    pub(super) fn parse(s: &str) -> Option<Self> {
        let s = s.trim();
        let (media, params) = s.split_once(';').unwrap_or((s, ""));

        let (type_, subtype) = media.trim().split_once('/')?;

        let mut quality = 1.0;
        for param in params.split(';') {
            let param = param.trim();
            if let Some(q) = param.strip_prefix("q=")
                && let Ok(parsed) = q.parse::<f32>()
            {
                // Reject NaN and infinite values, clamp to valid range [0.0, 1.0]
                if parsed.is_finite() {
                    quality = parsed.clamp(0.0, 1.0);
                }
                // If NaN or infinite, keep default quality of 1.0
            }
        }

        Some(MediaType {
            ty: type_.trim().to_lowercase(),
            subtype: subtype.trim().to_lowercase(),
            quality,
        })
    }

    /// Check if this media type matches a content type
    pub(super) fn matches(&self, content_type: ContentType) -> bool {
        let mime = content_type.mime_type();
        let (ct_type, ct_subtype) = mime.split_once('/').unwrap();

        let type_matches = self.ty == "*" || self.ty == ct_type;
        let subtype_matches = self.subtype == "*" || self.subtype == ct_subtype;

        type_matches && subtype_matches
    }

    /// Calculate specificity for sorting (more specific = higher priority)
    fn specificity(&self) -> u8 {
        match (self.ty.as_str(), self.subtype.as_str()) {
            ("*", "*") => 0,
            (_, "*") | ("*", _) => 1,
            _ => 2,
        }
    }
}

/// Configuration for HTTP content negotiation.
///
/// This struct controls how the middleware selects error renderers based on the
/// `Accept` header in HTTP requests. It maintains a list of media type patterns
/// and their corresponding renderers, plus a fallback renderer for when no
/// pattern matches.
///
/// # Default Behavior
///
/// By default, the following media types are supported:
/// - `application/json` → [`Renderer::Json`]
/// - `text/html` → [`Renderer::Html`]
/// - `application/graphql-response+json` → [`Renderer::GraphQL`]
/// - `application/json+graphql` → [`Renderer::GraphQL`]
/// - `text/plain` → [`Renderer::Text`]
/// - `application/json-rpc` → [`Renderer::JsonRpc`]
/// - No Accept header or no match → [`Renderer::Json`] (fallback)
///
/// # Examples
///
/// ## Basic Usage
///
/// ```rust
/// use apollo_errors::tower_http::NegotiationConfig;
///
/// let config = NegotiationConfig::new();
/// ```
///
/// ## Custom Mappings
///
/// Add support for custom media types:
///
/// ```rust
/// use apollo_errors::tower_http::{NegotiationConfig, Renderer};
///
/// let config = NegotiationConfig::new()
///     .with_mapping("application/vnd.api+json", Renderer::Json)
///     .with_mapping("application/vnd.myapp+json", Renderer::Json);
/// ```
///
/// ## Custom Fallback
///
/// Change the default renderer when no Accept header matches:
///
/// ```rust
/// use apollo_errors::tower_http::{NegotiationConfig, Renderer};
///
/// let config = NegotiationConfig::new()
///     .with_fallback(Renderer::Text);
/// ```
///
/// ## Full Customization
///
/// ```rust
/// use apollo_errors::tower_http::{NegotiationConfig, Renderer};
///
/// let config = NegotiationConfig::new()
///     .with_mapping("application/vnd.api+json", Renderer::Json)
///     .with_mapping("application/problem+json", Renderer::Json)
///     .with_fallback(Renderer::Html);
/// ```
#[derive(Debug, Clone)]
pub struct NegotiationConfig {
    /// Custom mappings from media type patterns to renderers
    mappings: Vec<(String, Renderer)>,
    /// Fallback renderer when no match is found
    fallback: Renderer,
    /// Per-renderer format overrides
    format_overrides: HashMap<Renderer, FormatConfig>,
}

impl Default for NegotiationConfig {
    fn default() -> Self {
        Self {
            mappings: vec![
                ("application/json".to_string(), Renderer::Json),
                ("text/html".to_string(), Renderer::Html),
                (
                    "application/graphql-response+json".to_string(),
                    Renderer::GraphQL,
                ),
                ("application/json+graphql".to_string(), Renderer::GraphQL),
                ("text/plain".to_string(), Renderer::Text),
                ("application/json-rpc".to_string(), Renderer::JsonRpc),
            ],
            fallback: Renderer::Json,
            format_overrides: HashMap::new(),
        }
    }
}

impl NegotiationConfig {
    /// Create a new configuration with default mappings.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use apollo_errors::tower_http::NegotiationConfig;
    ///
    /// let config = NegotiationConfig::new();
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a custom mapping from a media type pattern to a renderer.
    ///
    /// Custom mappings take precedence over default mappings. If you add multiple
    /// mappings for the same media type, the most recently added one takes precedence.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use apollo_errors::tower_http::{NegotiationConfig, Renderer};
    ///
    /// let config = NegotiationConfig::new()
    ///     .with_mapping("application/vnd.api+json", Renderer::Json)
    ///     .with_mapping("application/problem+json", Renderer::Json);
    /// ```
    ///
    /// # Parameters
    ///
    /// - `media_type`: The media type pattern (e.g., "application/json", "text/*")
    /// - `renderer`: The renderer to use for this media type
    #[must_use = "builder methods take self by value and return the modified value"]
    pub fn with_mapping(mut self, media_type: impl Into<String>, renderer: Renderer) -> Self {
        // Insert at the beginning so custom mappings take precedence over defaults
        self.mappings.insert(0, (media_type.into(), renderer));
        self
    }

    /// Set the fallback renderer to use when no Accept header matches.
    ///
    /// The fallback renderer is used when:
    /// - No `Accept` header is present in the request
    /// - The `Accept` header doesn't match any configured media types
    /// - The `Accept` header is malformed
    ///
    /// Default fallback is [`Renderer::Json`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use apollo_errors::tower_http::{NegotiationConfig, Renderer};
    ///
    /// // Fall back to HTML for browser-friendly error pages
    /// let config = NegotiationConfig::new()
    ///     .with_fallback(Renderer::Html);
    /// ```
    #[must_use = "builder methods take self by value and return the modified value"]
    pub fn with_fallback(mut self, renderer: Renderer) -> Self {
        self.fallback = renderer;
        self
    }

    /// Override the built-in format defaults for a specific renderer.
    ///
    /// Overrides set here take precedence over the built-in renderer defaults. If no override is
    /// set, each renderer falls back to its built-in default:
    ///
    /// | Renderer | Field case (default) | Code case (default) |
    /// |----------|----------------------|---------------------|
    /// | [`Renderer::GraphQL`] | [`CamelCase`](FieldCase::CamelCase) | [`ScreamingSnakeCase`](CodeCase::ScreamingSnakeCase) |
    /// | [`Renderer::Json`] | [`SnakeCase`](FieldCase::SnakeCase) | [`Default`](CodeCase::Default) |
    /// | [`Renderer::JsonRpc`] | [`SnakeCase`](FieldCase::SnakeCase) | [`Default`](CodeCase::Default) |
    /// | [`Renderer::Html`] | [`SnakeCase`](FieldCase::SnakeCase) | [`Default`](CodeCase::Default) |
    /// | [`Renderer::Text`] | [`SnakeCase`](FieldCase::SnakeCase) | [`Default`](CodeCase::Default) |
    ///
    /// # Examples
    ///
    /// Override the JSON renderer to use camelCase field names (e.g. for a JavaScript client).
    /// Without an override, JSON uses `snake_case` field names and unmodified error codes:
    /// { "error": "config::invalid_port", "config_file": "/etc/app.toml" }
    ///
    /// ```rust
    /// use apollo_errors::tower_http::{NegotiationConfig, Renderer};
    /// use apollo_errors::{FormatConfig, FieldCase, CodeCase};
    ///
    ///
    /// // With override — JSON uses CamelCase + ScreamingSnakeCase:
    /// let config = NegotiationConfig::new()
    ///     .with_format_config(Renderer::Json, FormatConfig {
    ///         field_case: FieldCase::CamelCase,
    ///         code_case: CodeCase::ScreamingSnakeCase,
    ///     });
    /// // { "error": "CONFIG_INVALID_PORT", "configFile": "/etc/app.toml" }
    /// ```
    #[must_use = "builder methods take self by value and return the modified value"]
    pub fn with_format_config(mut self, renderer: Renderer, format_config: FormatConfig) -> Self {
        self.format_overrides.insert(renderer, format_config);
        self
    }

    pub(super) fn format_for(&self, renderer: Renderer) -> FormatConfig {
        self.format_overrides
            .get(&renderer)
            .copied()
            .unwrap_or_else(|| renderer.default_format_config())
    }

    /// Negotiate the best renderer based on the Accept header.
    ///
    /// This method parses the `Accept` header and selects the most appropriate
    /// renderer based on:
    /// 1. Media type matching (exact or wildcard)
    /// 2. Quality values (`q` parameters)
    /// 3. Specificity (more specific types are preferred)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use apollo_errors::tower_http::{NegotiationConfig, Renderer};
    ///
    /// let config = NegotiationConfig::new();
    ///
    /// // Exact match
    /// assert_eq!(config.negotiate(Some("application/json")), Renderer::Json);
    ///
    /// // Quality values
    /// assert_eq!(
    ///     config.negotiate(Some("text/html;q=0.9, application/json;q=0.8")),
    ///     Renderer::Html
    /// );
    ///
    /// // Wildcard
    /// assert_eq!(config.negotiate(Some("text/*")), Renderer::Html);
    ///
    /// // No match - uses fallback
    /// assert_eq!(config.negotiate(Some("application/xml")), Renderer::Json);
    /// assert_eq!(config.negotiate(None), Renderer::Json);
    /// ```
    pub fn negotiate(&self, accept_header: Option<&str>) -> Renderer {
        self.negotiate_with_content_type(accept_header).0
    }

    /// Negotiate the best renderer and return the content type to use in the response
    ///
    /// Returns (Renderer, content_type_string) where content_type_string is the
    /// actual media type that was matched (e.g., "application/json" even for GraphQL
    /// if that's what the client requested).
    pub fn negotiate_with_content_type(&self, accept_header: Option<&str>) -> (Renderer, String) {
        let Some(accept) = accept_header else {
            return (
                self.fallback,
                self.fallback.content_type().mime_type().to_string(),
            );
        };

        // Parse all media types from Accept header
        let mut media_types: Vec<MediaType> =
            accept.split(',').filter_map(MediaType::parse).collect();

        // Sort by quality (desc), then specificity (desc)
        media_types.sort_by(|a, b| {
            match b.quality.partial_cmp(&a.quality) {
                Some(Ordering::Equal) => {}
                Some(ord) => return ord,
                None => {
                    // SAFETY: NaN and infinite values are rejected during parsing (MediaType::parse),
                    // so this should never happen. If it does, it's a bug in our parsing logic.
                    unreachable!(
                        "Quality values should not be NaN or infinite: a={}, b={}",
                        a.quality, b.quality
                    );
                }
            }
            b.specificity().cmp(&a.specificity())
        });

        // Find first matching renderer
        for media_type in &media_types {
            // Check custom mappings (supports wildcards via matches())
            for (pattern, renderer) in &self.mappings {
                if let Some(pattern_media) = MediaType::parse(pattern) {
                    // Exact match
                    if media_type.ty == pattern_media.ty
                        && media_type.subtype == pattern_media.subtype
                    {
                        let content_type = format!("{}/{}", media_type.ty, media_type.subtype);
                        return (*renderer, content_type);
                    }
                }

                // Check if media_type matches this renderer's content type (handles wildcards)
                let content_type = renderer.content_type();
                if media_type.matches(content_type) {
                    return (*renderer, content_type.mime_type().to_string());
                }
            }
        }

        (
            self.fallback,
            self.fallback.content_type().mime_type().to_string(),
        )
    }

    /// Build a lookup map for faster negotiation
    pub fn build_lookup(&self) -> HashMap<String, Renderer> {
        self.mappings
            .iter()
            .map(|(k, v)| (k.to_lowercase(), *v))
            .collect()
    }
}

#[cfg(test)]
#[allow(clippy::float_cmp)]
mod tests {
    use super::*;

    #[test]
    fn test_media_type_parse() {
        let mt = MediaType::parse("text/html").unwrap();
        assert_eq!(mt.ty, "text");
        assert_eq!(mt.subtype, "html");
        assert_eq!(mt.quality, 1.0);
    }

    #[test]
    fn test_media_type_parse_with_quality() {
        let mt = MediaType::parse("text/html;q=0.9").unwrap();
        assert_eq!(mt.ty, "text");
        assert_eq!(mt.subtype, "html");
        assert_eq!(mt.quality, 0.9);
    }

    #[test]
    fn test_media_type_parse_wildcard() {
        let mt = MediaType::parse("*/*").unwrap();
        assert_eq!(mt.ty, "*");
        assert_eq!(mt.subtype, "*");
    }

    #[test]
    fn test_negotiate_json() {
        let config = NegotiationConfig::new();
        let renderer = config.negotiate(Some("application/json"));
        assert_eq!(renderer, Renderer::Json);
    }

    #[test]
    fn test_negotiate_html() {
        let config = NegotiationConfig::new();
        let renderer = config.negotiate(Some("text/html"));
        assert_eq!(renderer, Renderer::Html);
    }

    #[test]
    fn test_negotiate_graphql() {
        let config = NegotiationConfig::new();
        let renderer = config.negotiate(Some("application/graphql-response+json"));
        assert_eq!(renderer, Renderer::GraphQL);
    }

    #[test]
    fn test_negotiate_graphql_legacy() {
        let config = NegotiationConfig::new();
        let renderer = config.negotiate(Some("application/json+graphql"));
        assert_eq!(renderer, Renderer::GraphQL);
    }

    #[test]
    fn test_negotiate_text() {
        let config = NegotiationConfig::new();
        let renderer = config.negotiate(Some("text/plain"));
        assert_eq!(renderer, Renderer::Text);
    }

    #[test]
    fn test_negotiate_with_quality() {
        let config = NegotiationConfig::new();
        // HTML has higher quality, should be chosen
        let renderer = config.negotiate(Some("application/json;q=0.8, text/html;q=0.9"));
        assert_eq!(renderer, Renderer::Html);
    }

    #[test]
    fn test_negotiate_wildcard_fallback() {
        let config = NegotiationConfig::new();
        let renderer = config.negotiate(Some("*/*"));
        assert_eq!(renderer, Renderer::Json);
    }

    #[test]
    fn test_negotiate_no_header_fallback() {
        let config = NegotiationConfig::new();
        let renderer = config.negotiate(None);
        assert_eq!(renderer, Renderer::Json);
    }

    #[test]
    fn test_negotiate_custom_fallback() {
        let config = NegotiationConfig::new().with_fallback(Renderer::Text);
        let renderer = config.negotiate(None);
        assert_eq!(renderer, Renderer::Text);
    }

    #[test]
    fn test_negotiate_multiple_accept() {
        let config = NegotiationConfig::new();
        let renderer = config.negotiate(Some("text/html, application/json, */*"));
        // text/html comes first and has equal quality
        assert_eq!(renderer, Renderer::Html);
    }

    #[test]
    fn test_negotiate_text_wildcard() {
        let config = NegotiationConfig::new();
        let renderer = config.negotiate(Some("text/*"));
        // Should match text/html or text/plain - first in mappings wins
        assert_eq!(renderer, Renderer::Html);
    }

    #[test]
    fn test_negotiate_application_wildcard() {
        let config = NegotiationConfig::new();
        let renderer = config.negotiate(Some("application/*"));
        // Should match application/json or application/graphql-response+json
        assert_eq!(renderer, Renderer::Json);
    }

    #[test]
    fn test_negotiate_wildcard_with_quality() {
        let config = NegotiationConfig::new();
        // text/* with lower quality than application/json
        let renderer = config.negotiate(Some("text/*;q=0.5, application/json"));
        assert_eq!(renderer, Renderer::Json);
    }

    #[test]
    fn test_negotiate_wildcard_fallback_order() {
        let config = NegotiationConfig::new();
        // When text/* matches, it should prefer the first matching text type
        let renderer = config.negotiate(Some("text/*"));
        assert_eq!(renderer, Renderer::Html);
    }

    #[test]
    fn test_negotiate_specific_over_wildcard() {
        let config = NegotiationConfig::new();
        // Specific should win over wildcard due to specificity
        let renderer = config.negotiate(Some("text/*, text/plain"));
        assert_eq!(renderer, Renderer::Text);
    }

    #[test]
    fn test_negotiate_type_wildcard() {
        let config = NegotiationConfig::new();
        // */json is unusual but should work
        let renderer = config.negotiate(Some("*/json"));
        assert_eq!(renderer, Renderer::Json);
    }

    #[test]
    fn test_media_type_matches() {
        let mt = MediaType::parse("text/*").unwrap();
        assert!(mt.matches(ContentType::Html));
        assert!(mt.matches(ContentType::Text));
        assert!(!mt.matches(ContentType::Json));
        assert!(!mt.matches(ContentType::GraphQL));
    }

    #[test]
    fn test_media_type_matches_application_wildcard() {
        let mt = MediaType::parse("application/*").unwrap();
        assert!(mt.matches(ContentType::Json));
        assert!(mt.matches(ContentType::GraphQL));
        assert!(!mt.matches(ContentType::Html));
        assert!(!mt.matches(ContentType::Text));
    }

    #[test]
    fn test_media_type_matches_full_wildcard() {
        let mt = MediaType::parse("*/*").unwrap();
        assert!(mt.matches(ContentType::Json));
        assert!(mt.matches(ContentType::Html));
        assert!(mt.matches(ContentType::GraphQL));
        assert!(mt.matches(ContentType::Text));
    }

    #[test]
    fn test_media_type_parse_nan_quality() {
        // NaN quality should be rejected and default to 1.0
        let mt = MediaType::parse("text/html;q=NaN").unwrap();
        assert_eq!(mt.quality, 1.0);
        assert!(!mt.quality.is_nan());
    }

    #[test]
    fn test_media_type_parse_infinite_quality() {
        // Infinite quality should be rejected and default to 1.0
        let mt = MediaType::parse("text/html;q=inf").unwrap();
        assert_eq!(mt.quality, 1.0);
        assert!(mt.quality.is_finite());
    }

    #[test]
    fn test_media_type_parse_negative_quality() {
        // Negative quality should be clamped to 0.0
        let mt = MediaType::parse("text/html;q=-0.5").unwrap();
        assert_eq!(mt.quality, 0.0);
    }

    #[test]
    fn test_media_type_parse_quality_over_one() {
        // Quality over 1.0 should be clamped to 1.0
        let mt = MediaType::parse("text/html;q=2.5").unwrap();
        assert_eq!(mt.quality, 1.0);
    }

    #[test]
    fn test_negotiate_with_nan_quality() {
        let config = NegotiationConfig::new();
        // NaN should be treated as 1.0, so text/html should be chosen
        let renderer = config.negotiate(Some("text/html;q=NaN, application/json;q=0.5"));
        assert_eq!(renderer, Renderer::Html);
    }
}