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
# Installation Guide

**Complete guide to installing and configuring domainstack and its companion crates.**

## Table of Contents

- [Quick Start]#quick-start
- [Core Crate]#core-crate
- [Feature Flags]#feature-flags
- [Companion Crates]#companion-crates
- [Common Configurations]#common-configurations
- [Version Compatibility]#version-compatibility

## Quick Start

Add domainstack to your `Cargo.toml`:

```toml
[dependencies]
domainstack = { version = "1.0", features = ["derive", "regex"] }
```

**Recommended features:**
- `derive` - Enables `#[derive(Validate)]` macro
- `regex` - Enables email, URL, and pattern matching rules

## Core Crate

### Basic Installation

```toml
[dependencies]
# Minimal - only core validation primitives
domainstack = "1.0"

# Recommended - includes derive macro
domainstack = { version = "1.0", features = ["derive"] }

# Full-featured - all optional features
domainstack = { version = "1.0", features = ["derive", "regex", "async", "chrono", "serde"] }
```

### Version Requirements

- **Rust:** 1.70 or later (for advanced const generics)
- **Edition:** 2021 or later

## Feature Flags

The `domainstack` crate provides several optional features:

| Feature | Adds | Use When | Dependencies |
|---------|------|----------|--------------|
| `derive` | `#[derive(Validate)]` macro | Declarative validation (recommended) | `domainstack-derive` |
| `regex` | Email, URL, pattern matching | Web APIs, user input validation | `regex` |
| `async` | `AsyncValidate` trait | Database checks, external API validation | `async-trait` |
| `chrono` | Date/time validation rules | Temporal constraints, age verification | `chrono` |
| `serde` | `ValidateOnDeserialize` derive | Validate during JSON/YAML parsing | `serde` |

### Feature Details

#### `derive` - Derive Macro

Enables `#[derive(Validate)]` for declarative validation:

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

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

**Adds:**
- `#[derive(Validate)]` procedural macro
- `#[validate(...)]` field attributes

**When to use:** Almost always. Manual `impl Validate` is verbose.

#### `regex` - Pattern Matching

Enables rules that require regular expressions:

```rust
use domainstack::rules::*;

let email_rule = email();                        // Requires regex
let url_rule = url();                             // Requires regex
let pattern_rule = matches_regex(r"^[A-Z0-9]+$"); // Requires regex
```

**Adds:**
- `email()` - RFC 5322 email validation
- `url()` - URL format validation
- `matches_regex()` - Custom regex patterns
- `alphanumeric()` - Alphanumeric-only validation
- `alpha_only()` - Alphabetic-only validation
- `numeric_string()` - Numeric string validation

**When to use:** Web APIs, user input, any validation requiring pattern matching.

#### `async` - Async Validation

Enables `AsyncValidate` trait for I/O-based validation:

```rust
use domainstack::{AsyncValidate, ValidationContext};
use async_trait::async_trait;

#[async_trait]
impl AsyncValidate for User {
    async fn validate_async(&self, ctx: &ValidationContext) -> Result<(), ValidationError> {
        // Database uniqueness check
        let db = ctx.get_resource::<PgPool>("db")?;
        let exists = query!("SELECT id FROM users WHERE email = $1", self.email)
            .fetch_optional(db)
            .await?;

        if exists.is_some() {
            return Err(ValidationError::single("email", "taken", "Email already exists"));
        }

        Ok(())
    }
}
```

**Adds:**
- `AsyncValidate` trait
- `ValidationContext` for passing resources

**When to use:**
- Database uniqueness checks
- External API validation
- Rate limiting
- Real-time availability checks

**Dependencies:** `async-trait = "0.1"`

#### `chrono` - Date/Time Validation

Enables date and time validation rules:

```rust
use domainstack::rules::*;
use chrono::NaiveDate;

let booking_date = NaiveDate::from_ymd_opt(2025, 6, 15).unwrap();

let future_rule = future();                              // Must be in future
let past_rule = past();                                  // Must be in past
let before_rule = before(NaiveDate::from_ymd_opt(2026, 1, 1).unwrap());
let after_rule = after(NaiveDate::from_ymd_opt(2025, 1, 1).unwrap());
let age_rule = min_age(18);                              // Age verification
```

**Adds:**
- `future()` - Date must be in the future
- `past()` - Date must be in the past
- `before()` - Date must be before a specific date
- `after()` - Date must be after a specific date
- `min_age()` - Age verification from date of birth

**When to use:**
- Event scheduling (booking dates, deadlines)
- Age verification (birth dates)
- Historical data validation
- Temporal constraints

