atproto-lexicon 0.14.5

AT Protocol lexicon resolution and validation
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
//! Schema type definitions for ATProtocol lexicons
//!
//! This module defines all the schema types used in ATProtocol lexicons.
//! See: <https://atproto.com/specs/lexicon>

use indexmap::IndexMap;
use serde::{Deserialize, Serialize};

/// A schema definition - the main entry point for lexicon types
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum SchemaDef {
    /// Record schema (main type for stored records)
    Record(RecordSchema),
    /// Query schema (HTTP GET endpoint)
    Query(QuerySchema),
    /// Procedure schema (HTTP POST endpoint)
    Procedure(ProcedureSchema),
    /// Subscription schema (WebSocket stream)
    Subscription(SubscriptionSchema),
    /// Permission set
    #[serde(rename = "permission-set")]
    PermissionSet(PermissionSetSchema),
    /// Boolean type
    Boolean(BooleanSchema),
    /// Integer type
    Integer(IntegerSchema),
    /// String type
    String(StringSchema),
    /// Bytes type (base64 encoded)
    Bytes(BytesSchema),
    /// CID link type
    #[serde(rename = "cid-link")]
    CidLink(CidLinkSchema),
    /// Array type
    Array(ArraySchema),
    /// Object type
    Object(ObjectSchema),
    /// Blob type (file reference)
    Blob(BlobSchema),
    /// Params type (query parameters)
    Params(ParamsSchema),
    /// Reference to another type
    Ref(RefSchema),
    /// Union of types
    Union(UnionSchema),
    /// Unknown type (accepts any value)
    Unknown(UnknownSchema),
    /// Token type (constant string)
    Token(TokenSchema),
}

impl SchemaDef {
    /// Get the type name
    pub fn type_name(&self) -> &'static str {
        match self {
            SchemaDef::Record(_) => "record",
            SchemaDef::Query(_) => "query",
            SchemaDef::Procedure(_) => "procedure",
            SchemaDef::Subscription(_) => "subscription",
            SchemaDef::PermissionSet(_) => "permission-set",
            SchemaDef::Boolean(_) => "boolean",
            SchemaDef::Integer(_) => "integer",
            SchemaDef::String(_) => "string",
            SchemaDef::Bytes(_) => "bytes",
            SchemaDef::CidLink(_) => "cid-link",
            SchemaDef::Array(_) => "array",
            SchemaDef::Object(_) => "object",
            SchemaDef::Blob(_) => "blob",
            SchemaDef::Params(_) => "params",
            SchemaDef::Ref(_) => "ref",
            SchemaDef::Union(_) => "union",
            SchemaDef::Unknown(_) => "unknown",
            SchemaDef::Token(_) => "token",
        }
    }

    /// Check if this is a primary type (record, query, procedure, subscription)
    pub fn is_primary(&self) -> bool {
        matches!(
            self,
            SchemaDef::Record(_)
                | SchemaDef::Query(_)
                | SchemaDef::Procedure(_)
                | SchemaDef::Subscription(_)
                | SchemaDef::PermissionSet(_)
        )
    }

    /// Expand local refs (like `#link`) to full refs (like `nsid#link`)
    ///
    /// This is used when retrieving schemas from the catalog to ensure
    /// local refs can be resolved in any context.
    pub fn expand_local_refs(&mut self, nsid: &str) {
        match self {
            SchemaDef::Record(r) => {
                r.record.expand_local_refs(nsid);
            }
            SchemaDef::Query(q) => {
                if let Some(params) = &mut q.parameters {
                    params.expand_local_refs(nsid);
                }
                if let Some(output) = &mut q.output
                    && let Some(schema) = &mut output.schema
                {
                    schema.expand_local_refs(nsid);
                }
            }
            SchemaDef::Procedure(p) => {
                if let Some(params) = &mut p.parameters {
                    params.expand_local_refs(nsid);
                }
                if let Some(input) = &mut p.input
                    && let Some(schema) = &mut input.schema
                {
                    schema.expand_local_refs(nsid);
                }
                if let Some(output) = &mut p.output
                    && let Some(schema) = &mut output.schema
                {
                    schema.expand_local_refs(nsid);
                }
            }
            SchemaDef::Subscription(s) => {
                if let Some(params) = &mut s.parameters {
                    params.expand_local_refs(nsid);
                }
                if let Some(message) = &mut s.message {
                    message.schema.expand_local_refs(nsid);
                }
            }
            SchemaDef::Array(a) => {
                a.items.expand_local_refs(nsid);
            }
            SchemaDef::Object(o) => {
                for prop in o.properties.values_mut() {
                    prop.expand_local_refs(nsid);
                }
            }
            SchemaDef::Params(p) => {
                for prop in p.properties.values_mut() {
                    prop.expand_local_refs(nsid);
                }
            }
            SchemaDef::Ref(r) => {
                if r.ref_path.starts_with('#') {
                    r.ref_path = format!("{}{}", nsid, r.ref_path);
                }
            }
            SchemaDef::Union(u) => {
                for ref_path in &mut u.refs {
                    if ref_path.starts_with('#') {
                        *ref_path = format!("{}{}", nsid, ref_path);
                    }
                }
            }
            // These types don't contain refs
            SchemaDef::PermissionSet(_)
            | SchemaDef::Boolean(_)
            | SchemaDef::Integer(_)
            | SchemaDef::String(_)
            | SchemaDef::Bytes(_)
            | SchemaDef::CidLink(_)
            | SchemaDef::Blob(_)
            | SchemaDef::Unknown(_)
            | SchemaDef::Token(_) => {}
        }
    }
}

