domainstack-schema 1.0.0

OpenAPI schema generation for domainstack validation types
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
//! JSON Schema (Draft 2020-12) generation for domainstack validation types.
//!
//! This module provides a trait-based approach to JSON Schema generation,
//! complementing the CLI-based approach for cases where programmatic
//! schema generation is preferred.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// JSON Schema document (Draft 2020-12)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JsonSchema {
    #[serde(rename = "$schema", skip_serializing_if = "Option::is_none")]
    pub schema: Option<String>,

    #[serde(rename = "$id", skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,

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

    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub schema_type: Option<JsonSchemaType>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub format: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub properties: Option<HashMap<String, JsonSchema>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub required: Option<Vec<String>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub items: Option<Box<JsonSchema>>,

    #[serde(
        rename = "additionalProperties",
        skip_serializing_if = "Option::is_none"
    )]
    pub additional_properties: Option<AdditionalProperties>,

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

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

    #[serde(skip_serializing_if = "Option::is_none")]
    pub pattern: Option<String>,

    // Numeric constraints
    #[serde(skip_serializing_if = "Option::is_none")]
    pub minimum: Option<f64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub maximum: Option<f64>,

    #[serde(rename = "exclusiveMinimum", skip_serializing_if = "Option::is_none")]
    pub exclusive_minimum: Option<f64>,

    #[serde(rename = "exclusiveMaximum", skip_serializing_if = "Option::is_none")]
    pub exclusive_maximum: Option<f64>,

    #[serde(rename = "multipleOf", skip_serializing_if = "Option::is_none")]
    pub multiple_of: Option<f64>,

    // Array constraints
    #[serde(rename = "minItems", skip_serializing_if = "Option::is_none")]
    pub min_items: Option<usize>,

    #[serde(rename = "maxItems", skip_serializing_if = "Option::is_none")]
    pub max_items: Option<usize>,

    #[serde(rename = "uniqueItems", skip_serializing_if = "Option::is_none")]
    pub unique_items: Option<bool>,

    // Enum constraint
    #[serde(rename = "enum", skip_serializing_if = "Option::is_none")]
    pub r#enum: Option<Vec<serde_json::Value>>,

    #[serde(rename = "const", skip_serializing_if = "Option::is_none")]
    pub r#const: Option<serde_json::Value>,

    // Reference
    #[serde(rename = "$ref", skip_serializing_if = "Option::is_none")]
    pub reference: Option<String>,

    // Composition
    #[serde(rename = "anyOf", skip_serializing_if = "Option::is_none")]
    pub any_of: Option<Vec<JsonSchema>>,

    #[serde(rename = "allOf", skip_serializing_if = "Option::is_none")]
    pub all_of: Option<Vec<JsonSchema>>,

    #[serde(rename = "oneOf", skip_serializing_if = "Option::is_none")]
    pub one_of: Option<Vec<JsonSchema>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub not: Option<Box<JsonSchema>>,

    // Metadata
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default: Option<serde_json::Value>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub examples: Option<Vec<serde_json::Value>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub deprecated: Option<bool>,

    #[serde(rename = "readOnly", skip_serializing_if = "Option::is_none")]
    pub read_only: Option<bool>,

    #[serde(rename = "writeOnly", skip_serializing_if = "Option::is_none")]
    pub write_only: Option<bool>,

    // $defs for schema definitions
    #[serde(rename = "$defs", skip_serializing_if = "Option::is_none")]
    pub defs: Option<HashMap<String, JsonSchema>>,
}

/// JSON Schema types
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum JsonSchemaType {
    String,
    Number,
    Integer,
    Boolean,
    Array,
    Object,
    Null,
}

/// Additional properties can be a boolean or a schema
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum AdditionalProperties {
    Bool(bool),
    Schema(Box<JsonSchema>),
}

impl JsonSchema {
    /// Create a new empty schema
    pub fn new() -> Self {
        Self {
            schema: None,
            id: None,
            title: None,
            description: None,
            schema_type: None,
            format: None,
            properties: None,
            required: None,
            items: None,
            additional_properties: None,
            min_length: None,
            max_length: None,
            pattern: None,
            minimum: None,
            maximum: None,
            exclusive_minimum: None,
            exclusive_maximum: None,
            multiple_of: None,
            min_items: None,
            max_items: None,
            unique_items: None,
            r#enum: None,
            r#const: None,
            reference: None,
            any_of: None,
            all_of: None,
            one_of: None,
            not: None,
            default: None,
            examples: None,
            deprecated: None,
            read_only: None,
            write_only: None,
            defs: None,
        }
    }

    /// Create a string schema
    pub fn string() -> Self {
        Self {
            schema_type: Some(JsonSchemaType::String),
            ..Self::new()
        }
    }

