mik-sdk 0.1.2

Ergonomic macros for WASI HTTP handlers - ok!, error!, json!
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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
//! Typed input infrastructure for type-safe request handling.
//!
//! This module provides:
//! - [`Id`] - Built-in path parameter for single ID routes
//! - [`ParseError`] - Error type for parsing failures
//! - [`ValidationError`] - Error type for constraint validation
//! - Traits for parsing JSON, query strings, and path parameters
//!
//! # Newtypes and Validation
//!
//! This SDK provides structural types ([`Id`], derive macros) but intentionally
//! delegates field validation to external crates like `garde`.
//!
//! **Why?** Validation requirements vary widely between projects. Some need strict
//! email validation, others accept any string. By separating concerns:
//! - SDK handles parsing and type conversion
//! - Validation crates handle domain-specific rules
//!
//! # Example: ParseError and ValidationError
//!
//! ```
//! use mik_sdk::typed::{ParseError, ValidationError};
//!
//! // Create parse errors
//! let missing = ParseError::missing("email");
//! assert_eq!(missing.field(), "email");
//!
//! // Create validation errors
//! let too_short = ValidationError::min("name", 3);
//! assert_eq!(too_short.field(), "name");
//! assert_eq!(too_short.constraint(), "min");
//! ```

mod parse_error;
mod validation_error;

pub use parse_error::ParseError;
pub use validation_error::ValidationError;

use crate::json::JsonValue;
use std::collections::HashMap;

// ============================================================================
// BUILT-IN TYPES
// ============================================================================

/// Single path parameter type using String for JS compatibility.
///
/// Use this for simple routes with a single `{id}` parameter.
///
/// # Example
///
/// ```
/// # use mik_sdk::typed::Id;
/// let id = Id::new("user_123");
/// assert_eq!(id.as_str(), "user_123");
///
/// // Parse as integer if needed
/// let numeric_id = Id::new("42");
/// let parsed: i64 = numeric_id.parse().unwrap();
/// assert_eq!(parsed, 42);
///
/// // Get owned String if needed
/// let id = Id::new("user_456");
/// let inner: String = id.into_inner();
/// assert_eq!(inner, "user_456");
/// ```
///
/// # Why String?
///
/// JavaScript `Number` loses precision for integers > 2^53.
/// String IDs are safe for all ID formats:
/// - Numeric: `"123"`
/// - UUID: `"550e8400-e29b-41d4-a716-446655440000"`
/// - Prefixed: `"usr_abc123"`
/// - Snowflake/ULID: `"01ARZ3NDEKTSV4RRFFQ69G5FAV"`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Id(String);

impl Id {
    /// Create a new Id from a string.
    #[inline]
    pub fn new(s: impl Into<String>) -> Self {
        Self(s.into())
    }

    /// Get the inner string reference.
    #[inline]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consume the Id and return the inner String.
    ///
    /// Use this when you need ownership of the underlying string.
    ///
    /// # Example
    ///
    /// ```
    /// # use mik_sdk::typed::Id;
    /// let id = Id::new("user_123");
    /// let inner: String = id.into_inner();
    /// assert_eq!(inner, "user_123");
    /// ```
    #[inline]
    pub fn into_inner(self) -> String {
        self.0
    }

    /// Parse the ID as a specific type.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError::InvalidFormat`] if parsing fails.
    ///
    /// # Example
    ///
    /// ```
    /// # use mik_sdk::typed::Id;
    /// let id = Id::new("42");
    /// let num: i64 = id.parse().unwrap();
    /// assert_eq!(num, 42);
    ///
    /// // Invalid format returns error
    /// let id = Id::new("not_a_number");
    /// let result: Result<i64, _> = id.parse();
    /// assert!(result.is_err());
    /// ```
    #[inline]
    pub fn parse<T: std::str::FromStr>(&self) -> Result<T, ParseError> {
        self.0
            .parse()
            .map_err(|_| ParseError::invalid_format("id", &self.0))
    }
}

impl FromPath for Id {
    fn from_params(params: &HashMap<String, String>) -> Result<Self, ParseError> {
        params
            .get("id")
            .map(|s| Self(s.clone()))
            .ok_or_else(|| ParseError::missing("id"))
    }
}

impl OpenApiSchema for Id {
    fn openapi_schema() -> &'static str {
        r#"{"type":"string","description":"Resource identifier"}"#
    }

    fn schema_name() -> &'static str {
        "Id"
    }
}