/// Record schema - stored data type
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RecordSchema {
    /// Description of the record
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Key for the record (e.g., "tid", "any", "literal:self")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub key: Option<String>,

    /// The record structure
    pub record: Box<SchemaDef>,
}

/// Query schema - HTTP GET endpoint
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct QuerySchema {
    /// Description of the query
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Query parameters
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parameters: Option<Box<SchemaDef>>,

    /// Output type
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output: Option<OutputSchema>,

    /// Possible errors
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub errors: Vec<ErrorSchema>,
}

/// Procedure schema - HTTP POST endpoint
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct ProcedureSchema {
    /// Description of the procedure
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Query parameters
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parameters: Option<Box<SchemaDef>>,

    /// Input body
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input: Option<InputSchema>,

    /// Output type
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output: Option<OutputSchema>,

    /// Possible errors
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub errors: Vec<ErrorSchema>,
}

/// Subscription schema - WebSocket stream
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct SubscriptionSchema {
    /// Description of the subscription
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Query parameters
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parameters: Option<Box<SchemaDef>>,

    /// Message types
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<MessageSchema>,

    /// Possible errors
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub errors: Vec<ErrorSchema>,
}

/// Permission set schema - defines OAuth permission groupings
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct PermissionSetSchema {
    /// Human-readable title for the permission grouping (required)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,

    /// Descriptive text shown during OAuth flow (spec field name)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,

    /// Descriptive text (alternative to detail, for compatibility)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Localization map for title (language code -> translated title)
    #[serde(
        rename = "title:lang",
        default,
        skip_serializing_if = "IndexMap::is_empty"
    )]
    pub title_lang: IndexMap<String, String>,

    /// Localization map for detail (language code -> translated detail)
    #[serde(
        rename = "detail:lang",
        default,
        skip_serializing_if = "IndexMap::is_empty"
    )]
    pub detail_lang: IndexMap<String, String>,

    /// Array of permission objects
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub permissions: Vec<Permission>,
}

impl PermissionSetSchema {
    /// Get the detail/description text (prefers detail over description)
    pub fn get_detail(&self) -> Option<&str> {
        self.detail.as_deref().or(self.description.as_deref())
    }
}

/// A single permission entry in a permission set
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Permission {
    /// Type field - must be "permission"
    #[serde(rename = "type")]
    pub type_field: String,

    /// Resource type: "repo", "rpc", "blob", "identity", or "account"
    pub resource: String,

    /// Actions for repo resources (e.g., ["create", "update", "delete"])
    #[serde(skip_serializing_if = "Option::is_none")]
    pub action: Option<Vec<String>>,

    /// Collection NSIDs for repo resources
    #[serde(skip_serializing_if = "Option::is_none")]
    pub collection: Option<Vec<String>>,

    /// Lexicon method NSIDs for rpc resources
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lxm: Option<Vec<String>>,

    /// Whether to inherit audience for rpc resources
    #[serde(rename = "inheritAud", skip_serializing_if = "Option::is_none")]
    pub inherit_aud: Option<bool>,
}

/// Valid resource types for permissions
pub const PERMISSION_RESOURCES: &[&str] = &["repo", "rpc", "blob", "identity", "account"];

/// Valid actions for repo permissions
pub const REPO_ACTIONS: &[&str] = &["create", "update", "delete"];

