bibby 0.2.0

The official Rust SDK for Bytebury — typed clients, smart .env initialization, and ergonomic macros for Geo, Images, PDF, Mailer, Uploader, Cron, Forms, Webhooks, Monitors, and Vault.
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
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
//! Client and types for **Bytebury Images** (`https://api.bytebury.com/images/v1`).
//!
//! Inspect, transform, vectorize, analyze palettes/blurhash,
//! prepare images for vision LLMs, generate favicon sets, diff two images, and
//! read or generate QR codes.

use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use serde::{Deserialize, Serialize};

use crate::client::Bibby;
use crate::error::Result;

const PRODUCT: &str = "images";

/// Client for **Bytebury Images**.
///
/// Obtained via [`Bibby::images`].
#[derive(Debug, Clone, Copy)]
pub struct ImagesClient<'a> {
    client: &'a Bibby,
}

impl<'a> ImagesClient<'a> {
    pub(crate) fn new(client: &'a Bibby) -> Self {
        Self { client }
    }

    /// Reads format, dimensions, color type, and alpha metadata from an image header.
    ///
    /// Calls `POST /images/v1/images/info`.
    pub async fn info(&self, image: ImageSource) -> Result<ImageInfo> {
        #[derive(Serialize)]
        struct Body {
            image: ImageSource,
        }
        self.client
            .post_json(PRODUCT, "images/info", &Body { image })
            .await
    }

    /// Runs a sequential pipeline of up to 20 operations on an image and encodes the result.
    ///
    /// Use [`crate::image_ops!`] to build [`TransformRequest::operations`] concisely.
    ///
    /// Calls `POST /images/v1/images/transform`.
    pub async fn transform(&self, request: &TransformRequest) -> Result<EncodedImage> {
        self.client
            .post_json(PRODUCT, "images/transform", request)
            .await
    }

    /// Traces a raster image (up to 4 MP) into an SVG vector illustration.
    ///
    /// Calls `POST /images/v1/images/vectorize`.
    pub async fn vectorize(&self, request: &VectorizeRequest) -> Result<VectorImage> {
        self.client
            .post_json(PRODUCT, "images/vectorize", request)
            .await
    }

    /// Extracts dominant color palette, average color, transparency, BlurHash, and ThumbHash.
    ///
    /// Calls `POST /images/v1/images/analyze`.
    pub async fn analyze(&self, request: &AnalyzeRequest) -> Result<ImageAnalysis> {
        self.client
            .post_json(PRODUCT, "images/analyze", request)
            .await
    }

    /// Downscales and compresses an image to fit vision-model / bandwidth limits
    /// without ever upscaling.
    ///
    /// Calls `POST /images/v1/images/prepare`.
    pub async fn prepare(&self, request: &PrepareRequest) -> Result<EncodedImage> {
        self.client
            .post_json(PRODUCT, "images/prepare", request)
            .await
    }

    /// Generates a full favicon & web app icon pack (`favicon.ico`, PNG sizes,
    /// `apple-touch-icon.png`, `site.webmanifest`, and `<head>` HTML tags).
    ///
    /// Calls `POST /images/v1/images/icons`.
    pub async fn icons(&self, request: &IconsRequest) -> Result<IconSet> {
        self.client
            .post_json(PRODUCT, "images/icons", request)
            .await
    }

    /// Compares two images perceptually and (when dimensions match) pixel-by-pixel.
    ///
    /// Calls `POST /images/v1/images/compare`.
    pub async fn compare(&self, request: &CompareRequest) -> Result<Comparison> {
        self.client
            .post_json(PRODUCT, "images/compare", request)
            .await
    }

    /// Detects and decodes all QR codes in an image.
    ///
    /// Calls `POST /images/v1/qr-codes/read`.
    pub async fn read_qr_codes(&self, image: ImageSource) -> Result<QrCodes> {
        #[derive(Serialize)]
        struct Body {
            image: ImageSource,
        }
        self.client
            .post_json(PRODUCT, "qr-codes/read", &Body { image })
            .await
    }

