domainstack 1.1.1

Write validation once, use everywhere: Rust rules auto-generate JSON Schema + OpenAPI + TypeScript/Zod. WASM browser validation. Axum/Actix/Rocket adapters.
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
# JSON Schema Generation

**Auto-generate JSON Schema (Draft 2020-12) from validation rules**

Generate JSON Schema automatically from your validation rules, enabling frontend validation, API gateway validation, and cross-language schema sharing.

## Three Approaches

| Approach | Use Case | Requires |
|----------|----------|----------|
| **Derive Macro** | Compile-time schema generation with type safety | `domainstack-derive` with `schema` feature |
| **Trait** | Manual implementation for complex schemas | `domainstack-schema` |
| **CLI** | Build-time codegen from source files | `domainstack-cli` |

## Table of Contents

- [Quick Start]#quick-start
- [Installation]#installation
- [Why Auto-Derivation]#why-auto-derivation
- [Rule Mapping Reference]#rule-mapping-reference
- [Nested Types]#nested-types
- [Collections and Arrays]#collections-and-arrays
- [Optional Fields]#optional-fields
- [Custom Validators]#custom-validators
- [Schema Hints]#schema-hints
- [Advanced Usage]#advanced-usage
- [Trait Implementation]#trait-implementation
- [CLI Alternative]#cli-alternative

## Quick Start

```rust
use domainstack::prelude::*;
use domainstack_derive::{Validate, ToJsonSchema};
use domainstack_schema::JsonSchemaBuilder;

// Write validation rules ONCE, get BOTH runtime validation AND JSON Schema!
#[derive(Validate, ToJsonSchema)]
struct User {
    #[validate(email)]
    #[validate(max_len = 255)]
    email: String,

    #[validate(range(min = 18, max = 120))]
    age: u8,
}

// Runtime validation works
let user = User { email, age };
user.validate()?;  // Validates email format, length, age range

// Schema generation works
let schema = User::json_schema();
// Automatically includes:
//   - email: format="email", maxLength=255
//   - age: minimum=18, maximum=120
//   - required=["email", "age"]

// Build complete JSON Schema document
let doc = JsonSchemaBuilder::new()
    .title("My API Schema")
    .register::<User>()
    .build();

let json = serde_json::to_string_pretty(&doc)?;
```

## Installation

Add the required dependencies to your `Cargo.toml`:

```toml
[dependencies]
domainstack = "1.0"
domainstack-derive = { version = "1.0", features = ["schema"] }
domainstack-schema = "1.0"
serde_json = "1.0"  # For serializing schemas
```

The `schema` feature in `domainstack-derive` enables the `#[derive(ToJsonSchema)]` macro.

## Why Auto-Derivation

**The Problem:** Without auto-derivation, you write validation constraints twice—once for runtime validation, once for JSON Schema. This creates duplication, drift, and maintenance burden.

**The Solution:** With `#[derive(Validate, ToJsonSchema)]`, you write validation rules **once** and get **both** runtime validation AND JSON Schema:

```rust
#[derive(Validate, ToJsonSchema)]
struct CreateUser {
    #[validate(email)]
    #[validate(max_len = 255)]
    email: String,

    #[validate(range(min = 18, max = 120))]
    age: u8,

    #[validate(min_len = 2)]
    #[validate(max_len = 50)]
    name: String,
}

// Runtime validation works automatically
let user = CreateUser::new(email, age, name)?;  // Validates all rules

// Schema generation works automatically
let schema = CreateUser::json_schema();  // Includes all constraints
```

**Generated JSON Schema:**
```json
{
  "type": "object",
  "title": "CreateUser",
  "required": ["email", "age", "name"],
  "properties": {
    "email": {
      "type": "string",
      "format": "email",
      "maxLength": 255
    },
    "age": {
      "type": "integer",
      "minimum": 18,
      "maximum": 120
    },
    "name": {
      "type": "string",
      "minLength": 2,
      "maxLength": 50
    }
  },
  "additionalProperties": false
}
```