    /// Create an integer schema
    pub fn integer() -> Self {
        Self {
            schema_type: Some(JsonSchemaType::Integer),
            ..Self::new()
        }
    }

    /// Create a number schema
    pub fn number() -> Self {
        Self {
            schema_type: Some(JsonSchemaType::Number),
            ..Self::new()
        }
    }

    /// Create a boolean schema
    pub fn boolean() -> Self {
        Self {
            schema_type: Some(JsonSchemaType::Boolean),
            ..Self::new()
        }
    }

    /// Create an array schema
    pub fn array(items: JsonSchema) -> Self {
        Self {
            schema_type: Some(JsonSchemaType::Array),
            items: Some(Box::new(items)),
            ..Self::new()
        }
    }

    /// Create an object schema
    pub fn object() -> Self {
        Self {
            schema_type: Some(JsonSchemaType::Object),
            properties: Some(HashMap::new()),
            additional_properties: Some(AdditionalProperties::Bool(false)),
            ..Self::new()
        }
    }

    /// Create a null schema
    pub fn null() -> Self {
        Self {
            schema_type: Some(JsonSchemaType::Null),
            ..Self::new()
        }
    }

    /// Create a reference to another schema
    pub fn reference(name: &str) -> Self {
        Self {
            reference: Some(format!("#/$defs/{}", name)),
            ..Self::new()
        }
    }

    /// Set the title
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Set the description
    pub fn description(mut self, desc: impl Into<String>) -> Self {
        self.description = Some(desc.into());
        self
    }

    /// Set the format
    pub fn format(mut self, format: impl Into<String>) -> Self {
        self.format = Some(format.into());
        self
    }

    /// Add a property to an object schema
    pub fn property(mut self, name: impl Into<String>, schema: JsonSchema) -> Self {
        self.properties
            .get_or_insert_with(HashMap::new)
            .insert(name.into(), schema);
        self
    }

    /// Set required fields
    pub fn required(mut self, fields: &[&str]) -> Self {
        self.required = Some(fields.iter().map(|s| s.to_string()).collect());
        self
    }

    /// Set minimum length for strings
    pub fn min_length(mut self, min: usize) -> Self {
        self.min_length = Some(min);
        self
    }

    /// Set maximum length for strings
    pub fn max_length(mut self, max: usize) -> Self {
        self.max_length = Some(max);
        self
    }

    /// Set regex pattern for strings
    pub fn pattern(mut self, pattern: impl Into<String>) -> Self {
        self.pattern = Some(pattern.into());
        self
    }

    /// Set minimum value for numbers
    pub fn minimum(mut self, min: impl Into<f64>) -> Self {
        self.minimum = Some(min.into());
        self
    }

    /// Set maximum value for numbers
    pub fn maximum(mut self, max: impl Into<f64>) -> Self {
        self.maximum = Some(max.into());
        self
    }

    /// Set exclusive minimum for numbers
    pub fn exclusive_minimum(mut self, min: impl Into<f64>) -> Self {
        self.exclusive_minimum = Some(min.into());
        self
    }

    /// Set exclusive maximum for numbers
    pub fn exclusive_maximum(mut self, max: impl Into<f64>) -> Self {
        self.exclusive_maximum = Some(max.into());
        self
    }

    /// Set multipleOf constraint for numbers
    pub fn multiple_of(mut self, divisor: impl Into<f64>) -> Self {
        self.multiple_of = Some(divisor.into());
        self
    }

    /// Set minimum items for arrays
    pub fn min_items(mut self, min: usize) -> Self {
        self.min_items = Some(min);
        self
    }

    /// Set maximum items for arrays
    pub fn max_items(mut self, max: usize) -> Self {
        self.max_items = Some(max);
        self
    }

    /// Set unique items constraint for arrays
    pub fn unique_items(mut self, unique: bool) -> Self {
        self.unique_items = Some(unique);
        self
    }