    /// Generates a QR code image for the given text payload.
    ///
    /// Calls `POST /images/v1/qr-codes/generate`.
    pub async fn generate_qr_code(&self, request: &GenerateQrCodeRequest) -> Result<EncodedImage> {
        self.client
            .post_json(PRODUCT, "qr-codes/generate", request)
            .await
    }
}

/// Source image supplied to Bytebury Images endpoints.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ImageSource {
    /// Raw base64 or `data:<mime>;base64,...` data URL.
    Base64 {
        /// Base64-encoded image bytes.
        base64: String,
    },
    /// Public `http://` or `https://` image URL.
    Url {
        /// Public URL to fetch the image from.
        url: String,
    },
}

impl ImageSource {
    /// Encodes raw image bytes as base64.
    pub fn from_bytes(bytes: impl AsRef<[u8]>) -> Self {
        Self::Base64 {
            base64: STANDARD.encode(bytes.as_ref()),
        }
    }

    /// Uses an already base64-encoded string (or `data:` URL).
    pub fn from_base64(base64: impl Into<String>) -> Self {
        Self::Base64 {
            base64: base64.into(),
        }
    }

    /// References an image by public HTTP(S) URL.
    pub fn from_url(url: impl Into<String>) -> Self {
        Self::Url { url: url.into() }
    }
}

/// Supported image output formats.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ImageFormat {
    /// PNG (lossless).
    Png,
    /// JPEG (lossy; supports `quality`).
    #[serde(alias = "jpg")]
    Jpeg,
    /// WebP.
    Webp,
    /// GIF.
    Gif,
    /// BMP.
    Bmp,
    /// TIFF.
    Tiff,
    /// SVG (vectorized output).
    Svg,
}

/// Resize fit mode for [`Operation::Resize`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Fit {
    /// Preserve aspect ratio inside the bounding box (default).
    Contain,
    /// Preserve aspect ratio and crop to fill the exact box (requires both `width` and `height`).
    Cover,
    /// Stretch to exact dimensions (requires both `width` and `height`).
    Fill,
}

/// Flip axis for [`Operation::Flip`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FlipDirection {
    /// Mirror left-to-right.
    Horizontal,
    /// Mirror top-to-bottom.
    Vertical,
}