impl AsRef<str> for Id {
    #[inline]
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for Id {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

// ============================================================================
// PARSING TRAITS
// ============================================================================

/// Trait for types that can be parsed from JSON.
///
/// Implement this for request body types. Usually derived with `#[derive(Type)]`.
///
/// # Example
///
/// ```
/// # use mik_sdk::typed::{FromJson, ParseError};
/// # use mik_sdk::json::{self, JsonValue};
/// // Parse a String from JSON
/// let value = json::str("hello");
/// let result = String::from_json(&value);
/// assert_eq!(result.unwrap(), "hello");
///
/// // Type mismatch returns error
/// let value = json::int(42);
/// let result = String::from_json(&value);
/// assert!(result.is_err());
/// ```
pub trait FromJson: Sized {
    /// Parse this type from a JSON value.
    fn from_json(value: &JsonValue) -> Result<Self, ParseError>;

    /// Parse this type from a raw miniserde Value reference.
    ///
    /// This is used internally for efficient array parsing without cloning.
    /// The default implementation wraps the value in a JsonValue (which clones),
    /// but primitive types override this for zero-copy parsing.
    fn from_raw_value(value: &crate::json::RawValue) -> Result<Self, ParseError> {
        Self::from_json(&JsonValue::from_raw(value))
    }
}

/// Trait for types that can be parsed from query parameters.
///
/// Implement this for query parameter types. Usually derived with `#[derive(Query)]`.
/// The derive macro generates implementations that handle type conversion and defaults.
///
/// # Example
///
/// The trait takes query parameters as key-value pairs:
///
/// ```
/// # use mik_sdk::typed::{FromQuery, ParseError};
/// // Example of manually implementing FromQuery
/// struct PageQuery { page: u32 }
///
/// impl FromQuery for PageQuery {
///     fn from_query(params: &[(String, String)]) -> Result<Self, ParseError> {
///         let page = params.iter()
///             .find(|(k, _)| k == "page")
///             .map(|(_, v)| v.parse::<u32>())
///             .transpose()
///             .map_err(|_| ParseError::invalid_format("page", ""))?
///             .unwrap_or(1);
///         Ok(Self { page })
///     }
/// }
///
/// let params = vec![("page".to_string(), "5".to_string())];
/// let query = PageQuery::from_query(&params).unwrap();
/// assert_eq!(query.page, 5);
/// ```
pub trait FromQuery: Sized {
    /// Parse this type from query parameters.
    fn from_query(params: &[(String, String)]) -> Result<Self, ParseError>;
}

/// Trait for types that can be parsed from path parameters.
///
/// Implement this for path parameter types. Usually derived with `#[derive(Path)]`.
///
/// # Example
///
/// ```
/// # use mik_sdk::typed::{FromPath, ParseError};
/// # use std::collections::HashMap;
/// // Example of manually implementing FromPath
/// struct UserPath { id: String }
///
/// impl FromPath for UserPath {
///     fn from_params(params: &HashMap<String, String>) -> Result<Self, ParseError> {
///         let id = params.get("id")
///             .ok_or_else(|| ParseError::missing("id"))?
///             .clone();
///         Ok(Self { id })
///     }
/// }
///
/// let mut params = HashMap::new();
/// params.insert("id".to_string(), "user_123".to_string());
/// let path = UserPath::from_params(&params).unwrap();
/// assert_eq!(path.id, "user_123");
/// ```
pub trait FromPath: Sized {
    /// Parse this type from path parameters.
    fn from_params(params: &HashMap<String, String>) -> Result<Self, ParseError>;
}

/// Trait for types that can be validated against constraints.
///
/// Implement this for types with field constraints. Usually derived with `#[derive(Type)]`.
///
/// # Example
///
/// ```
/// # use mik_sdk::typed::{Validate, ValidationError};
/// // Example of manually implementing Validate
/// struct CreateUser { name: String }
///
/// impl Validate for CreateUser {
///     fn validate(&self) -> Result<(), ValidationError> {
///         if self.name.is_empty() {
///             return Err(ValidationError::min("name", 1));
///         }
///         if self.name.len() > 100 {
///             return Err(ValidationError::max("name", 100));
///         }
///         Ok(())
///     }
/// }
///
/// let user = CreateUser { name: String::new() };
/// let result = user.validate();
/// assert!(result.is_err());
///
/// let user = CreateUser { name: "Alice".to_string() };
/// assert!(user.validate().is_ok());
/// ```
pub trait Validate {
    /// Validate this value against its constraints.
    fn validate(&self) -> Result<(), ValidationError>;
}

/// Trait for types that can generate their OpenAPI schema.
///
/// Implemented by types derived with `#[derive(Type)]`, `#[derive(Query)]`, etc.
pub trait OpenApiSchema {
    /// Get the OpenAPI JSON schema for this type.
    fn openapi_schema() -> &'static str;

    /// Get the schema name for $ref references.
    fn schema_name() -> &'static str;

    /// Get OpenAPI query parameters array for Query types.
    ///
    /// Returns a JSON array of parameter objects for use in OpenAPI path items.
    /// Only meaningful for types derived with `#[derive(Query)]`.
    ///
    /// Default implementation returns empty array for non-Query types.
    fn openapi_query_params() -> &'static str {
        "[]"
    }
}

// ============================================================================
// HELPER IMPLEMENTATIONS
// ============================================================================

// Implement FromJson for common types
impl FromJson for String {
    fn from_json(value: &JsonValue) -> Result<Self, ParseError> {
        value
            .str()
            .ok_or_else(|| ParseError::type_mismatch("value", "string"))
    }
}

impl FromJson for i32 {
    fn from_json(value: &JsonValue) -> Result<Self, ParseError> {
        value
            .int()
            .map(|n| n as Self)
            .ok_or_else(|| ParseError::type_mismatch("value", "integer"))
    }
}

impl FromJson for i64 {
    fn from_json(value: &JsonValue) -> Result<Self, ParseError> {
        value
            .int()
            .ok_or_else(|| ParseError::type_mismatch("value", "integer"))
    }
}

impl FromJson for f64 {
    fn from_json(value: &JsonValue) -> Result<Self, ParseError> {
        value
            .float()
            .ok_or_else(|| ParseError::type_mismatch("value", "number"))
    }
}

impl FromJson for bool {
    fn from_json(value: &JsonValue) -> Result<Self, ParseError> {
        value
            .bool()
            .ok_or_else(|| ParseError::type_mismatch("value", "boolean"))
    }
}

impl<T: FromJson> FromJson for Option<T> {
    fn from_json(value: &JsonValue) -> Result<Self, ParseError> {
        if value.is_null() {
            Ok(None)
        } else {
            T::from_json(value).map(Some)
        }
    }
}

impl<T: FromJson> FromJson for Vec<T> {
    fn from_json(value: &JsonValue) -> Result<Self, ParseError> {
        // Use try_map_array for direct iteration without index-based access.
        // This avoids the overhead of len() check + at(i) bounds checking per element.
        value
            .try_map_array(|elem| T::from_json(&crate::json::JsonValue::from_raw(elem)))
            .ok_or_else(|| ParseError::type_mismatch("value", "array"))?
    }
}

#[cfg(test)]
#[allow(clippy::float_cmp)]
mod tests {
    use super::*;
    use crate::json;

