quillmark-core 0.54.1

Core types and functionality for Quillmark
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
use std::collections::HashMap;

use time::format_description::well_known::Rfc3339;
use time::{Date, OffsetDateTime};

use crate::quill::formats::DATE_FORMAT;
use crate::quill::{CardSchema, FieldSchema, FieldType, QuillConfig};
use crate::value::QuillValue;

/// Validation error with a structured field path.
#[derive(Debug, Clone, thiserror::Error, PartialEq, Eq)]
pub enum ValidationError {
    #[error("missing required field `{path}`")]
    MissingRequired { path: String },

    #[error("field `{path}` has type `{actual}`, expected `{expected}`")]
    TypeMismatch {
        path: String,
        expected: String,
        actual: String,
    },

    #[error("field `{path}` value `{value}` not in allowed set {allowed:?}")]
    EnumViolation {
        path: String,
        value: String,
        allowed: Vec<String>,
    },

    #[error("field `{path}` does not match expected format `{format}`")]
    FormatViolation { path: String, format: String },

    #[error("unknown card type `{card}` at `{path}`")]
    UnknownCard { path: String, card: String },

    #[error("card at `{path}` missing `CARD` discriminator")]
    MissingCardDiscriminator { path: String },
}

/// Validate a parsed document against the full config.
///
/// Validates main fields, all card instances, and enforces required fields.
/// Collects all errors rather than short-circuiting on the first.
pub fn validate_document(
    config: &QuillConfig,
    fields: &HashMap<String, QuillValue>,
) -> Result<(), Vec<ValidationError>> {
    let mut errors = validate_fields_for_card(config.main(), fields, "");

    if let Some(cards_value) = fields.get("CARDS") {
        match cards_value.as_array() {
            Some(cards) => {
                for (index, card_value) in cards.iter().enumerate() {
                    let item_path = index_path("cards", index);
                    let Some(card_object) = card_value.as_object() else {
                        errors.push(ValidationError::TypeMismatch {
                            path: item_path,
                            expected: "object".to_string(),
                            actual: json_type_name(card_value).to_string(),
                        });
                        continue;
                    };

                    let Some(card_discriminator) = card_object.get("CARD") else {
                        errors.push(ValidationError::MissingCardDiscriminator { path: item_path });
                        continue;
                    };

                    let Some(card_name) = card_discriminator.as_str() else {
                        errors.push(ValidationError::TypeMismatch {
                            path: child_path(&item_path, "CARD"),
                            expected: "string".to_string(),
                            actual: json_type_name(card_discriminator).to_string(),
                        });
                        continue;
                    };

                    let Some(card_schema) = config.card_definition(card_name) else {
                        errors.push(ValidationError::UnknownCard {
                            path: item_path,
                            card: card_name.to_string(),
                        });
                        continue;
                    };

                    let mut card_fields = HashMap::new();
                    for (key, value) in card_object {
                        card_fields.insert(key.clone(), QuillValue::from_json(value.clone()));
                    }

                    let card_path = format!("cards.{card_name}[{index}]");
                    errors.extend(validate_fields_for_card(
                        card_schema,
                        &card_fields,
                        &card_path,
                    ));
                }
            }
            None => errors.push(ValidationError::TypeMismatch {
                path: "CARDS".to_string(),
                expected: "array".to_string(),
                actual: json_type_name(cards_value.as_json()).to_string(),
            }),
        }
    }

    if errors.is_empty() {
        Ok(())
    } else {
        Err(errors)
    }
}

fn validate_fields_for_card(
    card: &CardSchema,
    fields: &HashMap<String, QuillValue>,
    base_path: &str,
) -> Vec<ValidationError> {
    let mut errors = Vec::new();
    let mut field_names: Vec<&String> = card.fields.keys().collect();
    field_names.sort();

    for field_name in field_names {
        let schema = &card.fields[field_name];
        let path = child_path(base_path, field_name);
        match fields.get(field_name) {
            Some(value) => errors.extend(validate_field(schema, value, &path)),
            None if schema.required => errors.push(ValidationError::MissingRequired { path }),
            None => {}
        }
    }

    errors
}

