Skip to main content

strands/types/
media.rs

1//! Media and document content blocks and their formats.
2//!
3//! Binary data is a `Vec<u8>` in memory and a standard base64 string on the wire.
4
5use serde::{Deserialize, Deserializer, Serialize, Serializer};
6
7use super::messages::TextBlock;
8
9/// Serde helpers for bytes stored as base64 strings.
10///
11/// Encoding is standard padded base64. Decoding is lenient: it accepts missing padding, the URL-safe
12/// alphabet and embedded whitespace. It also accepts the byte forms other Strands SDKs may write: a
13/// JSON array of byte values and an index-keyed object (`{"0":1,"1":2}`).
14pub(crate) mod base64_bytes {
15    use std::fmt;
16
17    use base64::Engine as _;
18    use base64::alphabet::STANDARD as STANDARD_ALPHABET;
19    use base64::engine::general_purpose::STANDARD;
20    use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig};
21    use serde::de::{self, MapAccess, SeqAccess, Visitor};
22    use serde::{Deserializer, Serializer};
23
24    const LENIENT: GeneralPurpose = GeneralPurpose::new(
25        &STANDARD_ALPHABET,
26        GeneralPurposeConfig::new()
27            .with_decode_padding_mode(DecodePaddingMode::Indifferent)
28            .with_decode_allow_trailing_bits(true),
29    );
30
31    pub(crate) fn encode(bytes: &[u8]) -> String {
32        STANDARD.encode(bytes)
33    }
34
35    pub(crate) fn decode(text: &str) -> Result<Vec<u8>, base64::DecodeError> {
36        let normalized: String = text
37            .chars()
38            .filter(|c| !c.is_ascii_whitespace())
39            .map(|c| match c {
40                '-' => '+',
41                '_' => '/',
42                other => other,
43            })
44            .collect();
45        LENIENT.decode(normalized.trim_end_matches('='))
46    }
47
48    pub(crate) fn serialize<S: Serializer>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error> {
49        serializer.serialize_str(&encode(bytes))
50    }
51
52    pub(crate) fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<u8>, D::Error> {
53        deserializer.deserialize_any(BytesVisitor)
54    }
55
56    struct BytesVisitor;
57
58    impl<'de> Visitor<'de> for BytesVisitor {
59        type Value = Vec<u8>;
60
61        fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62            f.write_str("a base64 string, an array of bytes or an index-keyed object of bytes")
63        }
64
65        fn visit_str<E: de::Error>(self, text: &str) -> Result<Vec<u8>, E> {
66            decode(text).map_err(|error| E::custom(format!("invalid base64 bytes: {error}")))
67        }
68
69        fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<u8>, A::Error> {
70            let mut bytes = Vec::with_capacity(seq.size_hint().unwrap_or(0));
71            while let Some(byte) = seq.next_element::<u8>()? {
72                bytes.push(byte);
73            }
74            Ok(bytes)
75        }
76
77        fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Vec<u8>, A::Error> {
78            let mut indexed = Vec::with_capacity(map.size_hint().unwrap_or(0));
79            while let Some((key, byte)) = map.next_entry::<String, u8>()? {
80                let index = key
81                    .parse::<usize>()
82                    .map_err(|_| de::Error::custom(format!("byte object key `{key}` is not an index")))?;
83                indexed.push((index, byte));
84            }
85            indexed.sort_unstable_by_key(|(index, _)| *index);
86            let contiguous = indexed
87                .iter()
88                .enumerate()
89                .all(|(position, (index, _))| position == *index);
90            if !contiguous {
91                return Err(de::Error::custom("byte object keys must be the indices 0..n"));
92            }
93            Ok(indexed.into_iter().map(|(_, byte)| byte).collect())
94        }
95    }
96
97    pub(crate) mod option {
98        use serde::{Deserialize, Deserializer, Serializer};
99
100        #[derive(Deserialize)]
101        struct Wrapped(#[serde(with = "super")] Vec<u8>);
102
103        #[allow(clippy::ref_option, reason = "serde `with` passes `&Option<T>`")]
104        pub(crate) fn serialize<S: Serializer>(bytes: &Option<Vec<u8>>, serializer: S) -> Result<S::Ok, S::Error> {
105            match bytes {
106                Some(bytes) => super::serialize(bytes, serializer),
107                None => serializer.serialize_none(),
108            }
109        }
110
111        pub(crate) fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<Vec<u8>>, D::Error> {
112            Ok(Option::<Wrapped>::deserialize(deserializer)?.map(|wrapped| wrapped.0))
113        }
114    }
115}
116
117/// Audio format (`AudioFormat`).
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
119#[serde(rename_all = "lowercase")]
120#[non_exhaustive]
121pub enum AudioFormat {
122    /// `mp3`
123    Mp3,
124    /// `opus`
125    Opus,
126    /// `wav`
127    Wav,
128    /// `aac`
129    Aac,
130    /// `flac`
131    Flac,
132    /// `mp4`
133    Mp4,
134    /// `ogg`
135    Ogg,
136    /// `mkv`
137    Mkv,
138    /// `mka`
139    Mka,
140    /// `x-aac`
141    #[serde(rename = "x-aac")]
142    XAac,
143    /// `m4a`
144    M4a,
145    /// `mpeg`
146    Mpeg,
147    /// `mpga`
148    Mpga,
149    /// `pcm`
150    Pcm,
151    /// `webm`
152    Webm,
153}
154
155/// Image format (`ImageFormat`).
156#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
157#[serde(rename_all = "lowercase")]
158#[non_exhaustive]
159pub enum ImageFormat {
160    /// `png`
161    Png,
162    /// `jpg`
163    Jpg,
164    /// `jpeg`
165    Jpeg,
166    /// `gif`
167    Gif,
168    /// `webp`
169    Webp,
170}
171
172/// Video format (`VideoFormat`).
173#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
174#[serde(rename_all = "lowercase")]
175#[non_exhaustive]
176pub enum VideoFormat {
177    /// `mkv`
178    Mkv,
179    /// `mov`
180    Mov,
181    /// `mp4`
182    Mp4,
183    /// `webm`
184    Webm,
185    /// `flv`
186    Flv,
187    /// `mpeg`
188    Mpeg,
189    /// `mpg`
190    Mpg,
191    /// `wmv`
192    Wmv,
193    /// `3gp`
194    #[serde(rename = "3gp")]
195    ThreeGp,
196}
197
198/// Document format (`DocumentFormat`).
199#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
200#[serde(rename_all = "lowercase")]
201#[non_exhaustive]
202pub enum DocumentFormat {
203    /// `pdf`
204    Pdf,
205    /// `csv`
206    Csv,
207    /// `doc`
208    Doc,
209    /// `docx`
210    Docx,
211    /// `xls`
212    Xls,
213    /// `xlsx`
214    Xlsx,
215    /// `html`
216    Html,
217    /// `txt`
218    Txt,
219    /// `md`
220    Md,
221    /// `json`
222    Json,
223    /// `xml`
224    Xml,
225}
226
227/// An S3 object location for media and document sources (`S3Location`).
228///
229/// Serializes with `"type": "s3"` first.
230#[derive(Debug, Clone, PartialEq, Eq)]
231#[non_exhaustive]
232pub struct S3Location {
233    /// S3 URI, `s3://bucket-name/key-name`.
234    pub uri: String,
235    /// AWS account ID of the bucket owner, required when the bucket belongs to another account.
236    pub bucket_owner: Option<String>,
237}
238
239impl S3Location {
240    /// Creates a location from an S3 URI.
241    pub fn new(uri: impl Into<String>) -> Self {
242        Self {
243            uri: uri.into(),
244            bucket_owner: None,
245        }
246    }
247
248    /// Sets the bucket owner's account ID.
249    #[must_use]
250    pub fn with_bucket_owner(mut self, bucket_owner: impl Into<String>) -> Self {
251        self.bucket_owner = Some(bucket_owner.into());
252        self
253    }
254}
255
256#[derive(Serialize)]
257#[serde(rename_all = "camelCase")]
258struct S3LocationWire<'a> {
259    r#type: &'static str,
260    uri: &'a str,
261    #[serde(skip_serializing_if = "Option::is_none")]
262    bucket_owner: Option<&'a str>,
263}
264
265#[derive(Deserialize)]
266#[serde(rename_all = "camelCase")]
267struct S3LocationData {
268    uri: String,
269    #[serde(default)]
270    bucket_owner: Option<String>,
271}
272
273impl Serialize for S3Location {
274    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
275        S3LocationWire {
276            r#type: "s3",
277            uri: &self.uri,
278            bucket_owner: self.bucket_owner.as_deref(),
279        }
280        .serialize(serializer)
281    }
282}
283
284impl<'de> Deserialize<'de> for S3Location {
285    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
286        let data = S3LocationData::deserialize(deserializer)?;
287        Ok(Self {
288            uri: data.uri,
289            bucket_owner: data.bucket_owner,
290        })
291    }
292}
293
294/// Source of an audio block (`AudioSource`).
295#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
296#[serde(rename_all = "camelCase")]
297#[non_exhaustive]
298pub enum AudioSource {
299    /// Raw bytes, base64 on the wire.
300    Bytes(#[serde(with = "base64_bytes")] Vec<u8>),
301    /// An S3 location.
302    Location(S3Location),
303}
304
305/// Source of an image block (`ImageSource`).
306#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
307#[serde(rename_all = "camelCase")]
308#[non_exhaustive]
309pub enum ImageSource {
310    /// Raw bytes, base64 on the wire.
311    Bytes(#[serde(with = "base64_bytes")] Vec<u8>),
312    /// An S3 location.
313    Location(S3Location),
314    /// An `https://` URL.
315    Url(String),
316}
317
318/// Source of a video block (`VideoSource`).
319#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
320#[serde(rename_all = "camelCase")]
321#[non_exhaustive]
322pub enum VideoSource {
323    /// Raw bytes, base64 on the wire.
324    Bytes(#[serde(with = "base64_bytes")] Vec<u8>),
325    /// An S3 location.
326    Location(S3Location),
327}
328
329/// A block nested inside a document's structured content (`DocumentContentBlock`).
330pub type DocumentContentBlock = TextBlock;
331
332/// Source of a document block (`DocumentSource`).
333#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
334#[serde(rename_all = "camelCase")]
335#[non_exhaustive]
336pub enum DocumentSource {
337    /// Raw bytes, base64 on the wire.
338    Bytes(#[serde(with = "base64_bytes")] Vec<u8>),
339    /// Plain text.
340    Text(String),
341    /// Structured content made of text blocks.
342    Content(Vec<DocumentContentBlock>),
343    /// An S3 location.
344    Location(S3Location),
345}
346
347/// Audio content block (`AudioBlock`).
348#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
349#[non_exhaustive]
350pub struct AudioBlock {
351    /// Audio format.
352    pub format: AudioFormat,
353    /// Audio source.
354    pub source: AudioSource,
355}
356
357impl AudioBlock {
358    /// Creates an audio block.
359    pub fn new(format: AudioFormat, source: AudioSource) -> Self {
360        Self { format, source }
361    }
362}
363
364/// Image content block (`ImageBlock`).
365#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
366#[non_exhaustive]
367pub struct ImageBlock {
368    /// Image format.
369    pub format: ImageFormat,
370    /// Image source.
371    pub source: ImageSource,
372}
373
374impl ImageBlock {
375    /// Creates an image block.
376    pub fn new(format: ImageFormat, source: ImageSource) -> Self {
377        Self { format, source }
378    }
379}
380
381/// Video content block (`VideoBlock`).
382#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
383#[non_exhaustive]
384pub struct VideoBlock {
385    /// Video format.
386    pub format: VideoFormat,
387    /// Video source.
388    pub source: VideoSource,
389}
390
391impl VideoBlock {
392    /// Creates a video block.
393    pub fn new(format: VideoFormat, source: VideoSource) -> Self {
394        Self { format, source }
395    }
396}
397
398/// Citation configuration of a document block.
399#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
400#[non_exhaustive]
401pub struct DocumentCitations {
402    /// Whether the model may cite this document.
403    pub enabled: bool,
404}
405
406impl DocumentCitations {
407    /// Creates the configuration.
408    pub fn new(enabled: bool) -> Self {
409        Self { enabled }
410    }
411}
412
413/// Document content block (`DocumentBlock`).
414#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
415#[non_exhaustive]
416pub struct DocumentBlock {
417    /// Document name.
418    pub name: String,
419    /// Document format.
420    pub format: DocumentFormat,
421    /// Document source.
422    pub source: DocumentSource,
423    /// Citation configuration.
424    #[serde(default, skip_serializing_if = "Option::is_none")]
425    pub citations: Option<DocumentCitations>,
426    /// Context information for the document.
427    #[serde(default, skip_serializing_if = "Option::is_none")]
428    pub context: Option<String>,
429}
430
431impl DocumentBlock {
432    /// Creates a document block.
433    pub fn new(name: impl Into<String>, format: DocumentFormat, source: DocumentSource) -> Self {
434        Self {
435            name: name.into(),
436            format,
437            source,
438            citations: None,
439            context: None,
440        }
441    }
442
443    /// Sets the citation configuration.
444    #[must_use]
445    pub fn with_citations(mut self, citations: DocumentCitations) -> Self {
446        self.citations = Some(citations);
447        self
448    }
449
450    /// Sets the document context.
451    #[must_use]
452    pub fn with_context(mut self, context: impl Into<String>) -> Self {
453        self.context = Some(context.into());
454        self
455    }
456}
457
458#[cfg(test)]
459mod tests {
460    use serde_json::json;
461
462    use super::*;
463
464    fn bytes() -> Vec<u8> {
465        vec![1, 2, 3]
466    }
467
468    fn round_trip<T: Serialize + for<'de> Deserialize<'de> + PartialEq + std::fmt::Debug>(value: &T) {
469        let json = serde_json::to_value(value).unwrap();
470        assert_eq!(&serde_json::from_value::<T>(json).unwrap(), value);
471    }
472
473    #[test]
474    fn creates_instance_with_uri_only() {
475        let location = S3Location::new("s3://test-bucket/file.jpg");
476        assert_eq!(location.uri, "s3://test-bucket/file.jpg");
477        assert_eq!(location.bucket_owner, None);
478    }
479
480    #[test]
481    fn creates_instance_with_uri_and_bucket_owner() {
482        let location = S3Location::new("s3://test-bucket/file.jpg").with_bucket_owner("123456789012");
483        assert_eq!(location.bucket_owner.as_deref(), Some("123456789012"));
484    }
485
486    #[test]
487    fn audio_block_creates_instance_with_bytes_source() {
488        let block = AudioBlock::new(AudioFormat::Mp3, AudioSource::Bytes(bytes()));
489        assert_eq!(
490            serde_json::to_value(&block).unwrap(),
491            json!({"format": "mp3", "source": {"bytes": "AQID"}})
492        );
493    }
494
495    #[test]
496    fn audio_block_creates_instance_with_s3_location_source() {
497        let block = AudioBlock::new(
498            AudioFormat::Wav,
499            AudioSource::Location(S3Location::new("s3://b/a.wav").with_bucket_owner("123456789012")),
500        );
501        assert_eq!(
502            serde_json::to_value(&block).unwrap(),
503            json!({"format": "wav", "source": {"location": {"type": "s3", "uri": "s3://b/a.wav", "bucketOwner": "123456789012"}}})
504        );
505    }
506
507    #[test]
508    fn audio_block_throws_error_for_invalid_source() {
509        assert!(serde_json::from_value::<AudioBlock>(json!({"format": "mp3", "source": {}})).is_err());
510    }
511
512    #[test]
513    fn image_block_creates_instance_with_bytes_source() {
514        let block = ImageBlock::new(ImageFormat::Png, ImageSource::Bytes(bytes()));
515        assert_eq!(
516            serde_json::to_value(&block).unwrap(),
517            json!({"format": "png", "source": {"bytes": "AQID"}})
518        );
519    }
520
521    #[test]
522    fn image_block_creates_instance_with_s3_location_source() {
523        let block = ImageBlock::new(
524            ImageFormat::Jpeg,
525            ImageSource::Location(S3Location::new("s3://b/i.jpg")),
526        );
527        assert_eq!(
528            serde_json::to_value(&block).unwrap(),
529            json!({"format": "jpeg", "source": {"location": {"type": "s3", "uri": "s3://b/i.jpg"}}})
530        );
531    }
532
533    #[test]
534    fn image_block_creates_instance_with_url_source() {
535        let block = ImageBlock::new(ImageFormat::Webp, ImageSource::Url("https://example.com/i.webp".into()));
536        assert_eq!(
537            serde_json::to_value(&block).unwrap(),
538            json!({"format": "webp", "source": {"url": "https://example.com/i.webp"}})
539        );
540    }
541
542    #[test]
543    fn image_block_throws_error_for_invalid_source() {
544        assert!(serde_json::from_value::<ImageBlock>(json!({"format": "png", "source": {}})).is_err());
545    }
546
547    #[test]
548    fn video_block_creates_instance_with_bytes_source() {
549        let block = VideoBlock::new(VideoFormat::Mp4, VideoSource::Bytes(bytes()));
550        assert_eq!(
551            serde_json::to_value(&block).unwrap(),
552            json!({"format": "mp4", "source": {"bytes": "AQID"}})
553        );
554    }
555
556    #[test]
557    fn video_block_creates_instance_with_s3_location_source() {
558        let block = VideoBlock::new(VideoFormat::ThreeGp, VideoSource::Location(S3Location::new("s3://b/v")));
559        assert_eq!(
560            serde_json::to_value(&block).unwrap(),
561            json!({"format": "3gp", "source": {"location": {"type": "s3", "uri": "s3://b/v"}}})
562        );
563    }
564
565    #[test]
566    fn video_block_throws_error_for_invalid_source() {
567        assert!(serde_json::from_value::<VideoBlock>(json!({"format": "mp4", "source": {}})).is_err());
568    }
569
570    #[test]
571    fn document_block_creates_instance_with_bytes_source() {
572        let block = DocumentBlock::new("doc", DocumentFormat::Pdf, DocumentSource::Bytes(bytes()));
573        assert_eq!(
574            serde_json::to_value(&block).unwrap(),
575            json!({"name": "doc", "format": "pdf", "source": {"bytes": "AQID"}})
576        );
577    }
578
579    #[test]
580    fn document_block_creates_instance_with_text_source() {
581        let block = DocumentBlock::new("doc", DocumentFormat::Txt, DocumentSource::Text("Hello".into()));
582        assert_eq!(
583            serde_json::to_value(&block).unwrap(),
584            json!({"name": "doc", "format": "txt", "source": {"text": "Hello"}})
585        );
586    }
587
588    #[test]
589    fn document_block_creates_instance_with_content_source() {
590        let source = DocumentSource::Content(vec![TextBlock::new("one"), TextBlock::new("two")]);
591        let block = DocumentBlock::new("doc", DocumentFormat::Html, source);
592        assert_eq!(
593            serde_json::to_value(&block).unwrap(),
594            json!({"name": "doc", "format": "html", "source": {"content": [{"text": "one"}, {"text": "two"}]}})
595        );
596    }
597
598    #[test]
599    fn document_block_creates_instance_with_s3_location_source() {
600        let block = DocumentBlock::new(
601            "doc",
602            DocumentFormat::Docx,
603            DocumentSource::Location(S3Location::new("s3://b/d.docx")),
604        );
605        assert_eq!(
606            serde_json::to_value(&block).unwrap(),
607            json!({"name": "doc", "format": "docx", "source": {"location": {"type": "s3", "uri": "s3://b/d.docx"}}})
608        );
609    }
610
611    #[test]
612    fn creates_instance_with_bytes_and_filename() {
613        let block = DocumentBlock::new("upload.pdf", DocumentFormat::Pdf, DocumentSource::Bytes(bytes()));
614        assert_eq!(
615            serde_json::to_value(&block).unwrap(),
616            json!({"name": "upload.pdf", "format": "pdf", "source": {"bytes": "AQID"}})
617        );
618    }
619
620    #[test]
621    fn creates_instance_with_text_and_filename() {
622        let block = DocumentBlock::new(
623            "note.txt",
624            DocumentFormat::Txt,
625            DocumentSource::Text("Hello world".into()),
626        );
627        assert_eq!(
628            serde_json::to_value(&block).unwrap(),
629            json!({"name": "note.txt", "format": "txt", "source": {"text": "Hello world"}})
630        );
631    }
632
633    #[test]
634    fn creates_instance_with_citations_and_context() {
635        let block = DocumentBlock::new("research.pdf", DocumentFormat::Pdf, DocumentSource::Bytes(bytes()))
636            .with_citations(DocumentCitations::new(true))
637            .with_context("Research paper about AI");
638        assert_eq!(
639            serde_json::to_value(&block).unwrap(),
640            json!({
641                "name": "research.pdf",
642                "format": "pdf",
643                "source": {"bytes": "AQID"},
644                "citations": {"enabled": true},
645                "context": "Research paper about AI"
646            })
647        );
648    }
649
650    #[test]
651    fn document_block_throws_error_for_invalid_source() {
652        assert!(serde_json::from_value::<DocumentBlock>(json!({"name": "d", "format": "pdf", "source": {}})).is_err());
653    }
654
655    #[test]
656    fn round_trips_empty_array() {
657        round_trip(&ImageSource::Bytes(Vec::new()));
658        assert_eq!(base64_bytes::encode(&[]), "");
659    }
660
661    #[test]
662    fn round_trips_single_byte() {
663        round_trip(&ImageSource::Bytes(vec![255]));
664    }
665
666    #[test]
667    fn round_trips_multi_byte_array() {
668        round_trip(&ImageSource::Bytes(vec![0, 1, 127, 128, 255]));
669    }
670
671    #[test]
672    fn round_trips_large_array() {
673        let large: Vec<u8> = (0..100_000u32).map(|i| (i % 256) as u8).collect();
674        round_trip(&ImageSource::Bytes(large));
675    }
676
677    #[test]
678    fn audio_block_from_json_accepts_base64_string_for_bytes() {
679        let block: AudioBlock = serde_json::from_value(json!({"format": "mp3", "source": {"bytes": "AQID"}})).unwrap();
680        assert_eq!(block.source, AudioSource::Bytes(bytes()));
681    }
682
683    #[test]
684    fn audio_block_from_json_accepts_uint8_array_for_bytes() {
685        let block: AudioBlock =
686            serde_json::from_value(json!({"format": "mp3", "source": {"bytes": [1, 2, 3]}})).unwrap();
687        assert_eq!(block.source, AudioSource::Bytes(bytes()));
688    }
689
690    #[test]
691    fn image_block_from_json_accepts_base64_string_for_bytes() {
692        let block: ImageBlock = serde_json::from_value(json!({"format": "png", "source": {"bytes": "AQID"}})).unwrap();
693        assert_eq!(block.source, ImageSource::Bytes(bytes()));
694    }
695
696    #[test]
697    fn image_block_from_json_accepts_uint8_array_for_bytes() {
698        let block: ImageBlock =
699            serde_json::from_value(json!({"format": "png", "source": {"bytes": [1, 2, 3]}})).unwrap();
700        assert_eq!(block.source, ImageSource::Bytes(bytes()));
701    }
702
703    #[test]
704    fn video_block_from_json_accepts_base64_string_for_bytes() {
705        let block: VideoBlock = serde_json::from_value(json!({"format": "mp4", "source": {"bytes": "AQID"}})).unwrap();
706        assert_eq!(block.source, VideoSource::Bytes(bytes()));
707    }
708
709    #[test]
710    fn video_block_from_json_accepts_uint8_array_for_bytes() {
711        let block: VideoBlock =
712            serde_json::from_value(json!({"format": "mp4", "source": {"bytes": [1, 2, 3]}})).unwrap();
713        assert_eq!(block.source, VideoSource::Bytes(bytes()));
714    }
715
716    #[test]
717    fn document_block_from_json_accepts_base64_string_for_bytes() {
718        let block: DocumentBlock =
719            serde_json::from_value(json!({"name": "d", "format": "pdf", "source": {"bytes": "AQID"}})).unwrap();
720        assert_eq!(block.source, DocumentSource::Bytes(bytes()));
721    }
722
723    #[test]
724    fn document_block_from_json_accepts_uint8_array_for_bytes() {
725        let block: DocumentBlock =
726            serde_json::from_value(json!({"name": "d", "format": "pdf", "source": {"bytes": [1, 2, 3]}})).unwrap();
727        assert_eq!(block.source, DocumentSource::Bytes(bytes()));
728    }
729
730    #[test]
731    fn s3_location_round_trips_with_uri_only() {
732        round_trip(&S3Location::new("s3://bucket/key"));
733    }
734
735    #[test]
736    fn s3_location_round_trips_with_uri_and_bucket_owner() {
737        round_trip(&S3Location::new("s3://bucket/key").with_bucket_owner("123456789012"));
738    }
739
740    #[test]
741    fn includes_type_in_json_output() {
742        assert_eq!(
743            serde_json::to_string(&S3Location::new("s3://bucket/key")).unwrap(),
744            r#"{"type":"s3","uri":"s3://bucket/key"}"#
745        );
746    }
747
748    #[test]
749    fn audio_block_round_trips_with_bytes_source() {
750        round_trip(&AudioBlock::new(AudioFormat::Flac, AudioSource::Bytes(bytes())));
751    }
752
753    #[test]
754    fn audio_block_round_trips_with_s3_location_source() {
755        round_trip(&AudioBlock::new(
756            AudioFormat::XAac,
757            AudioSource::Location(S3Location::new("s3://b/a")),
758        ));
759    }
760
761    #[test]
762    fn audio_block_encodes_bytes_as_base64_in_json_output() {
763        let json = serde_json::to_value(AudioBlock::new(AudioFormat::Mp3, AudioSource::Bytes(bytes()))).unwrap();
764        assert!(json["source"]["bytes"].is_string());
765    }
766
767    #[test]
768    fn image_block_round_trips_with_bytes_source() {
769        round_trip(&ImageBlock::new(ImageFormat::Gif, ImageSource::Bytes(bytes())));
770    }
771
772    #[test]
773    fn image_block_round_trips_with_url_source() {
774        round_trip(&ImageBlock::new(
775            ImageFormat::Jpg,
776            ImageSource::Url("https://example.com/a.jpg".into()),
777        ));
778    }
779
780    #[test]
781    fn image_block_round_trips_with_s3_location_source() {
782        round_trip(&ImageBlock::new(
783            ImageFormat::Png,
784            ImageSource::Location(S3Location::new("s3://b/i")),
785        ));
786    }
787
788    #[test]
789    fn image_block_encodes_bytes_as_base64_in_json_output() {
790        let json = serde_json::to_value(ImageBlock::new(ImageFormat::Png, ImageSource::Bytes(bytes()))).unwrap();
791        assert_eq!(json["source"]["bytes"], "AQID");
792    }
793
794    #[test]
795    fn video_block_round_trips_with_bytes_source() {
796        round_trip(&VideoBlock::new(VideoFormat::Mov, VideoSource::Bytes(bytes())));
797    }
798
799    #[test]
800    fn video_block_round_trips_with_s3_location_source() {
801        round_trip(&VideoBlock::new(
802            VideoFormat::Mkv,
803            VideoSource::Location(S3Location::new("s3://b/v")),
804        ));
805    }
806
807    #[test]
808    fn video_block_encodes_bytes_as_base64_in_json_output() {
809        let json = serde_json::to_value(VideoBlock::new(VideoFormat::Mp4, VideoSource::Bytes(bytes()))).unwrap();
810        assert_eq!(json["source"]["bytes"], "AQID");
811    }
812
813    #[test]
814    fn document_block_round_trips_with_bytes_source() {
815        round_trip(&DocumentBlock::new(
816            "d",
817            DocumentFormat::Pdf,
818            DocumentSource::Bytes(bytes()),
819        ));
820    }
821
822    #[test]
823    fn document_block_round_trips_with_text_source() {
824        round_trip(&DocumentBlock::new(
825            "d",
826            DocumentFormat::Md,
827            DocumentSource::Text("# hi".into()),
828        ));
829    }
830
831    #[test]
832    fn document_block_round_trips_with_content_source() {
833        let source = DocumentSource::Content(vec![TextBlock::new("a")]);
834        round_trip(&DocumentBlock::new("d", DocumentFormat::Txt, source));
835    }
836
837    #[test]
838    fn document_block_round_trips_with_s3_location_source() {
839        let source = DocumentSource::Location(S3Location::new("s3://b/d"));
840        round_trip(&DocumentBlock::new("d", DocumentFormat::Csv, source));
841    }
842
843    #[test]
844    fn document_block_round_trips_with_citations_and_context() {
845        let block = DocumentBlock::new("d", DocumentFormat::Pdf, DocumentSource::Bytes(bytes()))
846            .with_citations(DocumentCitations::new(true))
847            .with_context("ctx");
848        round_trip(&block);
849    }
850
851    #[test]
852    fn omits_undefined_citations_and_context_from_json() {
853        let json = serde_json::to_value(DocumentBlock::new(
854            "d",
855            DocumentFormat::Pdf,
856            DocumentSource::Text("x".into()),
857        ))
858        .unwrap();
859        assert!(json.get("citations").is_none());
860        assert!(json.get("context").is_none());
861    }
862
863    fn assert_wire<T: Serialize + for<'de> Deserialize<'de> + PartialEq + std::fmt::Debug>(cases: &[(T, &str)]) {
864        for (format, wire) in cases {
865            assert_eq!(serde_json::to_value(format).unwrap(), json!(wire));
866            assert_eq!(&serde_json::from_value::<T>(json!(wire)).unwrap(), format);
867        }
868    }
869
870    #[test]
871    fn every_media_format_round_trips_through_its_wire_string() {
872        use AudioFormat as A;
873        use DocumentFormat as D;
874        use ImageFormat as I;
875        use VideoFormat as V;
876        assert_wire(&[
877            (A::Mp3, "mp3"),
878            (A::Opus, "opus"),
879            (A::Wav, "wav"),
880            (A::Aac, "aac"),
881            (A::Flac, "flac"),
882            (A::Mp4, "mp4"),
883            (A::Ogg, "ogg"),
884            (A::Mkv, "mkv"),
885            (A::Mka, "mka"),
886            (A::XAac, "x-aac"),
887            (A::M4a, "m4a"),
888            (A::Mpeg, "mpeg"),
889            (A::Mpga, "mpga"),
890            (A::Pcm, "pcm"),
891            (A::Webm, "webm"),
892        ]);
893        assert_wire(&[
894            (I::Png, "png"),
895            (I::Jpg, "jpg"),
896            (I::Jpeg, "jpeg"),
897            (I::Gif, "gif"),
898            (I::Webp, "webp"),
899        ]);
900        assert_wire(&[
901            (V::Mkv, "mkv"),
902            (V::Mov, "mov"),
903            (V::Mp4, "mp4"),
904            (V::Webm, "webm"),
905            (V::Flv, "flv"),
906            (V::Mpeg, "mpeg"),
907            (V::Mpg, "mpg"),
908            (V::Wmv, "wmv"),
909            (V::ThreeGp, "3gp"),
910        ]);
911        assert_wire(&[
912            (D::Pdf, "pdf"),
913            (D::Csv, "csv"),
914            (D::Doc, "doc"),
915            (D::Docx, "docx"),
916            (D::Xls, "xls"),
917            (D::Xlsx, "xlsx"),
918            (D::Html, "html"),
919            (D::Txt, "txt"),
920            (D::Md, "md"),
921            (D::Json, "json"),
922            (D::Xml, "xml"),
923        ]);
924    }
925
926    #[test]
927    fn base64_decoding_is_as_lenient_as_node_buffer() {
928        let cases = [
929            ("AQID", vec![1, 2, 3]),
930            ("AQI", vec![1, 2]),
931            ("AQI=", vec![1, 2]),
932            ("-_8", vec![251, 255]),
933            ("+/8=", vec![251, 255]),
934            ("AQ ID\nBA==", vec![1, 2, 3, 4]),
935            ("", Vec::new()),
936        ];
937        for (text, expected) in cases {
938            assert_eq!(base64_bytes::decode(text).unwrap(), expected, "{text:?}");
939        }
940        assert_eq!(base64_bytes::encode(&[251, 255]), "+/8=");
941    }
942
943    #[test]
944    fn base64_rejects_characters_outside_both_alphabets() {
945        let error = serde_json::from_value::<ImageSource>(json!({"bytes": "A*B"})).unwrap_err();
946        assert!(error.to_string().starts_with("invalid base64 bytes"));
947    }
948}