Skip to main content

vld_http_common/
lib.rs

1//! # vld-http-common — Shared HTTP helpers for `vld` web integrations
2//!
3//! This crate provides the common parsing helpers and the shared
4//! [`VldHttpError`] type used by `vld-actix`, `vld-axum`, `vld-ntex`,
5//! `vld-poem`, `vld-rama`, `vld-rocket`, `vld-salvo`, `vld-tower`,
6//! `vld-warp` and `vld-tonic`.
7//!
8//! Applications normally use it through a framework adapter. Depend on it
9//! directly to write an adapter for another framework or to build the same
10//! error body by hand. It is framework-agnostic: no HTTP framework or `http`
11//! crate dependency.
12//!
13//! Guide: <https://s00d.github.io/vld/integrations/shared/http-common>
14//! (the rules below, per framework:
15//! <https://s00d.github.io/vld/integrations/web/overview>).
16//!
17//! # Example
18//!
19//! ```
20//! use vld_http_common::{parse_json_body, require_json_content_type, VldHttpError};
21//!
22//! vld::schema! {
23//!     #[derive(Debug)]
24//!     pub struct User {
25//!         pub name: String => vld::string().min(2),
26//!     }
27//! }
28//!
29//! fn extract(content_type: Option<&str>, body: &[u8]) -> Result<User, VldHttpError> {
30//!     require_json_content_type(content_type)?; // 415
31//!     let value = parse_json_body(body)?;       // 422 on malformed JSON
32//!     Ok(User::parse_value(&value)?)            // 422 on validation errors
33//! }
34//!
35//! let err = extract(Some("application/json"), br#"{"name": "A"}"#).unwrap_err();
36//! assert_eq!(err.status(), 422);
37//! assert_eq!(err.body()["issues"][0]["code"], "too_small");
38//! assert_eq!(extract(Some("text/plain"), b"{}").unwrap_err().status(), 415);
39//!
40//! // Text sources (query, form, path, headers, cookies) use `parse_coerced`.
41//! vld::schema! {
42//!     #[derive(Debug)]
43//!     pub struct Search {
44//!         pub q: String => vld::string(),
45//!         pub page: i64 => vld::number().int().min(1),
46//!         pub tags: Vec<String> => vld::array(vld::string()),
47//!     }
48//! }
49//!
50//! let value = vld_http_common::query_string_to_json("q=123&page=2&tags=a");
51//! let s: Search = vld_http_common::parse_coerced(&value).unwrap();
52//! assert_eq!((s.q.as_str(), s.page, s.tags.len()), ("123", 2, 1));
53//! ```
54//!
55//! # Value semantics (all adapters)
56//!
57//! - Query strings and form bodies: repeated keys (`a=1&a=2`) and `a[]=1`
58//!   become arrays; `?flag` and `?x=` become `""`.
59//! - Values are coerced with [`coerce_value`], which never loses information.
60//! - Coerced sources are validated with [`parse_coerced`]: a coerced number /
61//!   boolean is turned back into text where the schema expects a string
62//!   (`?q=123` into `vld::string()` is `"123"`), and a single value is
63//!   wrapped into an array where the schema expects one (`?tags=a`).
64//! - JSON body extractors require a JSON `Content-Type` (`application/json`
65//!   or `application/*+json`, see [`is_json_content_type`]) and form
66//!   extractors `application/x-www-form-urlencoded`
67//!   ([`require_form_content_type`]); a missing or different type is **415**
68//!   `{"error": "Unsupported Media Type", "message": ...}`.
69//! - Malformed bodies (JSON, non-UTF-8 forms, more than [`MAX_FORM_FIELDS`]
70//!   form fields) → **422** with the [`ValidationErrorBody`] shape; oversized
71//!   bodies → **413** `{"error": "Payload too large"}`.
72//! - Header names containing `_` are ignored (see [`headers_to_json`]); all
73//!   `Cookie` headers are read and the first occurrence of a cookie name wins
74//!   (see [`cookie_headers_to_json`]).
75//!
76//! # Error bodies
77//!
78//! | Status | Body |
79//! |---|---|
80//! | 422 | `{"error": "Validation failed", "issues": [{"path": ".name", "message": "...", "code": "too_small"}]}` |
81//! | 413 | `{"error": "Payload too large"}` |
82//! | 415 | `{"error": "Unsupported Media Type", "message": "Expected Content-Type: ..."}` |
83//!
84//! `path` is `""` for the root (e.g. malformed JSON), `.field` for fields and
85//! `[0]` for array items (`.items[0].name`); `code` is
86//! [`IssueCode::key()`](vld::error::IssueCode::key).
87
88pub use vld::schema::parse_coerced;
89
90/// Default max request body size (2 MiB — same as axum `DefaultBodyLimit`).
91///
92/// Every adapter applies it to JSON and form bodies unless a limit is
93/// configured ([`VldBodyLimit`], the framework's own setting, or a
94/// constructor argument; per adapter:
95/// <https://s00d.github.io/vld/integrations/web/overview#body-limits>).
96pub const DEFAULT_BODY_LIMIT: usize = 2 * 1024 * 1024;
97
98/// Max number of `&`-separated fields in a form body ([`parse_form_body`]).
99///
100/// Caps the memory a small body can expand into (`a&a&a&…` turns every two
101/// bytes into a JSON value); more fields are a 422 parse error.
102pub const MAX_FORM_FIELDS: usize = 1000;
103
104/// Body size limit in bytes, registered as request/app data for the adapters
105/// without a framework-native body limit setting (`vld-actix` `app_data`,
106/// `vld-ntex` app state, `vld-poem` `.data(..)`; `vld-rama` has its own
107/// extension type).
108///
109/// Without it those adapters use [`DEFAULT_BODY_LIMIT`].
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111pub struct VldBodyLimit(pub usize);
112
113/// Shared adapter conformance suite (test support, `conformance` feature).
114#[cfg(feature = "conformance")]
115pub mod conformance;
116
117/// Coerce a raw string value (query, form, path, header, cookie) into JSON.
118///
119/// Coercion never loses information: a value is only converted when the
120/// conversion round-trips to exactly the same text.
121///
122/// - `"true"` / `"false"` (lowercase only) → `Bool`
123/// - canonical integers (`0`, `42`, `-7`; no `+`, no leading zeros) that fit
124///   `i64`/`u64` → `Number`
125/// - canonical decimals (`3.14`, `-0.5`; no exponent, no trailing zeros, no
126///   precision loss in `f64`) → `Number`
127/// - everything else — including `""`, `"null"`, `"01234"`, `"+1555"`,
128///   `"1e3"`, `"TRUE"` and ids beyond `u64` — stays a `String`
129///
130/// Use `vld::string().coerce()` / `vld::number().coerce()` in schemas when a
131/// field must accept both forms (e.g. a string field that may look numeric).
132pub fn coerce_value(raw: &str) -> serde_json::Value {
133    use serde_json::Value;
134    match raw {
135        "true" => return Value::Bool(true),
136        "false" => return Value::Bool(false),
137        _ => {}
138    }
139    if is_canonical_number(raw) {
140        if !raw.contains('.') {
141            if let Ok(n) = raw.parse::<i64>() {
142                return Value::Number(n.into());
143            }
144            if let Ok(n) = raw.parse::<u64>() {
145                return Value::Number(n.into());
146            }
147        } else if let Ok(f) = raw.parse::<f64>() {
148            // `f64` Display is the shortest round-trip form: `1.50` → `1.5`,
149            // `0.1000000000000000001` → `0.1`; both stay strings.
150            if f.is_finite() && f.to_string() == raw {
151                if let Some(n) = serde_json::Number::from_f64(f) {
152                    return Value::Number(n);
153                }
154            }
155        }
156    }
157    Value::String(raw.to_string())
158}
159
160/// `-?(0|[1-9][0-9]*)(\.[0-9]+)?`, excluding `-0`.
161fn is_canonical_number(s: &str) -> bool {
162    let negative = s.starts_with('-');
163    let digits = s.strip_prefix('-').unwrap_or(s);
164    let (int, frac) = match digits.split_once('.') {
165        Some((i, f)) => (i, Some(f)),
166        None => (digits, None),
167    };
168    let all_digits = |p: &str| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit());
169    if !all_digits(int) || (int.len() > 1 && int.starts_with('0')) {
170        return false;
171    }
172    if frac.is_some_and(|f| !all_digits(f)) {
173        return false;
174    }
175    !(negative && frac.is_none() && int == "0")
176}
177
178/// Parse a URL query string (or `application/x-www-form-urlencoded` body)
179/// into a `serde_json::Map`.
180///
181/// - keys and values are form-decoded ([`url_decode`]) and values coerced via
182///   [`coerce_value`];
183/// - a key without `=` (`?flag`) yields `""`, like `URLSearchParams`;
184/// - a repeated key (`a=1&a=2`) yields an array `[1, 2]`;
185/// - a key ending in `[]` (`a[]=1`) always yields an array under `a`.
186pub fn parse_query_string(query: &str) -> serde_json::Map<String, serde_json::Value> {
187    use serde_json::Value;
188    let mut map = serde_json::Map::new();
189
190    for pair in query.split('&').filter(|p| !p.is_empty()) {
191        let (key, raw_value) = pair.split_once('=').unwrap_or((pair, ""));
192        let mut key = url_decode(key);
193        let value = coerce_value(&url_decode(raw_value));
194
195        let force_array = key.ends_with("[]");
196        if force_array {
197            key.truncate(key.len() - 2);
198        }
199
200        match map.get_mut(&key) {
201            Some(Value::Array(items)) => items.push(value),
202            Some(existing) => {
203                let first = existing.take();
204                *existing = Value::Array(vec![first, value]);
205            }
206            None if force_array => {
207                map.insert(key, Value::Array(vec![value]));
208            }
209            None => {
210                map.insert(key, value);
211            }
212        }
213    }
214
215    map
216}
217
218/// Parse a URL query string into a `serde_json::Value::Object`.
219///
220/// Convenience wrapper around [`parse_query_string`].
221pub fn query_string_to_json(query: &str) -> serde_json::Value {
222    serde_json::Value::Object(parse_query_string(query))
223}
224
225/// Build a JSON object from a `Cookie` header value.
226///
227/// Cookie names are used as-is. Values are unquoted (`"abc"` → `abc`),
228/// percent-decoded (`+` is kept) and coerced via [`coerce_value`].
229///
230/// When a name repeats (`sid=legit; sid=evil`) the **first** occurrence
231/// wins, as in most cookie parsers (browsers send the most specific path
232/// first); letting a later one win enables cookie tossing from a sibling
233/// subdomain.
234pub fn cookies_to_json(cookie_header: &str) -> serde_json::Value {
235    let mut map = serde_json::Map::new();
236
237    for cookie in cookie_header.split(';') {
238        let cookie = cookie.trim();
239        if cookie.is_empty() {
240            continue;
241        }
242        let (name, value) = cookie.split_once('=').unwrap_or((cookie, ""));
243        let value = value.trim();
244        let value = value
245            .strip_prefix('"')
246            .and_then(|v| v.strip_suffix('"'))
247            .unwrap_or(value);
248        map.entry(name.trim())
249            .or_insert_with(|| coerce_value(&percent_decode(value)));
250    }
251
252    serde_json::Value::Object(map)
253}
254
255/// Build a JSON object from **all** `Cookie` header values of a request.
256///
257/// HTTP/2 clients may send one `Cookie` header per cookie, so the values are
258/// joined with `"; "` before [`cookies_to_json`] (the first occurrence of a
259/// name wins). Non-UTF-8 bytes become `U+FFFD`.
260pub fn cookie_headers_to_json<'a, I>(values: I) -> serde_json::Value
261where
262    I: IntoIterator<Item = &'a [u8]>,
263{
264    let values: Vec<_> = values.into_iter().map(String::from_utf8_lossy).collect();
265    cookies_to_json(&values.join("; "))
266}
267
268/// Build a JSON object from HTTP header name/value pairs.
269///
270/// - names are lowercased and `-` becomes `_` (`X-Request-Id` → `x_request_id`);
271/// - names that already contain `_` (`x_user`) are **skipped**: a client
272///   could otherwise fill the `x_user` field past a proxy that strips only
273///   `X-User` (nginx, for one, also drops such names by default);
274/// - non-UTF-8 bytes become `U+FFFD` instead of silently dropping the header;
275/// - repeated headers are joined with `", "` (RFC 9110 §5.3);
276/// - the joined value is coerced via [`coerce_value`].
277pub fn headers_to_json<'a, I>(headers: I) -> serde_json::Value
278where
279    I: IntoIterator<Item = (&'a str, &'a [u8])>,
280{
281    let mut map = serde_json::Map::new();
282    let mut raw: Vec<(String, String)> = Vec::new();
283    for (name, value) in headers {
284        if name.contains('_') {
285            continue;
286        }
287        let key = name.to_ascii_lowercase().replace('-', "_");
288        let value = String::from_utf8_lossy(value);
289        match raw.iter_mut().find(|(k, _)| *k == key) {
290            Some((_, v)) => {
291                v.push_str(", ");
292                v.push_str(&value);
293            }
294            None => raw.push((key, value.into_owned())),
295        }
296    }
297    for (k, v) in raw {
298        map.insert(k, coerce_value(&v));
299    }
300    serde_json::Value::Object(map)
301}
302
303/// Build a JSON object from already-decoded path parameters, coercing each
304/// value via [`coerce_value`].
305pub fn path_params_to_json<'a, I>(params: I) -> serde_json::Value
306where
307    I: IntoIterator<Item = (&'a str, &'a str)>,
308{
309    serde_json::Value::Object(
310        params
311            .into_iter()
312            .map(|(k, v)| (k.to_string(), coerce_value(v)))
313            .collect(),
314    )
315}
316
317/// Parse an `application/x-www-form-urlencoded` body.
318///
319/// Fails with a 422 parse error when the body is not valid UTF-8 or has more
320/// than [`MAX_FORM_FIELDS`] fields.
321pub fn parse_form_body(body: &[u8]) -> Result<serde_json::Value, VldHttpError> {
322    let s = std::str::from_utf8(body)
323        .map_err(|_| VldHttpError::parse("Form body is not valid UTF-8"))?;
324    if s.split('&').filter(|p| !p.is_empty()).count() > MAX_FORM_FIELDS {
325        return Err(VldHttpError::parse(format!(
326            "Too many form fields (max {MAX_FORM_FIELDS})"
327        )));
328    }
329    Ok(query_string_to_json(s))
330}
331
332/// Parse a JSON body; malformed JSON is a 422 parse error.
333pub fn parse_json_body(body: &[u8]) -> Result<serde_json::Value, VldHttpError> {
334    serde_json::from_slice(body).map_err(|e| VldHttpError::parse(format!("Invalid JSON: {e}")))
335}
336
337/// The media type without parameters, trimmed and lowercased
338/// (`Application/JSON; charset=utf-8` → `application/json`).
339fn media_type_essence(content_type: &str) -> String {
340    content_type
341        .split(';')
342        .next()
343        .unwrap_or("")
344        .trim()
345        .to_ascii_lowercase()
346}
347
348/// `true` for `application/json` and any `application/<x>+json` media type
349/// with a non-empty `<x>` (case-insensitive; parameters such as
350/// `; charset=utf-8` are ignored, even malformed ones).
351pub fn is_json_content_type(content_type: &str) -> bool {
352    let essence = media_type_essence(content_type);
353    essence == "application/json"
354        || essence
355            .strip_prefix("application/")
356            .and_then(|s| s.strip_suffix("+json"))
357            .is_some_and(|prefix| !prefix.is_empty())
358}
359
360/// Check the `Content-Type` of a JSON body: `Ok` for JSON media types
361/// ([`is_json_content_type`]), otherwise a **415** error (also when the
362/// header is missing or not valid UTF-8).
363pub fn require_json_content_type(content_type: Option<&str>) -> Result<(), VldHttpError> {
364    match content_type {
365        Some(ct) if is_json_content_type(ct) => Ok(()),
366        _ => Err(VldHttpError::unsupported_media_type()),
367    }
368}
369
370/// Check the `Content-Type` of a form body: `Ok` for
371/// `application/x-www-form-urlencoded` (case-insensitive, parameters
372/// allowed), otherwise a **415** error (also when the header is missing or
373/// not valid UTF-8).
374pub fn require_form_content_type(content_type: Option<&str>) -> Result<(), VldHttpError> {
375    match content_type.map(media_type_essence) {
376        Some(ct) if ct == "application/x-www-form-urlencoded" => Ok(()),
377        _ => Err(VldHttpError::unsupported_form_media_type()),
378    }
379}
380
381// ---------------------------------------------------------------------------
382// Shared error type
383// ---------------------------------------------------------------------------
384
385/// Framework-independent error produced by all `vld` HTTP adapters.
386///
387/// | Constructor | Status | Body |
388/// |---|---|---|
389/// | [`validation`](Self::validation) / [`parse`](Self::parse) | 422 | [`ValidationErrorBody`] |
390/// | [`payload_too_large`](Self::payload_too_large) | 413 | [`ErrorBody`] |
391/// | [`unsupported_media_type`](Self::unsupported_media_type) / [`unsupported_form_media_type`](Self::unsupported_form_media_type) | 415 | [`ErrorWithMessage`] |
392///
393/// Adapters only convert [`status`](Self::status) and [`body`](Self::body)
394/// into their framework's response type.
395#[derive(Debug, Clone)]
396pub struct VldHttpError {
397    status: u16,
398    error: vld::error::VldError,
399}
400
401impl VldHttpError {
402    /// 422 — schema validation failed.
403    pub fn validation(error: vld::error::VldError) -> Self {
404        Self { status: 422, error }
405    }
406
407    /// 422 — the input could not be parsed (malformed JSON, bad UTF-8, ...).
408    pub fn parse(message: impl Into<String>) -> Self {
409        Self::validation(vld::error::VldError::single(
410            vld::error::IssueCode::ParseError,
411            message.into(),
412        ))
413    }
414
415    /// 413 — the body exceeds the size limit.
416    ///
417    /// [`error`](Self::error) holds a single `ParseError` issue
418    /// `"Payload too large"` (also what `Display` prints).
419    pub fn payload_too_large() -> Self {
420        Self {
421            status: 413,
422            error: vld::error::VldError::single(
423                vld::error::IssueCode::ParseError,
424                "Payload too large",
425            ),
426        }
427    }
428
429    /// 415 — a JSON body was sent without a JSON `Content-Type`.
430    ///
431    /// [`error`](Self::error) holds a single `ParseError` issue with
432    /// [`UNSUPPORTED_MEDIA_TYPE_MESSAGE`].
433    pub fn unsupported_media_type() -> Self {
434        Self::unsupported(UNSUPPORTED_MEDIA_TYPE_MESSAGE)
435    }
436
437    /// 415 — a form body was sent without
438    /// `Content-Type: application/x-www-form-urlencoded`.
439    ///
440    /// [`error`](Self::error) holds a single `ParseError` issue with
441    /// [`UNSUPPORTED_FORM_MEDIA_TYPE_MESSAGE`].
442    pub fn unsupported_form_media_type() -> Self {
443        Self::unsupported(UNSUPPORTED_FORM_MEDIA_TYPE_MESSAGE)
444    }
445
446    fn unsupported(message: &str) -> Self {
447        Self {
448            status: 415,
449            error: vld::error::VldError::single(vld::error::IssueCode::ParseError, message),
450        }
451    }
452
453    /// HTTP status code (422, 413 or 415).
454    #[must_use]
455    pub fn status(&self) -> u16 {
456        self.status
457    }
458
459    /// The underlying validation error.
460    pub fn error(&self) -> &vld::error::VldError {
461        &self.error
462    }
463
464    /// Consume and return the underlying validation error.
465    pub fn into_error(self) -> vld::error::VldError {
466        self.error
467    }
468
469    /// JSON response body for this error.
470    pub fn body(&self) -> serde_json::Value {
471        match self.status {
472            413 => format_payload_too_large(),
473            415 => serde_json::to_value(ErrorWithMessage {
474                error: "Unsupported Media Type".into(),
475                message: self
476                    .error
477                    .issues
478                    .first()
479                    .map_or(UNSUPPORTED_MEDIA_TYPE_MESSAGE, |i| i.message.as_str())
480                    .into(),
481            })
482            .expect("ErrorWithMessage serialization cannot fail"),
483            _ => format_vld_error(&self.error),
484        }
485    }
486}
487
488impl From<vld::error::VldError> for VldHttpError {
489    fn from(error: vld::error::VldError) -> Self {
490        Self::validation(error)
491    }
492}
493
494impl std::fmt::Display for VldHttpError {
495    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
496        match self.status {
497            413 => f.write_str("Payload too large"),
498            415 => f.write_str("Unsupported Media Type"),
499            _ => write!(f, "Validation failed: {}", self.error),
500        }
501    }
502}
503
504impl std::error::Error for VldHttpError {}
505
506/// Implement `Deref`/`DerefMut` to the inner value for tuple extractors
507/// `Name<T>(pub T)`.
508#[doc(hidden)]
509#[macro_export]
510macro_rules! impl_deref {
511    ($($name:ident),+ $(,)?) => {$(
512        impl<T> ::std::ops::Deref for $name<T> {
513            type Target = T;
514            fn deref(&self) -> &T {
515                &self.0
516            }
517        }
518        impl<T> ::std::ops::DerefMut for $name<T> {
519            fn deref_mut(&mut self) -> &mut T {
520                &mut self.0
521            }
522        }
523    )+};
524}
525
526// ---------------------------------------------------------------------------
527// Error response schemas (defined via vld::schema!)
528// ---------------------------------------------------------------------------
529
530use serde::Serialize;
531
532vld::schema! {
533    /// Simple error body: `{ "error": "..." }`.
534    ///
535    /// Used for generic HTTP errors such as "Payload too large",
536    /// "Not Found", "Method Not Allowed", etc.
537    #[derive(Debug, Clone, Serialize)]
538    pub struct ErrorBody {
539        pub error: String => vld::string(),
540    }
541}
542
543vld::schema! {
544    /// Error body with a message: `{ "error": "...", "message": "..." }`.
545    ///
546    /// The **415** body ([`VldHttpError::unsupported_media_type`],
547    /// [`VldHttpError::unsupported_form_media_type`]).
548    #[derive(Debug, Clone, Serialize)]
549    pub struct ErrorWithMessage {
550        pub error: String   => vld::string(),
551        pub message: String => vld::string(),
552    }
553}
554
555vld::schema! {
556    /// A single validation issue:
557    /// `{ "path": "...", "message": "...", "code": "..." }` (`code` is
558    /// [`IssueCode::key()`](vld::error::IssueCode::key)).
559    #[derive(Debug, Clone, Serialize)]
560    pub struct ValidationIssue {
561        pub path: String    => vld::string(),
562        pub message: String => vld::string(),
563        pub code: String    => vld::string(),
564    }
565}
566
567/// Same as [`ValidationIssue`], which always carries `code`.
568#[deprecated(since = "0.5.0", note = "use `ValidationIssue`")]
569pub type ValidationIssueWithCode = ValidationIssue;
570
571vld::schema! {
572    /// Validation error response body:
573    /// `{ "error": "Validation failed", "issues": [...] }`.
574    #[derive(Debug, Clone, Serialize)]
575    pub struct ValidationErrorBody {
576        pub error: String => vld::string(),
577        pub issues: Vec<ValidationIssue> => vld::array(vld::nested(ValidationIssue::parse_value)),
578    }
579}
580
581// ---------------------------------------------------------------------------
582// Formatting helpers
583// ---------------------------------------------------------------------------
584
585/// `.user.name`, `.items[0]` — spelled out instead of relying on
586/// `PathSegment`'s `Display` so the wire format stays stable.
587fn format_path(path: &[vld::error::PathSegment]) -> String {
588    use std::fmt::Write;
589    use vld::error::PathSegment;
590    let mut out = String::new();
591    for seg in path {
592        let _ = match seg {
593            PathSegment::Field(name) => write!(out, ".{name}"),
594            PathSegment::Index(idx) => write!(out, "[{idx}]"),
595        };
596    }
597    out
598}
599
600/// Format a [`VldError`](vld::error::VldError) into a list of
601/// [`ValidationIssue`] structs.
602pub fn format_issues(err: &vld::error::VldError) -> Vec<ValidationIssue> {
603    err.issues
604        .iter()
605        .map(|i| ValidationIssue {
606            path: format_path(&i.path),
607            message: i.message.clone(),
608            code: i.code.key().to_string(),
609        })
610        .collect()
611}
612
613/// Format a [`VldError`](vld::error::VldError) into a JSON object with
614/// `"error"` and `"issues"` keys — ready to be sent as a 422 response body.
615///
616/// Internally constructs a [`ValidationErrorBody`] and serializes it.
617pub fn format_vld_error(err: &vld::error::VldError) -> serde_json::Value {
618    let body = ValidationErrorBody {
619        error: "Validation failed".into(),
620        issues: format_issues(err),
621    };
622    serde_json::to_value(body).expect("ValidationErrorBody serialization cannot fail")
623}
624
625/// Same as [`format_issues`], which always includes `code`.
626#[deprecated(since = "0.5.0", note = "use `format_issues`")]
627pub fn format_issues_with_code(err: &vld::error::VldError) -> Vec<ValidationIssue> {
628    format_issues(err)
629}
630
631/// Decode a form/query component: `+` → space, then [`percent_decode`].
632pub fn url_decode(input: &str) -> String {
633    percent_decode(&input.replace('+', " "))
634}
635
636/// Percent-decode a URL component (path segment, cookie value); `+` is kept.
637///
638/// Only `%` followed by exactly two hex digits is decoded; anything else is
639/// kept literally. Decoded bytes are read as UTF-8 (`%C3%A9` → `é`); invalid
640/// sequences become `U+FFFD`.
641pub fn percent_decode(input: &str) -> String {
642    let bytes = input.as_bytes();
643    let hex = |i: usize| bytes.get(i).and_then(|&b| (b as char).to_digit(16));
644    let mut out = Vec::with_capacity(bytes.len());
645    let mut i = 0;
646    while i < bytes.len() {
647        if bytes[i] == b'%' {
648            if let (Some(h), Some(l)) = (hex(i + 1), hex(i + 2)) {
649                out.push((h * 16 + l) as u8);
650                i += 3;
651                continue;
652            }
653        }
654        out.push(bytes[i]);
655        i += 1;
656    }
657    String::from_utf8(out).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
658}
659
660// ---------------------------------------------------------------------------
661// Standard HTTP error response helpers
662// ---------------------------------------------------------------------------
663
664/// Build a JSON error body for invalid JSON parse errors.
665///
666/// Returns `{ "error": "Invalid JSON", "message": "..." }`.
667#[deprecated(
668    since = "0.5.0",
669    note = "unused: the adapters answer malformed JSON with a 422 `VldHttpError::parse` body"
670)]
671pub fn format_json_parse_error(message: &str) -> serde_json::Value {
672    serde_json::to_value(ErrorWithMessage {
673        error: "Invalid JSON".into(),
674        message: message.into(),
675    })
676    .expect("ErrorWithMessage serialization cannot fail")
677}
678
679/// Build a JSON error body for invalid UTF-8 payloads.
680///
681/// Returns `{ "error": "Invalid UTF-8" }`.
682#[deprecated(
683    since = "0.5.0",
684    note = "unused: the adapters answer invalid UTF-8 with a 422 `VldHttpError::parse` body"
685)]
686pub fn format_utf8_error() -> serde_json::Value {
687    format_generic_error("Invalid UTF-8")
688}
689
690/// Build a JSON error body for payloads that exceed the size limit.
691///
692/// Returns `{ "error": "Payload too large" }`.
693///
694/// Internally constructs an [`ErrorBody`] and serializes it.
695pub fn format_payload_too_large() -> serde_json::Value {
696    format_generic_error("Payload too large")
697}
698
699/// Message of the 415 body and error for JSON extractors.
700pub const UNSUPPORTED_MEDIA_TYPE_MESSAGE: &str =
701    "Expected Content-Type: application/json (or application/*+json)";
702
703/// Message of the 415 body and error for form extractors.
704pub const UNSUPPORTED_FORM_MEDIA_TYPE_MESSAGE: &str =
705    "Expected Content-Type: application/x-www-form-urlencoded";
706
707/// Build the JSON error body for a non-JSON `Content-Type`.
708///
709/// Returns `{ "error": "Unsupported Media Type", "message": "Expected Content-Type: ..." }`.
710pub fn format_unsupported_media_type() -> serde_json::Value {
711    VldHttpError::unsupported_media_type().body()
712}
713
714/// Build a generic JSON error body with a custom error string.
715///
716/// Returns `{ "error": "<error>" }`.
717///
718/// Internally constructs an [`ErrorBody`] and serializes it.
719pub fn format_generic_error(error: &str) -> serde_json::Value {
720    serde_json::to_value(ErrorBody {
721        error: error.into(),
722    })
723    .expect("ErrorBody serialization cannot fail")
724}