    /// Set enum values
    pub fn enum_values<T: Serialize>(mut self, values: &[T]) -> Self {
        self.r#enum = Some(
            values
                .iter()
                .map(|v| serde_json::to_value(v).expect("Failed to serialize enum value"))
                .collect(),
        );
        self
    }

    /// Set a const value
    pub fn const_value<T: Serialize>(mut self, value: T) -> Self {
        self.r#const = Some(serde_json::to_value(value).expect("Failed to serialize const value"));
        self
    }

    /// Set a default value
    pub fn default<T: Serialize>(mut self, value: T) -> Self {
        self.default =
            Some(serde_json::to_value(value).expect("Failed to serialize default value"));
        self
    }

    /// Set example values
    pub fn examples<T: Serialize>(mut self, values: Vec<T>) -> Self {
        self.examples = Some(
            values
                .into_iter()
                .map(|v| serde_json::to_value(v).expect("Failed to serialize example value"))
                .collect(),
        );
        self
    }

    /// Mark as deprecated
    pub fn deprecated(mut self, deprecated: bool) -> Self {
        self.deprecated = Some(deprecated);
        self
    }

    /// Mark as read-only
    pub fn read_only(mut self, read_only: bool) -> Self {
        self.read_only = Some(read_only);
        self
    }

    /// Mark as write-only
    pub fn write_only(mut self, write_only: bool) -> Self {
        self.write_only = Some(write_only);
        self
    }

    /// Create an anyOf schema
    pub fn any_of(schemas: Vec<JsonSchema>) -> Self {
        Self {
            any_of: Some(schemas),
            ..Self::new()
        }
    }

    /// Create an allOf schema
    pub fn all_of(schemas: Vec<JsonSchema>) -> Self {
        Self {
            all_of: Some(schemas),
            ..Self::new()
        }
    }

    /// Create a oneOf schema
    pub fn one_of(schemas: Vec<JsonSchema>) -> Self {
        Self {
            one_of: Some(schemas),
            ..Self::new()
        }
    }

    /// Create a negation schema (not)
    pub fn negation(schema: JsonSchema) -> Self {
        Self {
            not: Some(Box::new(schema)),
            ..Self::new()
        }
    }
}

impl Default for JsonSchema {
    fn default() -> Self {
        Self::new()
    }
}

/// Types that can generate JSON Schema (Draft 2020-12).
///
/// This trait provides programmatic JSON Schema generation as an alternative
/// to the CLI-based approach.
///
/// # Example
///
/// ```rust
/// use domainstack_schema::{ToJsonSchema, JsonSchema};
///
/// struct User {
///     email: String,
///     age: u8,
/// }
///
/// impl ToJsonSchema for User {
///     fn schema_name() -> &'static str {
///         "User"
///     }
///
///     fn json_schema() -> JsonSchema {
///         JsonSchema::object()
///             .property("email", JsonSchema::string().format("email"))
///             .property("age", JsonSchema::integer().minimum(0).maximum(150))
///             .required(&["email", "age"])
///     }
/// }
/// ```
pub trait ToJsonSchema {
    /// The name of this schema in the $defs section.
    fn schema_name() -> &'static str;

    /// Generate the JSON Schema for this type.
    fn json_schema() -> JsonSchema;
}

// Implementations for primitive types
impl ToJsonSchema for String {
    fn schema_name() -> &'static str {
        "string"
    }

    fn json_schema() -> JsonSchema {
        JsonSchema::string()
    }
}

impl ToJsonSchema for str {
    fn schema_name() -> &'static str {
        "string"
    }

    fn json_schema() -> JsonSchema {
        JsonSchema::string()
    }
}

impl ToJsonSchema for u8 {
    fn schema_name() -> &'static str {
        "integer"
    }

    fn json_schema() -> JsonSchema {
        JsonSchema::integer().minimum(0).maximum(255)
    }
}

impl ToJsonSchema for u16 {
    fn schema_name() -> &'static str {
        "integer"
    }

    fn json_schema() -> JsonSchema {
        JsonSchema::integer().minimum(0).maximum(65535)
    }
}

impl ToJsonSchema for u32 {
    fn schema_name() -> &'static str {
        "integer"
    }

    fn json_schema() -> JsonSchema {
        JsonSchema::integer().minimum(0)
    }
}

impl ToJsonSchema for i32 {
    fn schema_name() -> &'static str {
        "integer"
    }

    fn json_schema() -> JsonSchema {
        JsonSchema::integer()
    }
}

impl ToJsonSchema for i64 {
    fn schema_name() -> &'static str {
        "integer"
    }

    fn json_schema() -> JsonSchema {
        JsonSchema::integer()
    }
}

impl ToJsonSchema for f32 {
    fn schema_name() -> &'static str {
        "number"
    }

    fn json_schema() -> JsonSchema {
        JsonSchema::number()
    }
}

impl ToJsonSchema for f64 {
    fn schema_name() -> &'static str {
        "number"
    }

    fn json_schema() -> JsonSchema {
        JsonSchema::number()
    }
}

impl ToJsonSchema for bool {
    fn schema_name() -> &'static str {
        "boolean"
    }

    fn json_schema() -> JsonSchema {
        JsonSchema::boolean()
    }
}

impl<T: ToJsonSchema> ToJsonSchema for Vec<T> {
    fn schema_name() -> &'static str {
        "array"
    }

    fn json_schema() -> JsonSchema {
        JsonSchema::array(T::json_schema())
    }
}

impl<T: ToJsonSchema> ToJsonSchema for Option<T> {
    fn schema_name() -> &'static str {
        T::schema_name()
    }

    fn json_schema() -> JsonSchema {
        T::json_schema()
    }
}