/// A single image transformation step for [`TransformRequest`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case")]
pub enum Operation {
    /// Resize the image.
    Resize {
        /// Target width in pixels (`1..=10000`).
        #[serde(skip_serializing_if = "Option::is_none")]
        width: Option<u32>,
        /// Target height in pixels (`1..=10000`).
        #[serde(skip_serializing_if = "Option::is_none")]
        height: Option<u32>,
        /// Fit mode (`contain`, `cover`, or `fill`).
        #[serde(skip_serializing_if = "Option::is_none")]
        fit: Option<Fit>,
    },
    /// Crop a rectangular region.
    Crop {
        /// Left offset in pixels.
        x: u32,
        /// Top offset in pixels.
        y: u32,
        /// Crop width (`1..=10000`).
        width: u32,
        /// Crop height (`1..=10000`).
        height: u32,
    },
    /// Rotate by `90`, `180`, `270`, or `-90` degrees.
    Rotate {
        /// Clockwise rotation angle (`90`, `180`, `270`, or `-90`).
        degrees: i32,
    },
    /// Flip horizontally or vertically.
    Flip {
        /// Flip axis.
        direction: FlipDirection,
    },
    /// Convert to grayscale.
    Grayscale,
    /// Invert all color channels.
    Invert,
    /// Apply Gaussian blur (`sigma` in `0.1..=50.0`).
    Blur {
        /// Blur radius sigma.
        sigma: f64,
    },
    /// Apply unsharp-mask sharpening.
    Sharpen {
        /// Sharpen sigma (`0.1..=50.0`, default `1.0`).
        #[serde(skip_serializing_if = "Option::is_none")]
        sigma: Option<f64>,
        /// Minimum brightness delta (`0..=255`, default `0`).
        #[serde(skip_serializing_if = "Option::is_none")]
        threshold: Option<u8>,
    },
    /// Adjust brightness (`-255..=255`).
    Brightness {
        /// Brightness delta.
        amount: i32,
    },
    /// Adjust contrast (`-100.0..=100.0`).
    Contrast {
        /// Contrast adjustment.
        amount: f64,
    },
    /// Rotate hue (`-360..=360`).
    Hue {
        /// Hue shift in degrees.
        degrees: i32,
    },
    /// Trim uniform border pixels.
    Trim {
        /// Per-channel color tolerance (`0..=254`, default `16`).
        #[serde(skip_serializing_if = "Option::is_none")]
        tolerance: Option<u8>,
    },
    /// Add padding around the image.
    Pad {
        /// Top padding in pixels.
        #[serde(skip_serializing_if = "Option::is_none")]
        top: Option<u32>,
        /// Right padding in pixels.
        #[serde(skip_serializing_if = "Option::is_none")]
        right: Option<u32>,
        /// Bottom padding in pixels.
        #[serde(skip_serializing_if = "Option::is_none")]
        bottom: Option<u32>,
        /// Left padding in pixels.
        #[serde(skip_serializing_if = "Option::is_none")]
        left: Option<u32>,
        /// Hex fill color (`#rrggbb` or `#rrggbbaa`).
        #[serde(skip_serializing_if = "Option::is_none")]
        color: Option<String>,
    },
    /// Flatten transparency onto a solid hex background color.
    Background {
        /// Hex color (`#rrggbb` or `#rrggbbaa`).
        color: String,
    },
    /// Pixelate the whole image or a rectangular sub-region.
    Pixelate {
        /// Pixel block size (`2..=500`).
        block: u32,
        /// Optional region left offset.
        #[serde(skip_serializing_if = "Option::is_none")]
        x: Option<u32>,
        /// Optional region top offset.
        #[serde(skip_serializing_if = "Option::is_none")]
        y: Option<u32>,
        /// Optional region width.
        #[serde(skip_serializing_if = "Option::is_none")]
        width: Option<u32>,
        /// Optional region height.
        #[serde(skip_serializing_if = "Option::is_none")]
        height: Option<u32>,
    },
}

/// Request body for [`ImagesClient::transform`].
#[derive(Debug, Clone, Serialize)]
pub struct TransformRequest {
    /// Input image.
    pub image: ImageSource,
    /// Sequential list of up to 20 operations.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub operations: Vec<Operation>,
    /// Output format (defaults to input format, or PNG for SVG inputs).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub format: Option<ImageFormat>,
    /// JPEG quality (`1..=100`, default `85`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quality: Option<u8>,
    /// Optional target maximum output size in bytes (`1024..=20_971_520`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_bytes: Option<usize>,
}

impl TransformRequest {
    /// Creates a new transform request for `image`.
    pub fn new(image: ImageSource) -> Self {
        Self {
            image,
            operations: Vec::new(),
            format: None,
            quality: None,
            max_bytes: None,
        }
    }

    /// Sets the list of operations (works great with [`crate::image_ops!`]).
    pub fn operations(mut self, operations: Vec<Operation>) -> Self {
        self.operations = operations;
        self
    }

    /// Appends a single operation to the pipeline.
    pub fn op(mut self, operation: Operation) -> Self {
        self.operations.push(operation);
        self
    }

    /// Sets the output format.
    pub fn format(mut self, format: ImageFormat) -> Self {
        self.format = Some(format);
        self
    }

    /// Sets JPEG output quality (`1..=100`).
    pub fn quality(mut self, quality: u8) -> Self {
        self.quality = Some(quality);
        self
    }

    /// Caps the output byte size (`1024..=20_971_520`).
    pub fn max_bytes(mut self, max_bytes: usize) -> Self {
        self.max_bytes = Some(max_bytes);
        self
    }
}

/// Tracing style for [`VectorizeRequest`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum VectorStyle {
    /// Flat posterized regions (default).
    Poster,
    /// Detailed photographic color layers.
    Photo,
    /// High-contrast line art.
    LineArt,
}