    // ============================================================================
    // ID STRUCT TESTS
    // ============================================================================

    #[test]
    fn test_id_new_and_as_str() {
        let id = Id::new("user_123");
        assert_eq!(id.as_str(), "user_123");
    }

    #[test]
    fn test_id_from_string() {
        let id = Id::new(String::from("uuid-abc-123"));
        assert_eq!(id.as_str(), "uuid-abc-123");
    }

    #[test]
    fn test_id_empty_string() {
        let id = Id::new("");
        assert_eq!(id.as_str(), "");
        assert!(id.as_str().is_empty());
    }

    #[test]
    fn test_id_into_inner() {
        let id = Id::new("user_123");
        let inner = id.into_inner();
        assert_eq!(inner, "user_123");
    }

    #[test]
    fn test_id_parse_valid_integer() {
        let id = Id::new("42");
        let parsed: Result<i64, _> = id.parse();
        assert_eq!(parsed.unwrap(), 42);
    }

    #[test]
    fn test_id_parse_valid_u32() {
        let id = Id::new("12345");
        let parsed: Result<u32, _> = id.parse();
        assert_eq!(parsed.unwrap(), 12345);
    }

    #[test]
    fn test_id_parse_invalid_format() {
        let id = Id::new("not-a-number");
        let parsed: Result<i64, _> = id.parse();
        assert!(parsed.is_err());
        let err = parsed.unwrap_err();
        assert_eq!(err.field(), "id");
        assert!(err.message().contains("invalid format"));
        assert!(err.message().contains("not-a-number"));
    }