/// Builder for creating JSON Schema documents with $defs
pub struct JsonSchemaBuilder {
    id: Option<String>,
    title: Option<String>,
    description: Option<String>,
    defs: HashMap<String, JsonSchema>,
}

impl JsonSchemaBuilder {
    /// Create a new JSON Schema builder
    pub fn new() -> Self {
        Self {
            id: None,
            title: None,
            description: None,
            defs: HashMap::new(),
        }
    }

    /// Set the $id
    pub fn id(mut self, id: impl Into<String>) -> Self {
        self.id = Some(id.into());
        self
    }

    /// Set the title
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Set the description
    pub fn description(mut self, desc: impl Into<String>) -> Self {
        self.description = Some(desc.into());
        self
    }

    /// Register a type that implements ToJsonSchema
    pub fn register<T: ToJsonSchema>(mut self) -> Self {
        self.defs
            .insert(T::schema_name().to_string(), T::json_schema());
        self
    }

    /// Add a schema with a custom name
    pub fn add_schema(mut self, name: impl Into<String>, schema: JsonSchema) -> Self {
        self.defs.insert(name.into(), schema);
        self
    }

    /// Build the final JSON Schema document
    pub fn build(self) -> JsonSchema {
        JsonSchema {
            schema: Some("https://json-schema.org/draft/2020-12/schema".to_string()),
            id: self.id,
            title: self.title,
            description: self.description,
            defs: if self.defs.is_empty() {
                None
            } else {
                Some(self.defs)
            },
            ..JsonSchema::new()
        }
    }

    /// Build and serialize to JSON string
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        let schema = JsonSchema {
            schema: Some("https://json-schema.org/draft/2020-12/schema".to_string()),
            id: self.id.clone(),
            title: self.title.clone(),
            description: self.description.clone(),
            defs: if self.defs.is_empty() {
                None
            } else {
                Some(self.defs.clone())
            },
            ..JsonSchema::new()
        };
        serde_json::to_string_pretty(&schema)
    }
}

impl Default for JsonSchemaBuilder {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_string_schema() {
        let schema = JsonSchema::string().min_length(3).max_length(50);
        assert!(matches!(schema.schema_type, Some(JsonSchemaType::String)));
        assert_eq!(schema.min_length, Some(3));
        assert_eq!(schema.max_length, Some(50));
    }

    #[test]
    fn test_integer_schema() {
        let schema = JsonSchema::integer().minimum(0).maximum(100);
        assert!(matches!(schema.schema_type, Some(JsonSchemaType::Integer)));
        assert_eq!(schema.minimum, Some(0.0));
        assert_eq!(schema.maximum, Some(100.0));
    }

    #[test]
    fn test_object_schema() {
        let schema = JsonSchema::object()
            .property("name", JsonSchema::string())
            .property("age", JsonSchema::integer())
            .required(&["name"]);

        assert!(matches!(schema.schema_type, Some(JsonSchemaType::Object)));
        assert_eq!(schema.properties.as_ref().unwrap().len(), 2);
        assert!(schema
            .required
            .as_ref()
            .unwrap()
            .contains(&"name".to_string()));
    }

    #[test]
    fn test_array_schema() {
        let schema = JsonSchema::array(JsonSchema::string())
            .min_items(1)
            .max_items(10);
        assert!(matches!(schema.schema_type, Some(JsonSchemaType::Array)));
        assert!(schema.items.is_some());
        assert_eq!(schema.min_items, Some(1));
    }

    #[test]
    fn test_reference() {
        let schema = JsonSchema::reference("User");
        assert_eq!(schema.reference, Some("#/$defs/User".to_string()));
    }

    #[test]
    fn test_any_of() {
        let schema = JsonSchema::any_of(vec![JsonSchema::string(), JsonSchema::integer()]);
        assert!(schema.any_of.is_some());
        assert_eq!(schema.any_of.as_ref().unwrap().len(), 2);
    }

    #[test]
    fn test_builder() {
        struct User;
        impl ToJsonSchema for User {
            fn schema_name() -> &'static str {
                "User"
            }

            fn json_schema() -> JsonSchema {
                JsonSchema::object()
                    .property("email", JsonSchema::string().format("email"))
                    .required(&["email"])
            }
        }

        let doc = JsonSchemaBuilder::new()
            .title("My Schema")
            .register::<User>()
            .build();

        assert!(doc.schema.is_some());
        assert_eq!(doc.title, Some("My Schema".to_string()));
        assert!(doc.defs.as_ref().unwrap().contains_key("User"));
    }

    #[test]
    fn test_serialization() {
        let schema = JsonSchema::object()
            .property("email", JsonSchema::string().format("email"))
            .property("age", JsonSchema::integer().minimum(0))
            .required(&["email", "age"]);

        let json = serde_json::to_string(&schema).unwrap();
        assert!(json.contains("\"type\":\"object\""));
        assert!(json.contains("\"email\""));
    }
}