**Dependencies:** `chrono = "0.4"`

#### `serde` - Validate on Deserialize

Enables `ValidateOnDeserialize` derive macro:

```rust
use serde::Deserialize;
use domainstack::ValidateOnDeserialize;

#[derive(Deserialize, ValidateOnDeserialize)]
struct User {
    #[validate(email)]
    email: String,

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

// Validation happens automatically during deserialization
let user: User = serde_json::from_str(json)?;  // Validates!
```

**Adds:**
- `#[derive(ValidateOnDeserialize)]` macro
- Automatic validation during `serde` deserialization

**When to use:**
- API request handlers
- Configuration file parsing
- Any JSON/YAML/TOML deserialization

**Dependencies:** `serde = "1.0"`

## Companion Crates

### domainstack-schema - Schema Generation

Generate OpenAPI 3.0 and JSON Schema (Draft 2020-12) from validation rules:

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

**Usage - OpenAPI:**

```rust
use domainstack_derive::{Validate, ToSchema};

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

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

let schema = User::schema();
// Generates OpenAPI 3.0 schema with validation constraints
```

**Usage - JSON Schema:**

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

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

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

let doc = JsonSchemaBuilder::new()
    .title("My API")
    .register::<User>()
    .build();
// Generates JSON Schema (Draft 2020-12) with validation constraints
```

**Features:**
- Automatic schema generation from `#[validate(...)]` attributes
- Rule → schema constraint mapping (OpenAPI and JSON Schema)
- Nested type support with `$ref` references
- Collection and optional field handling

**See:**
- [OPENAPI_SCHEMA.md]OPENAPI_SCHEMA.md - OpenAPI generation guide
- [JSON_SCHEMA.md]JSON_SCHEMA.md - JSON Schema generation guide

### domainstack-envelope - HTTP Error Envelopes

Structured HTTP error responses:

```toml
[dependencies]
domainstack = { version = "1.0", features = ["derive"] }
domainstack-envelope = "1.0"
```

**Usage:**

```rust
use domainstack_envelope::IntoEnvelopeError;

async fn create_user(Json(dto): Json<UserDto>) -> Result<Json<User>, ErrorResponse> {
    let user = User::try_from(dto)
        .map_err(|e| e.into_envelope_error())?;  // Convert to structured error format
    Ok(Json(user))
}
```

**Produces:**

```json
{
  "code": "VALIDATION",
  "status": 400,
  "message": "Validation failed with 2 errors",
  "retryable": false,
  "details": {
    "fields": {
      "email": [{"code": "invalid_email", "message": "Invalid email format"}],
      "age": [{"code": "out_of_range", "message": "Must be between 18 and 120"}]
    }
  }
}
```

**See:** [HTTP_INTEGRATION.md](HTTP_INTEGRATION.md) for complete documentation

### domainstack-axum - Axum Integration

Axum 0.7+ extractors with automatic validation:

```toml
[dependencies]
domainstack = { version = "1.0", features = ["derive"] }
domainstack-axum = "1.0"
```

**Usage:**

```rust
use domainstack_axum::{DomainJson, ErrorResponse};

async fn create_user(
    DomainJson(dto, user): DomainJson<UserDto, User>
) -> Result<Json<User>, ErrorResponse> {
    // `user` is already validated via TryFrom<UserDto>
    Ok(Json(user))
}
```

**Features:**
- `DomainJson<Dto, Domain>` - Deserialize + validate + convert
- `ValidatedJson<T>` - Simple validation extractor
- Automatic error responses with field-level errors

**Requirements:** `axum = "0.7"`

**See:** [HTTP_INTEGRATION.md](HTTP_INTEGRATION.md) for complete documentation

### domainstack-actix - Actix-web Integration

Actix-web 4.x extractors with automatic validation:

```toml
[dependencies]
domainstack = { version = "1.0", features = ["derive"] }
domainstack-actix = "1.0"
```

**Usage:**

```rust
use domainstack_actix::{DomainJson, ErrorResponse};
use actix_web::{post, web::Json};

#[post("/users")]
async fn create_user(
    DomainJson(dto, user): DomainJson<UserDto, User>
) -> Result<Json<User>, ErrorResponse> {
    // `user` is already validated
    Ok(Json(user))
}
```

**Requirements:** `actix-web = "4"`

**See:** [HTTP_INTEGRATION.md](HTTP_INTEGRATION.md) for complete documentation

### domainstack-rocket - Rocket Integration

Rocket 0.5+ data guards with automatic validation:

```toml
[dependencies]
domainstack = { version = "1.0", features = ["derive"] }
domainstack-rocket = "1.0"
```