    #[test]
    fn test_id_parse_empty_string_as_integer() {
        let id = Id::new("");
        let parsed: Result<i64, _> = id.parse();
        assert!(parsed.is_err());
    }

    #[test]
    fn test_id_equality() {
        let id1 = Id::new("abc");
        let id2 = Id::new("abc");
        let id3 = Id::new("xyz");
        assert_eq!(id1, id2);
        assert_ne!(id1, id3);
    }

    #[test]
    fn test_id_clone() {
        let id1 = Id::new("test");
        let id2 = id1.clone();
        assert_eq!(id1, id2);
    }

    #[test]
    fn test_id_hash() {
        use std::collections::HashSet;
        let mut set = HashSet::new();
        set.insert(Id::new("a"));
        set.insert(Id::new("b"));
        set.insert(Id::new("a")); // duplicate
        assert_eq!(set.len(), 2);
    }

    #[test]
    fn test_id_from_path_success() {
        let mut params = HashMap::new();
        params.insert("id".to_string(), "user_456".to_string());
        let id = Id::from_params(&params).unwrap();
        assert_eq!(id.as_str(), "user_456");
    }

    #[test]
    fn test_id_from_path_missing() {
        let params = HashMap::new();
        let result = Id::from_params(&params);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.field(), "id");
        assert!(err.message().contains("missing"));
    }

    #[test]
    fn test_id_openapi_schema() {
        let schema = Id::openapi_schema();
        assert!(schema.contains("\"type\":\"string\""));
        assert!(schema.contains("\"description\":\"Resource identifier\""));
    }

    #[test]
    fn test_id_schema_name() {
        assert_eq!(Id::schema_name(), "Id");
    }

    // ============================================================================
    // PARSE ERROR TESTS
    // ============================================================================

    #[test]
    fn test_parse_error_missing() {
        let err = ParseError::missing("email");
        assert_eq!(err.field(), "email");
        assert!(err.message().contains("missing required field"));
        assert!(err.message().contains("email"));
        // Test pattern matching
        assert!(matches!(err, ParseError::MissingField { .. }));
    }

    #[test]
    fn test_parse_error_invalid_format() {
        let err = ParseError::invalid_format("date", "not-a-date");
        assert_eq!(err.field(), "date");
        assert!(err.message().contains("invalid format"));
        assert!(err.message().contains("date"));
        assert!(err.message().contains("not-a-date"));
        // Test pattern matching
        assert!(matches!(err, ParseError::InvalidFormat { .. }));
    }

    #[test]
    fn test_parse_error_type_mismatch() {
        let err = ParseError::type_mismatch("age", "integer");
        assert_eq!(err.field(), "age");
        assert!(err.message().contains("expected integer"));
        assert!(err.message().contains("age"));
        // Test pattern matching
        assert!(matches!(err, ParseError::TypeMismatch { .. }));
    }

    #[test]
    fn test_parse_error_custom() {
        let err = ParseError::custom("field", "Something went wrong");
        assert_eq!(err.field(), "field");
        assert_eq!(err.message(), "Something went wrong");
        // Test pattern matching
        assert!(matches!(err, ParseError::Custom { .. }));
    }

    #[test]
    fn test_parse_error_custom_with_string() {
        let msg = String::from("Custom error message");
        let err = ParseError::custom("field", msg);
        assert_eq!(err.message(), "Custom error message");
    }

    #[test]
    fn test_parse_error_display() {
        let err = ParseError::missing("name");
        let display = format!("{err}");
        assert!(display.contains("missing required field `name`"));
    }

    #[test]
    fn test_parse_error_debug() {
        let err = ParseError::missing("name");
        let debug = format!("{err:?}");
        // Enum variant name appears in debug output
        assert!(debug.contains("MissingField"));
        assert!(debug.contains("name"));
    }

    #[test]
    fn test_parse_error_equality() {
        let err1 = ParseError::missing("field");
        let err2 = ParseError::missing("field");
        let err3 = ParseError::missing("other");
        assert_eq!(err1, err2);
        assert_ne!(err1, err3);
    }

    #[test]
    fn test_parse_error_clone() {
        let err1 = ParseError::missing("field");
        let err2 = err1.clone();
        assert_eq!(err1, err2);
    }

    #[test]
    fn test_parse_error_is_std_error() {
        let err = ParseError::missing("field");
        let _: &dyn std::error::Error = &err;
    }