/// Curve fitting mode for [`VectorizeRequest`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum VectorCurves {
    /// Smooth cubic Bezier curves (default).
    Smooth,
    /// Straight-edged polygons.
    Polygon,
    /// Pixel-aligned staircase paths.
    Pixel,
}

/// Request body for [`ImagesClient::vectorize`].
#[derive(Debug, Clone, Serialize)]
pub struct VectorizeRequest {
    /// Input image (up to 4 megapixels).
    pub image: ImageSource,
    /// Tracing style.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub style: Option<VectorStyle>,
    /// Curve fitting mode.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub curves: Option<VectorCurves>,
    /// Maximum palette colors (`2..=64`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_colors: Option<u32>,
}

impl VectorizeRequest {
    /// Creates a vectorization request for `image`.
    pub fn new(image: ImageSource) -> Self {
        Self {
            image,
            style: None,
            curves: None,
            max_colors: None,
        }
    }

    /// Sets the tracing style.
    pub fn style(mut self, style: VectorStyle) -> Self {
        self.style = Some(style);
        self
    }

    /// Sets the curve fitting mode.
    pub fn curves(mut self, curves: VectorCurves) -> Self {
        self.curves = Some(curves);
        self
    }

    /// Sets the maximum number of colors (`2..=64`).
    pub fn max_colors(mut self, max_colors: u32) -> Self {
        self.max_colors = Some(max_colors);
        self
    }
}

/// Request body for [`ImagesClient::analyze`].
#[derive(Debug, Clone, Serialize)]
pub struct AnalyzeRequest {
    /// Input image.
    pub image: ImageSource,
    /// Number of palette colors to extract (`1..=12`, default `5`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub colors: Option<u32>,
}

impl AnalyzeRequest {
    /// Creates an analysis request for `image`.
    pub fn new(image: ImageSource) -> Self {
        Self {
            image,
            colors: None,
        }
    }

    /// Sets the number of dominant palette colors (`1..=12`).
    pub fn colors(mut self, colors: u32) -> Self {
        self.colors = Some(colors);
        self
    }
}

/// Request body for [`ImagesClient::prepare`].
#[derive(Debug, Clone, Serialize)]
pub struct PrepareRequest {
    /// Input image.
    pub image: ImageSource,
    /// Maximum side length in pixels (`64..=10000`, default `1568`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_side: Option<u32>,
    /// Maximum total pixel count (default `1_150_000`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_pixels: Option<u64>,
    /// Output format (default `jpeg`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub format: Option<ImageFormat>,
    /// Maximum output bytes (default `3_932_160`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_bytes: Option<usize>,
}

impl PrepareRequest {
    /// Creates an image preparation request for `image`.
    pub fn new(image: ImageSource) -> Self {
        Self {
            image,
            max_side: None,
            max_pixels: None,
            format: None,
            max_bytes: None,
        }
    }
}

/// Request body for [`ImagesClient::icons`].
#[derive(Debug, Clone, Serialize)]
pub struct IconsRequest {
    /// Source square/logo image.
    pub image: ImageSource,
    /// Optional hex background color (`#rrggbb` or `#rrggbbaa`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub background: Option<String>,
}

impl IconsRequest {
    /// Creates an icon-pack request for `image`.
    pub fn new(image: ImageSource) -> Self {
        Self {
            image,
            background: None,
        }
    }

    /// Sets a background hex color.
    pub fn background(mut self, hex: impl Into<String>) -> Self {
        self.background = Some(hex.into());
        self
    }
}

/// Request body for [`ImagesClient::compare`].
#[derive(Debug, Clone, Serialize)]
pub struct CompareRequest {
    /// First image.
    pub first: ImageSource,
    /// Second image.
    pub second: ImageSource,
    /// Per-channel pixel diff tolerance (`0..=254`, default `16`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tolerance: Option<u8>,
}

impl CompareRequest {
    /// Creates a comparison request between two images.
    pub fn new(first: ImageSource, second: ImageSource) -> Self {
        Self {
            first,
            second,
            tolerance: None,
        }
    }