**Usage:**

```rust
use domainstack_rocket::{DomainJson, ErrorResponse};
use rocket::post;

#[post("/users", data = "<input>")]
async fn create_user(
    input: DomainJson<UserDto, User>
) -> Result<Json<User>, ErrorResponse> {
    // input.1 is the validated User
    Ok(Json(input.1))
}
```

**Requirements:** `rocket = "0.5"`

**See:** [HTTP_INTEGRATION.md](HTTP_INTEGRATION.md) for complete documentation

### domainstack-wasm - Browser Validation

Run the same validation logic in the browser via WebAssembly:

```toml
[dependencies]
domainstack = { version = "1.0", features = ["derive"] }
domainstack-wasm = "1.0"
```

**Build:**

```bash
rustup target add wasm32-unknown-unknown
wasm-pack build --target web --release
```

**Usage (JavaScript):**

```typescript
import init, { createValidator } from '@domainstack/wasm';

await init();
const validator = createValidator();

const result = validator.validate('User', JSON.stringify({ email: 'bad', age: 15 }));
if (!result.ok) {
  result.errors.forEach(e => console.log(`${e.path}: ${e.message}`));
}
```

**Features:**
- Same validation code runs in browser and server
- Zero drift between client/server validation
- ~60KB WASM bundle
- TypeScript types auto-generated

**See:** [WASM_VALIDATION.md](WASM_VALIDATION.md) for complete documentation

## Common Configurations

### Basic Web API

Most common setup for REST APIs:

```toml
[dependencies]
domainstack = { version = "1.0", features = ["derive", "regex"] }
domainstack-axum = "1.0"
```

**Use for:**
- REST APIs with JSON validation
- Email/URL validation
- Field-level error responses

### Full-Stack API with OpenAPI

Generate OpenAPI schemas + validation:

```toml
[dependencies]
domainstack = { version = "1.0", features = ["derive", "regex"] }
domainstack-schema = "1.0"
domainstack-axum = "1.0"
```

**Use for:**
- APIs with auto-generated OpenAPI docs
- Frontend integration with typed schemas
- Swagger UI / Redoc documentation

### API with Async Validation

Database uniqueness checks and external API validation:

```toml
[dependencies]
domainstack = { version = "1.0", features = ["derive", "regex", "async"] }
domainstack-axum = "1.0"
sqlx = { version = "0.7", features = ["postgres", "runtime-tokio"] }
```

**Use for:**
- User registration (email/username uniqueness)
- External API validation (VAT numbers, postal codes)
- Rate limiting checks

### Full-Featured Setup

All features enabled:

```toml
[dependencies]
domainstack = { version = "1.0", features = ["derive", "regex", "async", "chrono", "serde"] }
domainstack-schema = "1.0"
domainstack-envelope = "1.0"
domainstack-axum = "1.0"
```

**Use for:**
- Complex domain applications
- Multi-tenant systems
- Event scheduling with date validation
- Comprehensive API validation

### Minimal Setup

Core validation only (no derive macro):

```toml
[dependencies]
domainstack = "1.0"
```

**Use for:**
- Libraries (avoid macro dependencies)
- Manual `impl Validate` only
- Embedded systems (minimal dependencies)

## Version Compatibility

### domainstack

| Version | Rust | Features |
|---------|------|----------|
| 1.0.x   | 1.70+ | derive, regex, async, chrono, serde |

### Framework Adapters

| Crate | Framework Version | domainstack Version |
|-------|-------------------|---------------------|
| domainstack-axum | Axum 0.7+ | 1.0+ |
| domainstack-actix | Actix-web 4.x | 1.0+ |
| domainstack-rocket | Rocket 0.5+ | 1.0+ |

### Companion Crates

| Crate | domainstack Version |
|-------|---------------------|
| domainstack-schema | 1.0+ |
| domainstack-envelope | 1.0+ |
| domainstack-wasm | 1.0+ |

## See Also

- **[Quick Start]../README.md#quick-start** - Get started in 5 minutes
- **[Core Concepts]CORE_CONCEPTS.md** - Understanding domainstack fundamentals
- **[Derive Macro]DERIVE_MACRO.md** - Using `#[derive(Validate)]`
- **[HTTP Integration]HTTP_INTEGRATION.md** - Framework adapters guide
- **[OpenAPI Schema]OPENAPI_SCHEMA.md** - OpenAPI 3.0 schema generation
- **[JSON Schema]JSON_SCHEMA.md** - JSON Schema (Draft 2020-12) generation
- **[WASM Validation]WASM_VALIDATION.md** - Browser validation guide