**Benefits:**
- Write validation rules **once**
- Schema **always matches** validation
- Less boilerplate
- Single source of truth
- Impossible for docs to drift from validation

## Rule Mapping Reference

The derive macro automatically maps validation rules to JSON Schema constraints:

### String Rules

| Validation Rule | JSON Schema Constraint | Example |
|----------------|------------------------|---------|
| `email()` | `format: "email"` | `#[validate(email)]` → `"format": "email"` |
| `url()` | `format: "uri"` | `#[validate(url)]` → `"format": "uri"` |
| `min_len(n)` | `minLength: n` | `#[validate(min_len = 3)]` → `"minLength": 3` |
| `max_len(n)` | `maxLength: n` | `#[validate(max_len = 255)]` → `"maxLength": 255` |
| `length(min, max)` | `minLength, maxLength` | `#[validate(length(min = 3, max = 20))]` → both |
| `non_empty` | `minLength: 1` | Ensures non-empty string |
| `non_blank` | `minLength: 1, pattern` | Non-whitespace start |
| `matches_regex(p)` | `pattern: p` | `#[validate(matches_regex = "^[A-Z].*")]` → `"pattern": "^[A-Z].*"` |
| `ascii()` | `pattern: "^[\\x00-\\x7F]*$"` | ASCII characters only |
| `alphanumeric()` | `pattern: "^[a-zA-Z0-9]*$"` | Letters and digits only |
| `alpha_only()` | `pattern: "^[a-zA-Z]*$"` | Letters only |
| `numeric_string()` | `pattern: "^[0-9]*$"` | Digits only |
| `no_whitespace` | `pattern: "^\\S*$"` | No whitespace |
| `starts_with(s)` | `pattern: "^prefix.*"` | Prefix pattern |
| `ends_with(s)` | `pattern: ".*suffix$"` | Suffix pattern |
| `contains(s)` | `pattern: ".*needle.*"` | Contains pattern |

### Numeric Rules

| Validation Rule | JSON Schema Constraint | Example |
|----------------|------------------------|---------|
| `min(n)` | `minimum: n` | `#[validate(min = 0)]` → `"minimum": 0` |
| `max(n)` | `maximum: n` | `#[validate(max = 100)]` → `"maximum": 100` |
| `range(min, max)` | `minimum, maximum` | `#[validate(range(min = 18, max = 120))]` → both |
| `positive()` | `exclusiveMinimum: 0` | Greater than zero |
| `negative()` | `exclusiveMaximum: 0` | Less than zero |
| `non_zero()` | `not: {const: 0}` | Not equal to zero |
| `multiple_of(n)` | `multipleOf: n` | `#[validate(multiple_of = 5)]` → `"multipleOf": 5` |

### Collection Rules

| Validation Rule | JSON Schema Constraint | Example |
|----------------|------------------------|---------|
| `min_items(n)` | `minItems: n` | `#[validate(min_items = 1)]` → `"minItems": 1` |
| `max_items(n)` | `maxItems: n` | `#[validate(max_items = 10)]` → `"maxItems": 10` |
| `unique()` | `uniqueItems: true` | All array items must be unique |

## Nested Types

Nested validation automatically includes referenced schemas:

```rust
#[derive(Validate, ToJsonSchema)]
struct Email {
    #[validate(email)]
    #[validate(max_len = 255)]
    value: String,
}

#[derive(Validate, ToJsonSchema)]
struct Guest {
    #[validate(min_len = 2)]
    #[validate(max_len = 50)]
    name: String,

    #[validate(nested)]  // Automatically references Email schema
    email: Email,
}
```

**Generated schema:**
```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$defs": {
    "Guest": {
      "type": "object",
      "title": "Guest",
      "required": ["name", "email"],
      "properties": {
        "name": {
          "type": "string",
          "minLength": 2,
          "maxLength": 50
        },
        "email": {
          "$ref": "#/$defs/Email"
        }
      },
      "additionalProperties": false
    },
    "Email": {
      "type": "object",
      "title": "Email",
      "required": ["value"],
      "properties": {
        "value": {
          "type": "string",
          "format": "email",
          "maxLength": 255
        }
      },
      "additionalProperties": false
    }
  }
}
```