    #[test]
    fn test_parse_error_with_path() {
        let err = ParseError::missing("city").with_path("address");
        assert_eq!(err.field(), "address.city");
        assert!(err.message().contains("address.city"));

        // Test nested paths
        let err2 = err.with_path("user");
        assert_eq!(err2.field(), "user.address.city");
    }

    #[test]
    fn test_parse_error_with_path_all_variants() {
        // MissingField
        let err = ParseError::missing("name").with_path("user");
        assert_eq!(err.field(), "user.name");

        // InvalidFormat
        let err = ParseError::invalid_format("age", "abc").with_path("user");
        assert_eq!(err.field(), "user.age");

        // TypeMismatch
        let err = ParseError::type_mismatch("count", "integer").with_path("items");
        assert_eq!(err.field(), "items.count");

        // Custom
        let err = ParseError::custom("value", "custom error").with_path("data");
        assert_eq!(err.field(), "data.value");
    }

    #[test]
    fn test_validation_error_to_parse_error() {
        let validation_err = ValidationError::min("count", 1);
        let parse_err: ParseError = validation_err.into();
        assert_eq!(parse_err.field(), "count");
        assert!(parse_err.message().contains("at least"));
    }

    // ============================================================================
    // VALIDATION ERROR TESTS
    // ============================================================================

    #[test]
    fn test_validation_error_min() {
        let err = ValidationError::min("name", 3);
        assert_eq!(err.field(), "name");
        assert_eq!(err.constraint(), "min");
        assert!(err.message().contains("`name`"));
        assert!(err.message().contains("at least 3"));
        // Test pattern matching
        assert!(matches!(err, ValidationError::Min { min: 3, .. }));
    }

    #[test]
    fn test_validation_error_max() {
        let err = ValidationError::max("count", 100);
        assert_eq!(err.field(), "count");
        assert_eq!(err.constraint(), "max");
        assert!(err.message().contains("`count`"));
        assert!(err.message().contains("at most 100"));
        // Test pattern matching
        assert!(matches!(err, ValidationError::Max { max: 100, .. }));
    }

    #[test]
    fn test_validation_error_pattern() {
        let err = ValidationError::pattern("email", r"^[\w@.]+$");
        assert_eq!(err.field(), "email");
        assert_eq!(err.constraint(), "pattern");
        assert!(err.message().contains("`email`"));
        assert!(err.message().contains("must match pattern"));
        // Test pattern matching
        assert!(matches!(err, ValidationError::Pattern { .. }));
    }

    #[test]
    fn test_validation_error_format() {
        let err = ValidationError::format("email", "email address");
        assert_eq!(err.field(), "email");
        assert_eq!(err.constraint(), "format");
        assert!(err.message().contains("`email`"));
        assert!(err.message().contains("valid email address"));
        // Test pattern matching
        assert!(matches!(err, ValidationError::Format { .. }));
    }

    #[test]
    fn test_validation_error_custom() {
        let err = ValidationError::custom("age", "range", "Age must be between 0 and 150");
        assert_eq!(err.field(), "age");
        assert_eq!(err.constraint(), "range");
        assert_eq!(err.message(), "Age must be between 0 and 150");
        // Test pattern matching
        assert!(matches!(err, ValidationError::Custom { .. }));
    }

    #[test]
    fn test_validation_error_display() {
        let err = ValidationError::min("name", 1);
        let display = format!("{err}");
        assert!(display.contains("`name` must be at least 1"));
    }

    #[test]
    fn test_validation_error_debug() {
        let err = ValidationError::max("age", 120);
        let debug = format!("{err:?}");
        // Enum variant name appears in debug output
        assert!(debug.contains("Max"));
        assert!(debug.contains("age"));
        assert!(debug.contains("120"));
    }

    #[test]
    fn test_validation_error_equality() {
        let err1 = ValidationError::min("field", 5);
        let err2 = ValidationError::min("field", 5);
        let err3 = ValidationError::max("field", 5);
        assert_eq!(err1, err2);
        assert_ne!(err1, err3);
    }

    #[test]
    fn test_validation_error_clone() {
        let err1 = ValidationError::format("email", "email");
        let err2 = err1.clone();
        assert_eq!(err1, err2);
    }

    #[test]
    fn test_validation_error_is_std_error() {
        let err = ValidationError::min("field", 1);
        let _: &dyn std::error::Error = &err;
    }