/// Input schema for procedures
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct InputSchema {
    /// Content encoding (e.g., "application/json")
    pub encoding: String,

    /// The schema for the input
    #[serde(skip_serializing_if = "Option::is_none")]
    pub schema: Option<Box<SchemaDef>>,

    /// Description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// Output schema for queries and procedures
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OutputSchema {
    /// Content encoding (e.g., "application/json")
    pub encoding: String,

    /// The schema for the output
    #[serde(skip_serializing_if = "Option::is_none")]
    pub schema: Option<Box<SchemaDef>>,

    /// Description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// Message schema for subscriptions
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MessageSchema {
    /// Content encoding
    #[serde(skip_serializing_if = "Option::is_none")]
    pub encoding: Option<String>,

    /// The schema for the message
    pub schema: Box<SchemaDef>,

    /// Description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// Error schema
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ErrorSchema {
    /// Error name
    pub name: String,

    /// Error description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// Boolean schema
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct BooleanSchema {
    /// Description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Default value
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default: Option<bool>,

    /// Constant value
    #[serde(rename = "const", skip_serializing_if = "Option::is_none")]
    pub const_value: Option<bool>,
}

/// Integer schema
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct IntegerSchema {
    /// Description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Default value
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default: Option<i64>,

    /// Constant value
    #[serde(rename = "const", skip_serializing_if = "Option::is_none")]
    pub const_value: Option<i64>,

    /// Minimum value
    #[serde(skip_serializing_if = "Option::is_none")]
    pub minimum: Option<i64>,

    /// Maximum value
    #[serde(skip_serializing_if = "Option::is_none")]
    pub maximum: Option<i64>,

    /// Enumerated values
    #[serde(rename = "enum", skip_serializing_if = "Option::is_none")]
    pub enum_values: Option<Vec<i64>>,
}

/// String schema
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct StringSchema {
    /// Description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Default value
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default: Option<String>,

    /// Constant value
    #[serde(rename = "const", skip_serializing_if = "Option::is_none")]
    pub const_value: Option<String>,

    /// Format (e.g., "datetime", "uri", "did")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub format: Option<String>,

    /// Minimum length
    #[serde(rename = "minLength", skip_serializing_if = "Option::is_none")]
    pub min_length: Option<usize>,

    /// Maximum length
    #[serde(rename = "maxLength", skip_serializing_if = "Option::is_none")]
    pub max_length: Option<usize>,

    /// Minimum grapheme length
    #[serde(rename = "minGraphemes", skip_serializing_if = "Option::is_none")]
    pub min_graphemes: Option<usize>,

    /// Maximum grapheme length
    #[serde(rename = "maxGraphemes", skip_serializing_if = "Option::is_none")]
    pub max_graphemes: Option<usize>,

    /// Enumerated values
    #[serde(rename = "enum", skip_serializing_if = "Option::is_none")]
    pub enum_values: Option<Vec<String>>,

    /// Known values (non-exhaustive enum)
    #[serde(rename = "knownValues", skip_serializing_if = "Option::is_none")]
    pub known_values: Option<Vec<String>>,
}

/// Bytes schema
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct BytesSchema {
    /// Description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Minimum length in bytes
    #[serde(rename = "minLength", skip_serializing_if = "Option::is_none")]
    pub min_length: Option<usize>,

    /// Maximum length in bytes
    #[serde(rename = "maxLength", skip_serializing_if = "Option::is_none")]
    pub max_length: Option<usize>,
}

/// CID link schema
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct CidLinkSchema {
    /// Description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// Array schema
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ArraySchema {
    /// Description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Item type
    pub items: Box<SchemaDef>,

    /// Minimum length
    #[serde(rename = "minLength", skip_serializing_if = "Option::is_none")]
    pub min_length: Option<usize>,

    /// Maximum length
    #[serde(rename = "maxLength", skip_serializing_if = "Option::is_none")]
    pub max_length: Option<usize>,
}

/// Object schema
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct ObjectSchema {
    /// Description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Required property names
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub required: Vec<String>,

    /// Nullable property names
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub nullable: Vec<String>,

    /// Property definitions
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub properties: IndexMap<String, SchemaDef>,
}

/// Blob schema
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct BlobSchema {
    /// Description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Accepted MIME types
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub accept: Vec<String>,

    /// Maximum size in bytes
    #[serde(rename = "maxSize", skip_serializing_if = "Option::is_none")]
    pub max_size: Option<u64>,
}

/// Params schema (query parameters)
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct ParamsSchema {
    /// Description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Required parameter names
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub required: Vec<String>,

    /// Parameter definitions
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub properties: IndexMap<String, SchemaDef>,
}

/// Reference schema
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RefSchema {
    /// Description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Reference path (e.g., "#defs/myType" or "com.example.lexicon#type")
    #[serde(rename = "ref")]
    pub ref_path: String,
}

/// Union schema
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UnionSchema {
    /// Description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// References to types in the union
    pub refs: Vec<String>,

    /// Whether the union is closed (default) or open
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub closed: bool,
}

/// Unknown schema (accepts any value)
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct UnknownSchema {
    /// Description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// Token schema (constant string type)
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct TokenSchema {
    /// Description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

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

    #[test]
    fn test_schema_def_type_names() {
        assert_eq!(
            SchemaDef::Boolean(BooleanSchema::default()).type_name(),
            "boolean"
        );
        assert_eq!(
            SchemaDef::Integer(IntegerSchema::default()).type_name(),
            "integer"
        );
        assert_eq!(
            SchemaDef::String(StringSchema::default()).type_name(),
            "string"
        );
    }

    #[test]
    fn test_schema_def_is_primary() {
        let record = SchemaDef::Record(RecordSchema {
            description: None,
            key: None,
            record: Box::new(SchemaDef::Object(ObjectSchema::default())),
        });
        assert!(record.is_primary());

        let boolean = SchemaDef::Boolean(BooleanSchema::default());
        assert!(!boolean.is_primary());
    }

    #[test]
    fn test_deserialize_boolean_schema() {
        let json = r#"{"type": "boolean", "default": true}"#;
        let schema: SchemaDef = serde_json::from_str(json).unwrap();
        if let SchemaDef::Boolean(b) = schema {
            assert_eq!(b.default, Some(true));
        } else {
            panic!("Expected Boolean schema");
        }
    }

    #[test]
    fn test_deserialize_string_schema() {
        let json = r#"{"type": "string", "format": "datetime", "minLength": 1, "maxLength": 100}"#;
        let schema: SchemaDef = serde_json::from_str(json).unwrap();
        if let SchemaDef::String(s) = schema {
            assert_eq!(s.format, Some("datetime".to_string()));
            assert_eq!(s.min_length, Some(1));
            assert_eq!(s.max_length, Some(100));
        } else {
            panic!("Expected String schema");
        }
    }

    #[test]
    fn test_deserialize_object_schema() {
        let json = r#"{
            "type": "object",
            "required": ["name"],
            "properties": {
                "name": {"type": "string"},
                "count": {"type": "integer"}
            }
        }"#;
        let schema: SchemaDef = serde_json::from_str(json).unwrap();
        if let SchemaDef::Object(o) = schema {
            assert_eq!(o.required, vec!["name"]);
            assert!(o.properties.contains_key("name"));
            assert!(o.properties.contains_key("count"));
        } else {
            panic!("Expected Object schema");
        }
    }

    #[test]
    fn test_deserialize_array_schema() {
        let json = r#"{
            "type": "array",
            "items": {"type": "string"},
            "minLength": 1,
            "maxLength": 10
        }"#;
        let schema: SchemaDef = serde_json::from_str(json).unwrap();
        if let SchemaDef::Array(a) = schema {
            assert_eq!(a.min_length, Some(1));
            assert_eq!(a.max_length, Some(10));
            assert!(matches!(*a.items, SchemaDef::String(_)));
        } else {
            panic!("Expected Array schema");
        }
    }

    #[test]
    fn test_deserialize_ref_schema() {
        let json = r##"{"type": "ref", "ref": "#defs/myType"}"##;
        let schema: SchemaDef = serde_json::from_str(json).unwrap();
        if let SchemaDef::Ref(r) = schema {
            assert_eq!(r.ref_path, "#defs/myType");
        } else {
            panic!("Expected Ref schema");
        }
    }

    #[test]
    fn test_deserialize_union_schema() {
        let json = r##"{
            "type": "union",
            "refs": ["#defs/typeA", "#defs/typeB"],
            "closed": true
        }"##;
        let schema: SchemaDef = serde_json::from_str(json).unwrap();
        if let SchemaDef::Union(u) = schema {
            assert_eq!(u.refs.len(), 2);
            assert!(u.closed);
        } else {
            panic!("Expected Union schema");
        }
    }

    #[test]
    fn test_deserialize_blob_schema() {
        let json = r#"{
            "type": "blob",
            "accept": ["image/png", "image/jpeg"],
            "maxSize": 1000000
        }"#;
        let schema: SchemaDef = serde_json::from_str(json).unwrap();
        if let SchemaDef::Blob(b) = schema {
            assert_eq!(b.accept, vec!["image/png", "image/jpeg"]);
            assert_eq!(b.max_size, Some(1000000));
        } else {
            panic!("Expected Blob schema");
        }
    }

    #[test]
    fn test_deserialize_cid_link_schema() {
        let json = r#"{"type": "cid-link"}"#;
        let schema: SchemaDef = serde_json::from_str(json).unwrap();
        assert!(matches!(schema, SchemaDef::CidLink(_)));
    }
}