## Collections and Arrays

### Nested Collections with `each(nested)`

Array validation for nested types using `#[validate(each(nested))]`:

```rust
#[derive(Validate, ToJsonSchema)]
struct Team {
    #[validate(min_len = 1, max_len = 50)]
    team_name: String,

    #[validate(each(nested))]
    #[validate(min_items = 1)]
    #[validate(max_items = 10)]
    members: Vec<User>,
}
```

**Generated schema:**
```json
{
  "Team": {
    "type": "object",
    "required": ["team_name", "members"],
    "properties": {
      "team_name": {
        "type": "string",
        "minLength": 1,
        "maxLength": 50
      },
      "members": {
        "type": "array",
        "items": {
          "$ref": "#/$defs/User"
        },
        "minItems": 1,
        "maxItems": 10
      }
    }
  }
}
```

### Primitive Collections with `each(rule)`

Any validation rule can be used with `each()` to validate items in collections:

```rust
#[derive(Validate, ToJsonSchema)]
struct BlogPost {
    // Validate each email in the list
    #[validate(each(email))]
    #[validate(min_items = 1, max_items = 5)]
    author_emails: Vec<String>,

    // Validate each tag's length
    #[validate(each(length(min = 1, max = 50)))]
    tags: Vec<String>,

    // Validate each rating is in range
    #[validate(each(range(min = 1, max = 5)))]
    ratings: Vec<u8>,
}
```

## Optional Fields

Optional fields (using `Option<T>`) are not included in the `required` array:

```rust
#[derive(Validate, ToJsonSchema)]
struct UpdateUser {
    #[validate(email)]
    #[validate(max_len = 255)]
    email: Option<String>,  // Optional, not in "required"

    #[validate(range(min = 18, max = 120))]
    age: Option<u8>,
}
```

**Generated schema:**
```json
{
  "UpdateUser": {
    "type": "object",
    "properties": {
      "email": {
        "type": "string",
        "format": "email",
        "maxLength": 255
      },
      "age": {
        "type": "integer",
        "minimum": 18,
        "maximum": 120
      }
    }
  }
}
```

Note: `email` and `age` are **not** in the `required` array.

## Custom Validators

For custom validation functions, use `#[schema(...)]` hints:

```rust
fn validate_strong_password(value: &str) -> Result<(), ValidationError> {
    // Complex password validation logic
}

#[derive(Validate, ToJsonSchema)]
struct UserAccount {
    #[validate(custom = "validate_strong_password")]
    #[schema(
        description = "Must contain uppercase, lowercase, digit, and special character",
        pattern = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}$",
        min_length = 8
    )]
    password: String,
}
```

**Why hints are needed:**
Custom validators contain arbitrary logic that can't be automatically converted to JSON Schema constraints. Use `#[schema(...)]` to manually specify the constraints for documentation.

## Schema Hints

The `#[schema(...)]` attribute provides additional metadata:

### Available Attributes

```rust
#[derive(Validate, ToJsonSchema)]
struct Product {
    #[validate(min_len = 1, max_len = 100)]
    #[schema(
        description = "Product name",
        example = "Acme Widget"
    )]
    name: String,

    #[validate(range(min = 0, max = 1000000))]
    #[schema(
        description = "Price in cents",
        default = 0
    )]
    price: i32,
}
```

## Advanced Usage

### Building Complete Schema Documents

```rust
use domainstack_schema::{JsonSchemaBuilder, ToJsonSchema};

#[derive(Validate, ToJsonSchema)]
struct User {
    #[validate(email, max_len = 255)]
    email: String,

    #[validate(range(min = 18, max = 120))]
    age: u8,
}

#[derive(Validate, ToJsonSchema)]
struct Order {
    #[validate(positive)]
    total: f64,

    #[validate(nested)]
    customer: User,
}

// Generate complete JSON Schema document
let doc = JsonSchemaBuilder::new()
    .title("My API Schema")
    .description("Auto-generated from validation rules")
    .register::<User>()
    .register::<Order>()
    .build();

// Export as JSON
let json = serde_json::to_string_pretty(&doc)?;
```