/// Validate a single value against a field schema at the given path.
/// Used internally; exposed for testing.
pub(crate) fn validate_field(
    field: &FieldSchema,
    value: &QuillValue,
    path: &str,
) -> Vec<ValidationError> {
    let mut errors = Vec::new();

    let type_valid = match field.r#type {
        FieldType::String | FieldType::Markdown => value.as_str().is_some(),
        FieldType::Number => value.as_json().is_number(),
        FieldType::Boolean => value.as_bool().is_some(),
        FieldType::Date => {
            if value.as_json().is_null() {
                true
            } else {
                match value.as_str() {
                    Some(text) if text.is_empty() => true,
                    Some(text) => {
                        if is_valid_date(text) {
                            true
                        } else {
                            errors.push(ValidationError::FormatViolation {
                                path: path.to_string(),
                                format: "date".to_string(),
                            });
                            false
                        }
                    }
                    None => false,
                }
            }
        }
        FieldType::DateTime => {
            if value.as_json().is_null() {
                true
            } else {
                match value.as_str() {
                    Some(text) if text.is_empty() => true,
                    Some(text) => {
                        if is_valid_datetime(text) {
                            true
                        } else {
                            errors.push(ValidationError::FormatViolation {
                                path: path.to_string(),
                                format: "date-time".to_string(),
                            });
                            false
                        }
                    }
                    None => false,
                }
            }
        }
        FieldType::Array => match value.as_array() {
            Some(items) => {
                if let Some(item_schema) = &field.items {
                    for (idx, item) in items.iter().enumerate() {
                        errors.extend(validate_field(
                            item_schema,
                            &QuillValue::from_json(item.clone()),
                            &index_path(path, idx),
                        ));
                    }
                }
                true
            }
            None => false,
        },
        FieldType::Object => match value.as_object() {
            Some(object) => {
                if let Some(properties) = &field.properties {
                    let mut property_names: Vec<&String> = properties.keys().collect();
                    property_names.sort();
                    for property_name in property_names {
                        let property_schema = &properties[property_name];
                        let property_path = child_path(path, property_name);
                        match object.get(property_name) {
                            Some(property_value) => errors.extend(validate_field(
                                property_schema,
                                &QuillValue::from_json(property_value.clone()),
                                &property_path,
                            )),
                            None if property_schema.required => {
                                errors.push(ValidationError::MissingRequired {
                                    path: property_path,
                                })
                            }
                            None => {}
                        }
                    }
                }
                true
            }
            None => false,
        },
    };

    // A Date/DateTime with a string value already emitted a FormatViolation;
    // skip the redundant TypeMismatch in that case.
    let format_error_already_reported =
        matches!(field.r#type, FieldType::Date | FieldType::DateTime) && value.as_str().is_some();

    if !type_valid && !format_error_already_reported {
        errors.push(ValidationError::TypeMismatch {
            path: path.to_string(),
            expected: expected_type_name(&field.r#type).to_string(),
            actual: json_type_name(value.as_json()).to_string(),
        });
    }

    if type_valid {
        if let (Some(allowed), Some(actual)) = (&field.enum_values, value.as_str()) {
            if !allowed.contains(&actual.to_string()) {
                errors.push(ValidationError::EnumViolation {
                    path: path.to_string(),
                    value: actual.to_string(),
                    allowed: allowed.clone(),
                });
            }
        }
    }

    errors
}

fn is_valid_date(value: &str) -> bool {
    Date::parse(value, &DATE_FORMAT).is_ok()
}

fn is_valid_datetime(value: &str) -> bool {
    OffsetDateTime::parse(value, &Rfc3339).is_ok()
}

fn expected_type_name(field_type: &FieldType) -> &'static str {
    match field_type {
        FieldType::String | FieldType::Markdown | FieldType::Date | FieldType::DateTime => "string",
        FieldType::Number => "number",
        FieldType::Boolean => "boolean",
        FieldType::Array => "array",
        FieldType::Object => "object",
    }
}

