vld-app 0.9.0

Application-edge integrations for the vld validation library: config files (config-rs, figment), environment variables and .env files, clap arguments, Tauri IPC
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
//! # `vld_app::tauri` — Tauri IPC validation for `vld`
//!
//! Validate [Tauri](https://tauri.app/) IPC commands, events, state, plugin
//! config and channel messages with `vld` schemas.
//!
//! No dependency on `tauri`: the crate only needs `vld`, `serde` and
//! `serde_json`; add `tauri` to your app separately.
//!
//! | Item | Use |
//! |------|-----|
//! | [`validate`] | Validate a `serde_json::Value` (commands, events, state, config, channel messages) |
//! | [`validate_args`] | Parse and validate a raw JSON string |
//! | [`VldTauriError`] | Serializable error for `#[tauri::command]` results |
//! | [`VldPayload<T>`] | `Deserialize` wrapper that validates |
//! | [`VldEvent<T>`] | Type alias of [`VldPayload<T>`] for event payloads |
//!
//! Issue paths have no leading dot (`name`, `user.email`, `items[0]`).
//!
//! Guide: <https://s00d.github.io/vld/integrations/ui/tauri>
//!
//! # Usage patterns
//!
//! ## IPC commands — explicit validation (recommended)
//!
//! Accept `serde_json::Value` and validate manually.
//! The frontend receives structured error JSON on failure.
//!
//! ```rust,ignore
//! use vld_app::tauri::prelude::*;
//!
//! vld::schema! {
//!     #[derive(Debug, Clone, serde::Serialize)]
//!     pub struct CreateUser {
//!         pub name: String  => vld::string().min(2).max(50),
//!         pub email: String => vld::string().email(),
//!     }
//! }
//!
//! #[tauri::command]
//! fn create_user(payload: serde_json::Value) -> Result<String, VldTauriError> {
//!     let user = validate::<CreateUser>(payload)?;
//!     Ok(format!("Created {}", user.name))
//! }
//! ```
//!
//! ## IPC commands — auto-validated payload
//!
//! `VldPayload<T>` implements `Deserialize` and validates during
//! deserialization. If validation fails, Tauri reports an argument
//! deserialization error carrying the validation message as a string (not a
//! structured [`VldTauriError`]).
//!
//! ```rust,ignore
//! #[tauri::command]
//! fn create_user(payload: VldPayload<CreateUser>) -> Result<String, VldTauriError> {
//!     Ok(format!("Created {}", payload.name))
//! }
//! ```
//!
//! ## Event payloads
//!
//! Validate data from `emit()`/`listen()`:
//!
//! ```rust,ignore
//! use tauri::{Emitter, Listener};
//!
//! // Backend: validate incoming event from frontend
//! app.listen("user:update", |event| {
//!     let payload: serde_json::Value = serde_json::from_str(event.payload()).unwrap();
//!     match validate::<UserUpdate>(payload) {
//!         Ok(update) => println!("Valid update: {:?}", update),
//!         Err(e)     => eprintln!("Bad event: {e}"),
//!     }
//! });
//!
//! // Or validate while deserializing (VldEvent<T> is VldPayload<T>):
//! let event: VldEvent<UserUpdate> = serde_json::from_str(event.payload()).unwrap();
//! ```
//!
//! ## State validation at init
//!
//! ```rust,ignore
//! let config_json = std::fs::read_to_string("config.json").unwrap();
//! let config = validate::<AppConfig>(
//!     serde_json::from_str(&config_json).unwrap()
//! ).expect("Invalid app config");
//! app.manage(config);
//! ```
//!
//! ## Plugin config validation
//!
//! ```rust,ignore
//! let plugin_cfg: serde_json::Value = /* from tauri.conf.json */;
//! let cfg = validate::<MyPluginConfig>(plugin_cfg)
//!     .expect("Invalid plugin config");
//! ```
//!
//! ## Channel message validation
//!
//! ```rust,ignore
//! #[tauri::command]
//! fn stream(channel: Channel<serde_json::Value>) -> Result<(), VldTauriError> {
//!     let msg = ProgressUpdate { percent: 50, status: "working".into() };
//!     let validated = validate::<ProgressUpdate>(
//!         serde_json::to_value(&msg).unwrap()
//!     )?;
//!     channel.send(serde_json::to_value(&validated).unwrap()).unwrap();
//!     Ok(())
//! }
//! ```
//!
//! # Frontend usage (TypeScript)
//!
//! ```javascript,ignore
//! import { invoke } from '@tauri-apps/api/core';
//!
//! interface VldError {
//!   error: string;
//!   issues: Array<{
//!     path: string;
//!     message: string;
//!     code: string;                    // "too_small", "invalid_type", a rule key, …
//!     params: Record<string, string>;  // { minimum: "2", origin: "string", … }
//!   }>;
//! }
//!
//! try {
//!   const result = await invoke('create_user', {
//!     payload: { name: 'Alice', email: 'alice@example.com' }
//!   });
//! } catch (err) {
//!   const vldErr = err as VldError;
//!   for (const issue of vldErr.issues) {
//!     // vue-i18n: messages like `vld: { too_small: "At least {minimum}" }`
//!     console.error(`${issue.path}: ${t(`vld.${issue.code}`, issue.params)}`);
//!   }
//! }
//! ```

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};
use vld::schema::VldParse;

// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------

/// Single validation issue, serialised for the frontend.
///
/// `code` and `params` are what a frontend i18n library needs to render its
/// own message: with vue-i18n, `t(`vld.${issue.code}`, issue.params)` and a
/// `vld.too_small` message such as `"At least {minimum}"`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TauriIssue {
    /// Path of the failing field, e.g. `name`, `user.email`, `items[0]`.
    pub path: String,
    /// Human-readable error message.
    pub message: String,
    /// Issue code ([`IssueCode::key`](vld::error::IssueCode::key)):
    /// `too_small`, `invalid_type`, a rule key, …; `invalid_json` / `custom`
    /// for errors not produced by a schema.
    #[serde(default)]
    pub code: String,
    /// Template parameters of the code
    /// ([`IssueCode::params`](vld::error::IssueCode::params)): `minimum`,
    /// `origin`, `expected`, …
    #[serde(default)]
    pub params: BTreeMap<String, String>,
}

impl TauriIssue {
    fn plain(code: &str, message: String) -> Self {
        Self {
            path: String::new(),
            message,
            code: code.into(),
            params: BTreeMap::new(),
        }
    }
}

/// Serializable error type for Tauri IPC commands, events, and channel
/// messages.
///
/// Tauri requires command error types to implement `Serialize`.
/// `VldTauriError` serialises as:
///
/// ```json
/// {
///   "error": "Validation failed",
///   "issues": [
///     {
///       "path": "name",
///       "message": "String must be at least 2 characters",
///       "code": "too_small",
///       "params": { "inclusive": "true", "minimum": "2", "origin": "string" }
///     }
///   ]
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VldTauriError {
    /// Error category string (e.g. `"Validation failed"`, `"Invalid JSON"`).
    pub error: String,
    /// List of individual validation issues.
    pub issues: Vec<TauriIssue>,
}

impl VldTauriError {
    /// Create from a [`VldError`](vld::error::VldError).
    pub fn from_vld(e: &vld::error::VldError) -> Self {
        let issues = e
            .issues
            .iter()
            .map(|i| TauriIssue {
                path: vld::error::format_path(&i.path),
                message: i.message.clone(),
                code: i.code.key().to_string(),
                params: i
                    .code
                    .params()
                    .into_iter()
                    .map(|(k, v)| (k.to_string(), v))
                    .collect(),
            })
            .collect();
        Self {
            error: "Validation failed".into(),
            issues,
        }
    }

    /// Build a JSON-parse error.
    pub fn json_parse_error(msg: impl std::fmt::Display) -> Self {
        Self {
            error: "Invalid JSON".into(),
            issues: vec![TauriIssue::plain("invalid_json", msg.to_string())],
        }
    }

    /// Build a generic error with a custom category.
    pub fn custom(error: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            error: error.into(),
            issues: vec![TauriIssue::plain("custom", message.into())],
        }
    }

    /// `true` if the error contains any issues.
    pub fn has_issues(&self) -> bool {
        !self.issues.is_empty()
    }

    /// Number of issues.
    pub fn issue_count(&self) -> usize {
        self.issues.len()
    }
}

impl std::fmt::Display for VldTauriError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {} issue(s)", self.error, self.issues.len())
    }
}

impl std::error::Error for VldTauriError {}

impl From<vld::error::VldError> for VldTauriError {
    fn from(e: vld::error::VldError) -> Self {
        Self::from_vld(&e)
    }
}

// ---------------------------------------------------------------------------
// Core validate function
// ---------------------------------------------------------------------------