    /// Sets the per-channel difference tolerance (`0..=254`).
    pub fn tolerance(mut self, tolerance: u8) -> Self {
        self.tolerance = Some(tolerance);
        self
    }
}

/// QR code error correction level.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrorCorrection {
    /// 7% recovery capacity.
    Low,
    /// 15% recovery capacity (default).
    Medium,
    /// 25% recovery capacity.
    Quartile,
    /// 30% recovery capacity.
    High,
}

/// Request body for [`ImagesClient::generate_qr_code`].
#[derive(Debug, Clone, Serialize)]
pub struct GenerateQrCodeRequest {
    /// Text or URL encoded in the QR code.
    pub text: String,
    /// Output width/height in pixels (`21..=4096`, default `512`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub size: Option<u32>,
    /// Quiet-zone margin in modules (`0..=20`, default `4`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub margin: Option<u32>,
    /// Error correction level.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_correction: Option<ErrorCorrection>,
    /// Foreground hex color (`#rrggbb` or `#rrggbbaa`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dark: Option<String>,
    /// Background hex color (`#rrggbb` or `#rrggbbaa`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub light: Option<String>,
    /// Output format.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub format: Option<ImageFormat>,
}

impl GenerateQrCodeRequest {
    /// Creates a QR code generation request for `text`.
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            size: None,
            margin: None,
            error_correction: None,
            dark: None,
            light: None,
            format: None,
        }
    }

    /// Sets the pixel size (`21..=4096`).
    pub fn size(mut self, size: u32) -> Self {
        self.size = Some(size);
        self
    }

    /// Sets the quiet-zone margin in modules (`0..=20`).
    pub fn margin(mut self, margin: u32) -> Self {
        self.margin = Some(margin);
        self
    }

    /// Sets the error correction level.
    pub fn error_correction(mut self, level: ErrorCorrection) -> Self {
        self.error_correction = Some(level);
        self
    }

    /// Sets the dark module hex color.
    pub fn dark(mut self, hex: impl Into<String>) -> Self {
        self.dark = Some(hex.into());
        self
    }

    /// Sets the light background hex color.
    pub fn light(mut self, hex: impl Into<String>) -> Self {
        self.light = Some(hex.into());
        self
    }

    /// Sets the output image format.
    pub fn format(mut self, format: ImageFormat) -> Self {
        self.format = Some(format);
        self
    }
}

/// Encoded image returned by transform, prepare, and QR generation endpoints.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EncodedImage {
    /// Output format (e.g. `"webp"`).
    pub format: String,
    /// MIME type (e.g. `"image/webp"`).
    pub mime_type: String,
    /// Width in pixels.
    pub width: u32,
    /// Height in pixels.
    pub height: u32,
    /// Decoded byte size.
    pub size_bytes: u64,
    /// Base64-encoded image bytes.
    pub data: String,
}

impl EncodedImage {
    /// Decodes [`Self::data`] from base64 into raw image bytes.
    pub fn decode_bytes(&self) -> Result<Vec<u8>> {
        Ok(STANDARD.decode(&self.data)?)
    }
}

/// Header metadata returned by [`ImagesClient::info`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ImageInfo {
    /// Image format name.
    pub format: String,
    /// MIME type.
    pub mime_type: String,
    /// Width in pixels (after EXIF orientation).
    pub width: u32,
    /// Height in pixels (after EXIF orientation).
    pub height: u32,
    /// Whether the image has an alpha channel.
    pub has_alpha: bool,
    /// Color representation (e.g. `"rgb8"`, `"rgba8"`).
    pub color: String,
    /// Input size in bytes.
    pub size_bytes: u64,
}

/// Vectorized SVG response from [`ImagesClient::vectorize`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VectorImage {
    /// Always `"image/svg+xml"`.
    pub mime_type: String,
    /// Width in pixels.
    pub width: u32,
    /// Height in pixels.
    pub height: u32,
    /// Number of SVG paths generated.
    pub paths: u64,
    /// Size of the SVG text in bytes.
    pub size_bytes: u64,
    /// Raw SVG markup (not base64-encoded).
    pub svg: String,
}