    #[test]
    fn test_validation_error_with_path() {
        let err = ValidationError::min("count", 1).with_path("items");
        assert_eq!(err.field(), "items.count");
        assert!(err.message().contains("items.count"));

        // Test nested paths
        let err2 = err.with_path("order");
        assert_eq!(err2.field(), "order.items.count");
    }

    #[test]
    fn test_validation_error_with_path_all_variants() {
        // Min
        let err = ValidationError::min("count", 1).with_path("items");
        assert_eq!(err.field(), "items.count");

        // Max
        let err = ValidationError::max("limit", 100).with_path("query");
        assert_eq!(err.field(), "query.limit");

        // Pattern
        let err = ValidationError::pattern("code", "^[A-Z]+$").with_path("data");
        assert_eq!(err.field(), "data.code");

        // Format
        let err = ValidationError::format("email", "email").with_path("user");
        assert_eq!(err.field(), "user.email");

        // Custom
        let err = ValidationError::custom("value", "range", "out of range").with_path("config");
        assert_eq!(err.field(), "config.value");
    }

    // ============================================================================
    // FROM_JSON FOR PRIMITIVE TYPES
    // ============================================================================

    #[test]
    fn test_from_json_string() {
        let v = json::str("hello");
        let result = String::from_json(&v);
        assert_eq!(result.unwrap(), "hello");
    }