### Using with Frontend Validation (Ajv)

```typescript
import Ajv from 'ajv';
import schema from './schema.json';

const ajv = new Ajv();
const validate = ajv.getSchema('#/$defs/UserRegistration');

const valid = validate(formData);
if (!valid) {
  console.log(validate.errors);
}
```

### Using with Python Validation

```python
from jsonschema import validate
import json

with open('schema.json') as f:
    schema = json.load(f)

user_schema = schema['$defs']['User']
validate(instance=user_data, schema=user_schema)
```

## Trait Implementation

For complex schemas or types that can't use the derive macro, implement `ToJsonSchema` manually:

```rust
use domainstack_schema::{JsonSchema, JsonSchemaBuilder, ToJsonSchema};

struct PaymentMethod {
    method_type: String,
    card_number: Option<String>,
    bank_account: Option<String>,
}

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

    fn json_schema() -> JsonSchema {
        JsonSchema::object()
            .title("PaymentMethod")
            .description("Payment method with conditional fields")
            .property("method_type", JsonSchema::string()
                .enum_values(&["card", "bank", "cash"]))
            .property("card_number", JsonSchema::string()
                .min_length(13)
                .max_length(19)
                .pattern("^[0-9]+$"))
            .property("bank_account", JsonSchema::string()
                .pattern("^[A-Z]{2}[0-9]{2}[A-Z0-9]+$"))
            .required(&["method_type"])
    }
}

// Register in schema document
let doc = JsonSchemaBuilder::new()
    .title("Payment API")
    .register::<PaymentMethod>()
    .build();
```

**When to use manual implementation:**
- Complex conditional schemas (oneOf, anyOf, allOf)
- Schemas with custom vendor extensions
- Types from external crates without derive support
- Dynamic schema generation

## CLI Alternative

For build-time codegen without implementing traits, use `domainstack-cli`:

```bash
# Generate JSON Schema from Rust source files
domainstack json-schema --input src --output schema.json

# With verbose output
domainstack json-schema --input src --output schema.json --verbose

# Watch mode for development
domainstack json-schema --input src --output schema.json --watch
```

The CLI parses `#[validate(...)]` attributes from source files and generates JSON Schema without requiring trait implementations.

## Type Mappings

### Primitive Types

| Rust Type | JSON Schema Type | Notes |
|-----------|-----------------|-------|
| `String` | `"type": "string"` | |
| `bool` | `"type": "boolean"` | |
| `u8`, `u16`, `u32`, `i8`, `i16`, `i32` | `"type": "integer"` | Safe integer range |
| `u64`, `u128`, `i64`, `i128` | `"type": "integer"` | May exceed JS safe integer |
| `f32`, `f64` | `"type": "number"` | Floating point |

### Compound Types

| Rust Type | JSON Schema Type | Notes |
|-----------|-----------------|-------|
| `Option<T>` | Same as `T` | Field not in `required` array |
| `Vec<T>` | `"type": "array", "items": {...}` | Array with item schema |
| Custom struct | `"$ref": "#/$defs/TypeName"` | Reference to definition |

## Limitations

Some validation rules don't map directly to JSON Schema:

1. **Cross-field validation** - Cannot express field dependencies
2. **Conditional validation** - `.when()` clauses not mapped
3. **Async validation** - Database checks have no JSON Schema equivalent

For these cases, use vendor extensions:
```rust
#[schema(x_validation = "end_date > start_date")]
```

## See Also

- [OpenAPI Schema]OPENAPI_SCHEMA.md - OpenAPI 3.0 schema generation
- [CLI Guide]CLI_GUIDE.md - Full CLI documentation
- [RULES.md]RULES.md - Complete validation rules reference