/// Validate a `serde_json::Value` against a `vld` schema.
///
/// General-purpose entry-point used by all specialised helpers.
///
/// # Example
///
/// ```rust
/// use vld_app::tauri::validate;
///
/// vld::schema! {
///     #[derive(Debug)]
///     struct Greet {
///         name: String => vld::string().min(1),
///     }
/// }
///
/// let val = serde_json::json!({"name": "Alice"});
/// let g = validate::<Greet>(val).unwrap();
/// assert_eq!(g.name, "Alice");
/// ```
pub fn validate<T: VldParse>(value: serde_json::Value) -> Result<T, VldTauriError> {
    T::vld_parse_value(&value).map_err(VldTauriError::from)
}

/// Validate a raw JSON string against a `vld` schema.
///
/// Convenience wrapper — parses the string first, then validates.
///
/// # Example
///
/// ```rust
/// use vld_app::tauri::validate_args;
///
/// vld::schema! {
///     #[derive(Debug)]
///     struct Ping {
///         msg: String => vld::string().min(1),
///     }
/// }
///
/// let p = validate_args::<Ping>(r#"{"msg":"pong"}"#).unwrap();
/// assert_eq!(p.msg, "pong");
/// ```
pub fn validate_args<T: VldParse>(json_str: &str) -> Result<T, VldTauriError> {
    let value: serde_json::Value =
        serde_json::from_str(json_str).map_err(VldTauriError::json_parse_error)?;
    validate(value)
}

// ---------------------------------------------------------------------------
// VldPayload<T> — auto-validating wrapper for command args
// ---------------------------------------------------------------------------

/// Auto-validating wrapper for Tauri **command parameters**.
///
/// Implements [`Deserialize`] — on deserialization the incoming JSON is
/// validated through `T::vld_parse_value()`. If validation fails,
/// deserialization returns a `serde::de::Error` with the full message.
///
/// Implements [`Deref`](std::ops::Deref) to `T` so fields are accessible
/// directly.
///
/// # Example
///
/// ```rust,ignore
/// #[tauri::command]
/// fn greet(payload: VldPayload<GreetArgs>) -> Result<String, VldTauriError> {
///     Ok(format!("Hello, {}!", payload.name))
/// }
/// ```
pub struct VldPayload<T>(pub T);

impl<T> std::ops::Deref for VldPayload<T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.0
    }
}

impl<T> std::ops::DerefMut for VldPayload<T> {
    fn deref_mut(&mut self) -> &mut T {
        &mut self.0
    }
}

impl<T: std::fmt::Debug> std::fmt::Debug for VldPayload<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("VldPayload").field(&self.0).finish()
    }
}

impl<T: Clone> Clone for VldPayload<T> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<'de, T: VldParse> Deserialize<'de> for VldPayload<T> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = serde_json::Value::deserialize(deserializer)?;
        T::vld_parse_value(&value).map(VldPayload).map_err(|e| {
            let msg = format_vld_error_inline(&e);
            serde::de::Error::custom(msg)
        })
    }
}

// ---------------------------------------------------------------------------
// VldEvent<T> — auto-validating wrapper for event payloads
// ---------------------------------------------------------------------------

/// Auto-validating wrapper for Tauri **event payloads** — the same type as
/// [`VldPayload<T>`], named for data received via `Listener::listen()`.
///
/// Since 0.5 this is a type alias: construct / match it as `VldPayload(x)`.
///
/// # Example
///
/// ```rust,ignore
/// app.listen("settings:changed", |event| {
///     if let Ok(s) = serde_json::from_str::<VldEvent<Settings>>(event.payload()) {
///         println!("New settings: {:?}", s.0);
///     }
/// });
/// ```
pub type VldEvent<T> = VldPayload<T>;

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

fn format_vld_error_inline(e: &vld::error::VldError) -> String {
    let issues: Vec<String> = vld::error::flatten_issues(e)
        .into_iter()
        .map(|(path, message)| {
            if path.is_empty() {
                message
            } else {
                format!("{path}: {message}")
            }
        })
        .collect();
    format!("Validation failed: {}", issues.join("; "))
}

// ---------------------------------------------------------------------------
// Prelude
// ---------------------------------------------------------------------------

/// Prelude — import everything you need.
pub mod prelude {
    pub use super::{TauriIssue, VldEvent, VldPayload, VldTauriError, validate, validate_args};
    pub use vld::prelude::*;
}