    #[test]
    fn test_from_json_string_type_mismatch() {
        let v = json::int(42);
        let result = String::from_json(&v);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.field(), "value");
        assert!(err.message().contains("string"));
    }

    #[test]
    fn test_from_json_i32() {
        let v = json::int(42);
        let result = i32::from_json(&v);
        assert_eq!(result.unwrap(), 42);
    }

    #[test]
    fn test_from_json_i32_type_mismatch() {
        let v = json::str("not a number");
        let result = i32::from_json(&v);
        assert!(result.is_err());
    }

    #[test]
    fn test_from_json_i64() {
        let v = json::int(9_000_000_000);
        let result = i64::from_json(&v);
        assert_eq!(result.unwrap(), 9_000_000_000);
    }

    #[test]
    fn test_from_json_i64_type_mismatch() {
        let v = json::bool(true);
        let result = i64::from_json(&v);
        assert!(result.is_err());
    }

    #[test]
    fn test_from_json_f64() {
        let v = json::float(42.5);
        let result = f64::from_json(&v);
        let parsed = result.unwrap();
        assert!((parsed - 42.5).abs() < 0.001);
    }

    #[test]
    fn test_from_json_f64_from_int() {
        let v = json::int(42);
        let result = f64::from_json(&v);
        assert_eq!(result.unwrap(), 42.0);
    }

    #[test]
    fn test_from_json_f64_type_mismatch() {
        let v = json::str("not a number");
        let result = f64::from_json(&v);
        assert!(result.is_err());
    }

    #[test]
    fn test_from_json_bool_true() {
        let v = json::bool(true);
        let result = bool::from_json(&v);
        assert!(result.unwrap());
    }

    #[test]
    fn test_from_json_bool_false() {
        let v = json::bool(false);
        let result = bool::from_json(&v);
        assert!(!result.unwrap());
    }

    #[test]
    fn test_from_json_bool_type_mismatch() {
        let v = json::int(1);
        let result = bool::from_json(&v);
        assert!(result.is_err());
    }

    // ============================================================================
    // FROM_JSON FOR OPTION<T>
    // ============================================================================

    #[test]
    fn test_from_json_option_some_string() {
        let v = json::str("hello");
        let result = Option::<String>::from_json(&v);
        assert_eq!(result.unwrap(), Some("hello".to_string()));
    }

    #[test]
    fn test_from_json_option_none_null() {
        let v = json::null();
        let result = Option::<String>::from_json(&v);
        assert_eq!(result.unwrap(), None);
    }

    #[test]
    fn test_from_json_option_some_i64() {
        let v = json::int(123);
        let result = Option::<i64>::from_json(&v);
        assert_eq!(result.unwrap(), Some(123));
    }

    #[test]
    fn test_from_json_option_some_bool() {
        let v = json::bool(true);
        let result = Option::<bool>::from_json(&v);
        assert_eq!(result.unwrap(), Some(true));
    }

    #[test]
    fn test_from_json_option_type_mismatch_propagates() {
        // When the value is not null but doesn't match the expected type,
        // the error should propagate
        let v = json::str("not a number");
        let result = Option::<i64>::from_json(&v);
        assert!(result.is_err());
    }

    #[test]
    fn test_from_json_nested_option() {
        // Option<Option<T>> - outer Option handles null, inner handles presence
        let v = json::null();
        let result = Option::<Option<String>>::from_json(&v);
        assert_eq!(result.unwrap(), None);
    }

    // ============================================================================
    // FROM_JSON FOR VEC<T>
    // ============================================================================

    #[test]
    fn test_from_json_vec_strings() {
        let v = json::arr()
            .push(json::str("a"))
            .push(json::str("b"))
            .push(json::str("c"));
        let result = Vec::<String>::from_json(&v);
        assert_eq!(result.unwrap(), vec!["a", "b", "c"]);
    }

    #[test]
    fn test_from_json_vec_integers() {
        let v = json::arr()
            .push(json::int(1))
            .push(json::int(2))
            .push(json::int(3));
        let result = Vec::<i64>::from_json(&v);
        assert_eq!(result.unwrap(), vec![1, 2, 3]);
    }

    #[test]
    fn test_from_json_vec_empty() {
        let v = json::arr();
        let result = Vec::<String>::from_json(&v);
        assert_eq!(result.unwrap(), Vec::<String>::new());
    }

    #[test]
    fn test_from_json_vec_bools() {
        let v = json::arr()
            .push(json::bool(true))
            .push(json::bool(false))
            .push(json::bool(true));
        let result = Vec::<bool>::from_json(&v);
        assert_eq!(result.unwrap(), vec![true, false, true]);
    }

    #[test]
    fn test_from_json_vec_type_mismatch_not_array() {
        let v = json::str("not an array");
        let result = Vec::<String>::from_json(&v);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.message().contains("array"));
    }

    #[test]
    fn test_from_json_vec_element_type_mismatch() {
        let v = json::arr().push(json::str("valid")).push(json::int(123)); // Not a string
        let result = Vec::<String>::from_json(&v);
        assert!(result.is_err());
    }

    #[test]
    fn test_from_json_vec_option_elements() {
        // Vec<Option<String>> - array with optional elements
        let v = json::arr()
            .push(json::str("a"))
            .push(json::null())
            .push(json::str("c"));
        let result = Vec::<Option<String>>::from_json(&v);
        assert_eq!(
            result.unwrap(),
            vec![Some("a".to_string()), None, Some("c".to_string())]
        );
    }

    #[test]
    fn test_from_json_option_vec() {
        // Option<Vec<String>> - nullable array
        let v = json::arr().push(json::str("a")).push(json::str("b"));
        let result = Option::<Vec<String>>::from_json(&v);
        assert_eq!(
            result.unwrap(),
            Some(vec!["a".to_string(), "b".to_string()])
        );

        let v_null = json::null();
        let result_null = Option::<Vec<String>>::from_json(&v_null);
        assert_eq!(result_null.unwrap(), None);
    }

    // ============================================================================
    // FROM_JSON NESTED/COMPLEX TYPES
    // ============================================================================

    #[test]
    fn test_from_json_vec_of_vec() {
        // Vec<Vec<i64>> - nested arrays
        let v = json::arr()
            .push(json::arr().push(json::int(1)).push(json::int(2)))
            .push(json::arr().push(json::int(3)).push(json::int(4)));
        let result = Vec::<Vec<i64>>::from_json(&v);
        assert_eq!(result.unwrap(), vec![vec![1, 2], vec![3, 4]]);
    }

    #[test]
    fn test_from_json_vec_of_vec_empty_inner() {
        let v = json::arr()
            .push(json::arr())
            .push(json::arr().push(json::int(1)));
        let result = Vec::<Vec<i64>>::from_json(&v);
        assert_eq!(result.unwrap(), vec![vec![], vec![1]]);
    }

    // ============================================================================
    // TYPE COERCION EDGE CASES
    // ============================================================================

    #[test]
    fn test_from_json_i32_truncation() {
        // Large i64 value truncated to i32
        let v = json::int(100);
        let result = i32::from_json(&v);
        assert_eq!(result.unwrap(), 100);
    }

    #[test]
    fn test_from_json_f64_from_large_int() {
        // Very large integers might lose precision when converted to f64
        let v = json::int(1_000_000);
        let result = f64::from_json(&v);
        assert_eq!(result.unwrap(), 1_000_000.0);
    }

    #[test]
    fn test_from_json_null_not_valid_string() {
        let v = json::null();
        let result = String::from_json(&v);
        assert!(result.is_err());
    }

    #[test]
    fn test_from_json_null_not_valid_int() {
        let v = json::null();
        let result = i64::from_json(&v);
        assert!(result.is_err());
    }

    #[test]
    fn test_from_json_null_not_valid_bool() {
        let v = json::null();
        let result = bool::from_json(&v);
        assert!(result.is_err());
    }

    // ============================================================================
    // PARSE FROM JSON BYTES
    // ============================================================================

    #[test]
    fn test_from_json_parsed_string() {
        let v = json::try_parse(b"\"hello world\"").unwrap();
        let result = String::from_json(&v);
        assert_eq!(result.unwrap(), "hello world");
    }

    #[test]
    fn test_from_json_parsed_number() {
        let v = json::try_parse(b"42").unwrap();
        let result = i64::from_json(&v);
        assert_eq!(result.unwrap(), 42);
    }

    #[test]
    fn test_from_json_parsed_array() {
        let v = json::try_parse(b"[1, 2, 3]").unwrap();
        let result = Vec::<i64>::from_json(&v);
        assert_eq!(result.unwrap(), vec![1, 2, 3]);
    }

    #[test]
    fn test_from_json_parsed_null_option() {
        let v = json::try_parse(b"null").unwrap();
        let result = Option::<String>::from_json(&v);
        assert_eq!(result.unwrap(), None);
    }

    // ============================================================================
    // ERROR MESSAGE CONTENT VERIFICATION
    // ============================================================================

    #[test]
    fn test_parse_error_messages_are_user_friendly() {
        let missing = ParseError::missing("username");
        assert!(missing.message().starts_with("missing"));
        assert!(missing.to_string().contains("username"));

        let invalid = ParseError::invalid_format("date", "abc");
        assert!(invalid.message().contains("invalid"));
        assert!(invalid.to_string().contains("abc"));

        let type_err = ParseError::type_mismatch("age", "number");
        assert!(type_err.message().contains("expected"));
        assert!(type_err.to_string().contains("number"));
    }

    #[test]
    fn test_validation_error_messages_are_user_friendly() {
        let min = ValidationError::min("name", 3);
        assert!(min.message().contains("at least"));
        assert!(min.message().contains('3'));

        let max = ValidationError::max("items", 10);
        assert!(max.message().contains("at most"));
        assert!(max.message().contains("10"));

        let pattern = ValidationError::pattern("code", "^[A-Z]{3}$");
        assert!(pattern.message().contains("pattern"));

        let format = ValidationError::format("email", "email");
        assert!(format.message().contains("valid"));
    }

    // ============================================================================
    // EDGE CASES AND BOUNDARY CONDITIONS
    // ============================================================================

    #[test]
    fn test_id_with_special_characters() {
        let id = Id::new("user/123#section?query=1&foo=bar");
        assert_eq!(id.as_str(), "user/123#section?query=1&foo=bar");
    }

    #[test]
    fn test_id_with_unicode() {
        let id = Id::new("user_");
        assert_eq!(id.as_str(), "user_");
    }

    #[test]
    fn test_parse_error_with_empty_field_name() {
        let err = ParseError::missing("");
        assert_eq!(err.field(), "");
        // Should still have a message even with empty field
        assert!(!err.message().is_empty());
    }

    #[test]
    fn test_validation_error_with_negative_min() {
        let err = ValidationError::min("temperature", -40);
        assert!(err.message().contains("-40"));
    }

    #[test]
    fn test_validation_error_with_large_max() {
        let err = ValidationError::max("count", i64::MAX);
        assert!(err.message().contains(&i64::MAX.to_string()));
    }

    #[test]
    fn test_from_json_empty_string() {
        let v = json::str("");
        let result = String::from_json(&v);
        assert_eq!(result.unwrap(), "");
    }

    #[test]
    fn test_from_json_negative_integer() {
        let v = json::int(-999);
        let result = i64::from_json(&v);
        assert_eq!(result.unwrap(), -999);
    }

    #[test]
    fn test_from_json_zero() {
        let v = json::int(0);
        let result = i64::from_json(&v);
        assert_eq!(result.unwrap(), 0);
    }

    #[test]
    fn test_from_json_negative_float() {
        let v = json::float(-42.5);
        let result = f64::from_json(&v);
        let parsed = result.unwrap();
        assert!((parsed - (-42.5)).abs() < 0.001);
    }
}