/// A dominant color entry in [`ImageAnalysis::palette`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PaletteColor {
    /// Hex color string (e.g. `"#0b0a0d"`).
    pub hex: String,
    /// Fraction of pixels in `0.0..=1.0`.
    pub share: f64,
}

/// Analysis result returned by [`ImagesClient::analyze`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ImageAnalysis {
    /// Width in pixels.
    pub width: u32,
    /// Height in pixels.
    pub height: u32,
    /// Whether any pixel is actually transparent.
    pub transparent: bool,
    /// Average hex color across opaque pixels, if any.
    pub average_color: Option<String>,
    /// Dominant palette colors.
    #[serde(default)]
    pub palette: Vec<PaletteColor>,
    /// Compact BlurHash placeholder string.
    pub blurhash: String,
    /// Base64-encoded ThumbHash placeholder.
    pub thumbhash: String,
}

/// A single generated file inside [`IconSet`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IconFile {
    /// Filename (e.g. `"favicon.ico"`, `"apple-touch-icon.png"`, `"site.webmanifest"`).
    pub name: String,
    /// MIME type.
    pub mime_type: String,
    /// Square pixel size (`0` for `site.webmanifest`).
    pub size: u32,
    /// Decoded byte size.
    pub size_bytes: u64,
    /// Base64-encoded file contents.
    pub data: String,
}

impl IconFile {
    /// Decodes [`Self::data`] from base64 into raw bytes.
    pub fn decode_bytes(&self) -> Result<Vec<u8>> {
        Ok(STANDARD.decode(&self.data)?)
    }
}

/// Favicon and icon bundle returned by [`ImagesClient::icons`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IconSet {
    /// Generated icon and manifest files.
    pub files: Vec<IconFile>,
    /// Ready-to-paste HTML `<link>` tags for `<head>`.
    pub html: String,
}

/// Pixel dimensions of a compared image.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Dimensions {
    /// Width in pixels.
    pub width: u32,
    /// Height in pixels.
    pub height: u32,
}

/// Bounding box of changed pixels in a [`PixelDiff`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChangedArea {
    /// Left offset in pixels.
    pub x: u32,
    /// Top offset in pixels.
    pub y: u32,
    /// Width in pixels.
    pub width: u32,
    /// Height in pixels.
    pub height: u32,
}

/// Pixel-level diff included in [`Comparison`] when both images have the same dimensions.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PixelDiff {
    /// Number of pixels exceeding the tolerance.
    pub changed_pixels: u64,
    /// Fraction of pixels changed (`0.0..=1.0`).
    pub changed_share: f64,
    /// Tight bounding box of changed pixels (`None` if zero pixels changed).
    pub changed_area: Option<ChangedArea>,
    /// PNG diff image highlighting changed pixels in red.
    pub diff: EncodedImage,
}

/// Comparison result returned by [`ImagesClient::compare`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Comparison {
    /// `true` if the images are byte/pixel identical.
    pub identical: bool,
    /// Perceptual similarity score in `0.0..=1.0`.
    pub similarity: f64,
    /// `true` when `similarity >= 0.85`.
    pub same_picture: bool,
    /// Dimensions of the first image.
    pub first: Dimensions,
    /// Dimensions of the second image.
    pub second: Dimensions,
    /// Pixel diff (present only when dimensions match).
    pub pixels: Option<PixelDiff>,
}

/// Pixel coordinates of a QR code corner.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct QrCorner {
    /// X coordinate in pixels.
    pub x: i32,
    /// Y coordinate in pixels.
    pub y: i32,
}

/// A single decoded QR code.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct QrCode {
    /// Decoded UTF-8 payload.
    pub text: String,
    /// Four corner points in image pixel coordinates.
    #[serde(default)]
    pub corners: Vec<QrCorner>,
}

/// Response from [`ImagesClient::read_qr_codes`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct QrCodes {
    /// All QR codes found in the image.
    #[serde(default)]
    pub codes: Vec<QrCode>,
}