sema-validate 0.1.0

Schema validation for maps and data structures

Source

package.sema

196 lines c21eb74696c9
File details

Source stored with sema-validate 0.1.0. Line links refer to these exact bytes.

SHA-256 c21eb74696c93530ecb55b1fc10d85f91a28a1f70dd4223d818123175dfbcdca

1;; sema-validate — schema validation for maps and data structures
2;;
3;; A spec map pairs keys with either a bare predicate ({:name string?}), a
4;; validator built by the validate/* constructors, or a nested spec map.
5;; Validator maps have the shape {:check fn :message str :required? bool :nested map-or-nil}.
6
7(module sema-validate
8  (export validate/required
9          validate/optional
10          validate/one-of
11          validate/all-of
12          validate/list-of
13          validate/matches
14          validate/in-range
15          validate/min-length
16          validate/max-length
17          validate/schema
18          validate/errors
19          validate/valid?
20          validate/assert!)
21
22  ;; ---------------------------------------------------------------------------
23  ;; Private helpers
24  ;; ---------------------------------------------------------------------------
25
26  (define (validator? v)
27    (and (map? v) (contains? v :check)))
28
29  ;; "<native-fn string?>" / "<lambda adult?>" → "string?" / "adult?"
30  (define (pred-name p)
31    (let ((s (str p)))
32      (if (and (string/starts-with? s "<")
33               (string/ends-with? s ">")
34               (string/contains? s " "))
35        (last (string/split (substring s 1 (- (string-length s) 1)) " "))
36        s)))
37
38  (define (check-fn-of v)  (if (validator? v) (get v :check) v))
39
40  ;; Short description for use inside composite messages ("expected all-of: ...").
41  (define (message-of v)
42    (if (validator? v)
43      (string/chop-start (get v :message) "expected ")
44      (pred-name v)))
45
46  ;; ---------------------------------------------------------------------------
47  ;; Validator constructors
48  ;; ---------------------------------------------------------------------------
49
50  (define (validate/required pred)
51    "Mark a field as required. pred is a predicate, validator, or nested spec map."
52    (cond
53      ((validator? pred) (assoc pred :required? #t))
54      ((map? pred) (hash-map :check nil :message nil :required? #t :nested pred))
55      (#t (hash-map :check pred :message (string-append "expected " (pred-name pred))
56                    :required? #t :nested nil))))
57
58  (define (validate/optional pred)
59    "Mark a field as optional: absent is fine, present values must still match.
60     pred is a predicate, validator, or nested spec map."
61    (cond
62      ((validator? pred) (assoc pred :required? #f))
63      ((map? pred) (hash-map :check nil :message nil :required? #f :nested pred))
64      (#t (hash-map :check pred :message (string-append "expected " (pred-name pred))
65                    :required? #f :nested nil))))
66
67  (define (validate/one-of . values)
68    "Value must equal one of the given values."
69    (hash-map
70      :check   (fn (v) (any #(equal? % v) values))
71      :message (string-append "expected one-of: " (string/join (map str values) ", "))
72      :required? #t
73      :nested  nil))
74
75  (define (validate/all-of . preds)
76    "Value must satisfy every given predicate or validator."
77    (hash-map
78      :check   (fn (v) (every (fn (p) ((check-fn-of p) v)) preds))
79      :message (string-append "expected all-of: "
80                              (string/join (map message-of preds) ", "))
81      :required? #t
82      :nested  nil))
83
84  (define (validate/list-of pred)
85    "Value must be a list whose every element matches the predicate or validator."
86    (hash-map
87      :check   (fn (v) (and (list? v) (every (check-fn-of pred) v)))
88      :message (string-append "expected list-of: " (message-of pred))
89      :required? #t
90      :nested  nil))
91
92  (define (validate/matches pattern)
93    "Value must be a string matching the given regex pattern."
94    (hash-map
95      :check   (fn (v) (and (string? v) (regex/match? pattern v)))
96      :message (string-append "expected string matching " (str pattern))
97      :required? #t
98      :nested  nil))
99
100  (define (validate/in-range lo hi)
101    "Value must be a number within the inclusive range [lo, hi]."
102    (hash-map
103      :check   (fn (v) (and (number? v) (>= v lo) (<= v hi)))
104      :message (format "expected in-range ~a ~a" lo hi)
105      :required? #t
106      :nested  nil))
107
108  (define (validate/min-length n)
109    "Value must be a string or list with at least n characters/elements."
110    (hash-map
111      :check   (fn (v) (cond ((string? v) (>= (string-length v) n))
112                             ((list? v)   (>= (length v) n))
113                             (#t #f)))
114      :message (format "expected min-length ~a" n)
115      :required? #t
116      :nested  nil))
117
118  (define (validate/max-length n)
119    "Value must be a string or list with at most n characters/elements."
120    (hash-map
121      :check   (fn (v) (cond ((string? v) (<= (string-length v) n))
122                             ((list? v)   (<= (length v) n))
123                             (#t #f)))
124      :message (format "expected max-length ~a" n)
125      :required? #t
126      :nested  nil))
127
128  ;; ---------------------------------------------------------------------------
129  ;; Normalization: raw spec value → validator map
130  ;; ---------------------------------------------------------------------------
131
132  (define (normalize-spec spec)
133    (cond
134      ((validator? spec) spec)                                                 ; validator (incl. nested from required/optional)
135      ((map? spec) (hash-map :check nil :message nil :required? #t :nested spec)) ; bare nested spec map
136      (#t (hash-map :check spec :message (string-append "expected " (pred-name spec))
137                    :required? #t :nested nil))))                              ; bare predicate
138
139  ;; ---------------------------------------------------------------------------
140  ;; Schema creation & validation
141  ;; ---------------------------------------------------------------------------
142
143  (define (validate/schema spec)
144    "Create a schema from a spec map."
145    (hash-map :spec spec))
146
147  (define (collect-errors spec data path)
148    (let ((result '()))
149      (for-each (fn (key)
150        (let* ((raw      (get spec key))
151               (val-spec (normalize-spec raw))
152               (req?     (get val-spec :required?))
153               (check    (get val-spec :check))
154               (msg      (get val-spec :message))
155               (nested   (get val-spec :nested))
156               (present  (contains? data key))
157               (value    (if present (get data key) nil))
158               (cur-path (append path (list key))))
159          (cond
160            ((and (not present) req?)
161             (set! result (append result (list (hash-map :path cur-path :message "required field missing" :value nil)))))
162            ((not present) nil)
163            ((not (nil? nested))
164             (if (map? value)
165               (set! result (append result (collect-errors nested value cur-path)))
166               (set! result (append result (list (hash-map :path cur-path :message "expected a map" :value value))))))
167            ((and (not (nil? check)) (not (check value)))
168             (set! result (append result (list (hash-map :path cur-path :message msg :value value)))))
169            (#t nil))))
170        (keys spec))
171      result))
172
173  (define (validate/errors sch data)
174    "Return a list of error maps ({:path :message :value}). Empty list if valid."
175    (collect-errors (get sch :spec) data '()))
176
177  (define (validate/valid? sch data)
178    "Return #t if data matches the schema, #f otherwise."
179    (null? (validate/errors sch data)))
180
181  ;; ({:path (:a :b) :message "..."} ...) → "a.b: ...; ..."
182  (define (format-error e)
183    (string-append
184      (string/join (map (fn (k) (if (keyword? k) (keyword->string k) (str k)))
185                        (get e :path))
186                   ".")
187      ": " (get e :message)))
188
189  (define (validate/assert! sch data)
190    "Return data if valid; raise an error listing every failure if not."
191    (let ((errs (validate/errors sch data)))
192      (if (null? errs)
193        data
194        (error (string-append
195                 "validate/assert!: validation failed — "
196                 (string/join (map format-error errs) "; ")))))))