fn json_type_name(value: &serde_json::Value) -> &'static str {
    match value {
        serde_json::Value::Null => "null",
        serde_json::Value::Bool(_) => "boolean",
        serde_json::Value::Number(_) => "number",
        serde_json::Value::String(_) => "string",
        serde_json::Value::Array(_) => "array",
        serde_json::Value::Object(_) => "object",
    }
}

fn child_path(parent: &str, child: &str) -> String {
    if parent.is_empty() {
        child.to_string()
    } else {
        format!("{parent}.{child}")
    }
}

fn index_path(parent: &str, index: usize) -> String {
    format!("{parent}[{index}]")
}

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

    fn config_with(main_fields: &str, cards: &str) -> QuillConfig {
        let yaml = format!(
            r#"
Quill:
  name: native_validation
  backend: typst
  description: Native validator tests
  version: 1.0.0
main:
  fields:
{main_fields}
{cards}
"#
        );
        // Use _with_warnings so silently-dropped fields (e.g. unsupported
        // standalone `type: object`) fail loudly instead of passing vacuously.
        let (config, warnings) = QuillConfig::from_yaml_with_warnings(&yaml).unwrap();
        assert!(
            warnings.is_empty(),
            "config_with produced warnings (test schema is unsupported): {:?}",
            warnings
        );
        config
    }

    fn fields(entries: &[(&str, serde_json::Value)]) -> HashMap<String, QuillValue> {
        entries
            .iter()
            .map(|(k, v)| (k.to_string(), QuillValue::from_json(v.clone())))
            .collect()
    }

    fn has_error<F>(errors: &[ValidationError], predicate: F) -> bool
    where
        F: Fn(&ValidationError) -> bool,
    {
        errors.iter().any(predicate)
    }

    #[test]
    fn validates_simple_string_field() {
        let config = config_with("    title:\n      type: string\n      required: true", "");
        let doc = fields(&[("title", json!("Memo"))]);
        assert!(validate_document(&config, &doc).is_ok());
    }

    #[test]
    fn rejects_simple_string_type_mismatch() {
        let config = config_with("    title:\n      type: string", "");
        let doc = fields(&[("title", json!(9))]);
        let errors = validate_document(&config, &doc).unwrap_err();
        assert!(has_error(&errors, |e| matches!(
            e,
            ValidationError::TypeMismatch { path, expected, actual }
            if path == "title" && expected == "string" && actual == "number"
        )));
    }

    #[test]
    fn reports_missing_required_field() {
        let config = config_with(
            "    memo_for:\n      type: string\n      required: true",
            "",
        );
        let errors = validate_document(&config, &HashMap::new()).unwrap_err();
        assert!(has_error(&errors, |e| {
            matches!(e, ValidationError::MissingRequired { path } if path == "memo_for")
        }));
    }

    #[test]
    fn reports_required_field_wrong_type() {
        let config = config_with(
            "    memo_for:\n      type: string\n      required: true",
            "",
        );
        let doc = fields(&[("memo_for", json!(true))]);
        let errors = validate_document(&config, &doc).unwrap_err();
        assert!(has_error(&errors, |e| matches!(
            e,
            ValidationError::TypeMismatch { path, .. } if path == "memo_for"
        )));
    }

    #[test]
    fn validates_enum_value() {
        let config = config_with(
            "    status:\n      type: string\n      enum:\n        - draft\n        - final",
            "",
        );
        let doc = fields(&[("status", json!("draft"))]);
        assert!(validate_document(&config, &doc).is_ok());
    }

    #[test]
    fn rejects_invalid_enum_value() {
        let config = config_with(
            "    status:\n      type: string\n      enum:\n        - draft\n        - final",
            "",
        );
        let doc = fields(&[("status", json!("invalid"))]);
        let errors = validate_document(&config, &doc).unwrap_err();
        assert!(has_error(&errors, |e| matches!(
            e,
            ValidationError::EnumViolation { path, value, .. }
            if path == "status" && value == "invalid"
        )));
    }

    #[test]
    fn validates_date_format() {
        let config = config_with("    signed_on:\n      type: date", "");
        let doc = fields(&[("signed_on", json!("2026-04-13"))]);
        assert!(validate_document(&config, &doc).is_ok());
    }

    #[test]
    fn rejects_invalid_date_format() {
        let config = config_with("    signed_on:\n      type: date", "");
        let doc = fields(&[("signed_on", json!("13-04-2026"))]);
        let errors = validate_document(&config, &doc).unwrap_err();
        assert!(has_error(&errors, |e| {
            matches!(e, ValidationError::FormatViolation { path, format } if path == "signed_on" && format == "date")
        }));
    }

    #[test]
    fn validates_datetime_format() {
        let config = config_with("    created_at:\n      type: datetime", "");
        let doc = fields(&[("created_at", json!("2026-04-13T19:24:55Z"))]);
        assert!(validate_document(&config, &doc).is_ok());
    }

    #[test]
    fn rejects_invalid_datetime_format() {
        let config = config_with("    created_at:\n      type: datetime", "");
        let doc = fields(&[("created_at", json!("2026-04-13 19:24:55"))]);
        let errors = validate_document(&config, &doc).unwrap_err();
        assert!(has_error(&errors, |e| matches!(
            e,
            ValidationError::FormatViolation { path, format }
            if path == "created_at" && format == "date-time"
        )));
    }

    #[test]
    fn markdown_accepts_any_string() {
        let config = config_with("    body:\n      type: markdown", "");
        let doc = fields(&[("body", json!("# Heading\n\nBody text"))]);
        assert!(validate_document(&config, &doc).is_ok());
    }

    #[test]
    fn validates_array_of_strings() {
        let config = config_with(
            "    tags:\n      type: array\n      items:\n        type: string",
            "",
        );
        let doc = fields(&[("tags", json!(["a", "b"]))]);
        assert!(validate_document(&config, &doc).is_ok());
    }

    #[test]
    fn rejects_invalid_array_element_type() {
        let config = config_with(
            "    tags:\n      type: array\n      items:\n        type: string",
            "",
        );
        let doc = fields(&[("tags", json!(["a", 2]))]);
        let errors = validate_document(&config, &doc).unwrap_err();
        assert!(has_error(&errors, |e| matches!(
            e,
            ValidationError::TypeMismatch { path, .. } if path == "tags[1]"
        )));
    }

    #[test]
    fn validates_array_of_objects() {
        let config = config_with(
            "    recipients:\n      type: array\n      items:\n        type: object\n        properties:\n          name:\n            type: string\n            required: true\n          org:\n            type: string",
            "",
        );
        let doc = fields(&[("recipients", json!([{ "name": "Sam", "org": "HQ" }]))]);
        assert!(validate_document(&config, &doc).is_ok());
    }

    #[test]
    fn reports_missing_required_field_in_array_object() {
        let config = config_with(
            "    recipients:\n      type: array\n      items:\n        type: object\n        properties:\n          name:\n            type: string\n            required: true\n          org:\n            type: string",
            "",
        );
        let doc = fields(&[("recipients", json!([{ "org": "HQ" }]))]);
        let errors = validate_document(&config, &doc).unwrap_err();
        assert!(has_error(&errors, |e| {
            matches!(e, ValidationError::MissingRequired { path } if path == "recipients[0].name")
        }));
    }

    // NOTE: top-level `type: object` fields are explicitly unsupported by
    // the config parser (see `config::parse_fields_with_order`). Object
    // schemas only appear inside `array.items`; coverage for that shape lives
    // in `validates_array_of_objects` and
    // `reports_missing_required_field_in_array_object`.

    #[test]
    fn reports_type_mismatch_for_cards_when_not_array() {
        let config = config_with(
            "    title:\n      type: string",
            "cards:\n  indorsement:\n    fields:\n      signature_block:\n        type: string",
        );
        let doc = fields(&[("CARDS", json!("not-an-array"))]);
        let errors = validate_document(&config, &doc).unwrap_err();
        assert!(has_error(&errors, |e| {
            matches!(
                e,
                ValidationError::TypeMismatch { path, expected, actual }
                if path == "CARDS" && expected == "array" && actual == "string"
            )
        }));
    }

    #[test]
    fn accumulates_multiple_missing_required_errors() {
        let config = config_with(
            "    memo_for:\n      type: string\n      required: true\n    memo_from:\n      type: string\n      required: true",
            "",
        );
        let errors = validate_document(&config, &HashMap::new()).unwrap_err();
        let missing_paths: Vec<&str> = errors
            .iter()
            .filter_map(|e| match e {
                ValidationError::MissingRequired { path } => Some(path.as_str()),
                _ => None,
            })
            .collect();
        assert!(missing_paths.contains(&"memo_for"));
        assert!(missing_paths.contains(&"memo_from"));
    }

    #[test]
    fn validates_card_with_valid_discriminator() {
        let config = config_with(
            "    title:\n      type: string",
            "cards:\n  indorsement:\n    fields:\n      signature_block:\n        type: string\n        required: true",
        );
        let doc = fields(&[(
            "CARDS",
            json!([{ "CARD": "indorsement", "signature_block": "Signed" }]),
        )]);
        assert!(validate_document(&config, &doc).is_ok());
    }

    #[test]
    fn rejects_unknown_card_discriminator() {
        let config = config_with(
            "    title:\n      type: string",
            "cards:\n  indorsement:\n    fields:\n      signature_block:\n        type: string",
        );
        let doc = fields(&[("CARDS", json!([{ "CARD": "unknown" }]))]);
        let errors = validate_document(&config, &doc).unwrap_err();
        assert!(has_error(&errors, |e| {
            matches!(e, ValidationError::UnknownCard { path, card } if path == "cards[0]" && card == "unknown")
        }));
    }

    #[test]
    fn reports_missing_card_discriminator() {
        let config = config_with(
            "    title:\n      type: string",
            "cards:\n  indorsement:\n    fields:\n      signature_block:\n        type: string",
        );
        let doc = fields(&[("CARDS", json!([{ "signature_block": "Signed" }]))]);
        let errors = validate_document(&config, &doc).unwrap_err();
        assert!(has_error(&errors, |e| {
            matches!(e, ValidationError::MissingCardDiscriminator { path } if path == "cards[0]")
        }));
    }

    #[test]
    fn validates_multiple_card_instances_same_type() {
        let config = config_with(
            "    title:\n      type: string",
            "cards:\n  indorsement:\n    fields:\n      signature_block:\n        type: string\n        required: true",
        );
        let doc = fields(&[(
            "CARDS",
            json!([
                { "CARD": "indorsement", "signature_block": "A" },
                { "CARD": "indorsement", "signature_block": "B" }
            ]),
        )]);
        assert!(validate_document(&config, &doc).is_ok());
    }

    #[test]
    fn validates_multiple_card_types_mixed() {
        let config = config_with(
            "    title:\n      type: string",
            "cards:\n  indorsement:\n    fields:\n      signature_block:\n        type: string\n        required: true\n  routing:\n    fields:\n      office:\n        type: string\n        required: true",
        );
        let doc = fields(&[(
            "CARDS",
            json!([
                { "CARD": "indorsement", "signature_block": "A" },
                { "CARD": "routing", "office": "HQ" }
            ]),
        )]);
        assert!(validate_document(&config, &doc).is_ok());
    }

    #[test]
    fn reports_card_field_paths_with_card_name_and_index() {
        let config = config_with(
            "    title:\n      type: string",
            "cards:\n  indorsement:\n    fields:\n      signature_block:\n        type: string\n        required: true",
        );
        let doc = fields(&[("CARDS", json!([{ "CARD": "indorsement" }]))]);
        let errors = validate_document(&config, &doc).unwrap_err();
        assert!(has_error(&errors, |e| {
            matches!(e, ValidationError::MissingRequired { path } if path == "cards.indorsement[0].signature_block")
        }));
    }
}