sema-validate 0.1.0
Schema validation for maps and data structures
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 structures2;;3;; A spec map pairs keys with either a bare predicate ({:name string?}), a4;; 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}.67(module sema-validate8(export validate/required9validate/optional10validate/one-of11validate/all-of12validate/list-of13validate/matches14validate/in-range15validate/min-length16validate/max-length17validate/schema18validate/errors19validate/valid?20validate/assert!)2122;; ---------------------------------------------------------------------------23;; Private helpers24;; ---------------------------------------------------------------------------2526(define (validator? v)27(and (map? v) (contains? v :check)))2829;; "<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)) " "))36s)))3738(define (check-fn-of v) (if (validator? v) (get v :check) v))3940;; 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)))4546;; ---------------------------------------------------------------------------47;; Validator constructors48;; ---------------------------------------------------------------------------4950(define (validate/required pred)51"Mark a field as required. pred is a predicate, validator, or nested spec map."52(cond53((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))))5758(define (validate/optional pred)59"Mark a field as optional: absent is fine, present values must still match.60pred is a predicate, validator, or nested spec map."61(cond62((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))))6667(define (validate/one-of . values)68"Value must equal one of the given values."69(hash-map70:check (fn (v) (any #(equal? % v) values))71:message (string-append "expected one-of: " (string/join (map str values) ", "))72:required? #t73:nested nil))7475(define (validate/all-of . preds)76"Value must satisfy every given predicate or validator."77(hash-map78: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? #t82:nested nil))8384(define (validate/list-of pred)85"Value must be a list whose every element matches the predicate or validator."86(hash-map87:check (fn (v) (and (list? v) (every (check-fn-of pred) v)))88:message (string-append "expected list-of: " (message-of pred))89:required? #t90:nested nil))9192(define (validate/matches pattern)93"Value must be a string matching the given regex pattern."94(hash-map95:check (fn (v) (and (string? v) (regex/match? pattern v)))96:message (string-append "expected string matching " (str pattern))97:required? #t98:nested nil))99100(define (validate/in-range lo hi)101"Value must be a number within the inclusive range [lo, hi]."102(hash-map103:check (fn (v) (and (number? v) (>= v lo) (<= v hi)))104:message (format "expected in-range ~a ~a" lo hi)105:required? #t106:nested nil))107108(define (validate/min-length n)109"Value must be a string or list with at least n characters/elements."110(hash-map111: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? #t116:nested nil))117118(define (validate/max-length n)119"Value must be a string or list with at most n characters/elements."120(hash-map121: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? #t126:nested nil))127128;; ---------------------------------------------------------------------------129;; Normalization: raw spec value → validator map130;; ---------------------------------------------------------------------------131132(define (normalize-spec spec)133(cond134((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 map136(#t (hash-map :check spec :message (string-append "expected " (pred-name spec))137:required? #t :nested nil)))) ; bare predicate138139;; ---------------------------------------------------------------------------140;; Schema creation & validation141;; ---------------------------------------------------------------------------142143(define (validate/schema spec)144"Create a schema from a spec map."145(hash-map :spec spec))146147(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(cond160((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))171result))172173(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 '()))176177(define (validate/valid? sch data)178"Return #t if data matches the schema, #f otherwise."179(null? (validate/errors sch data)))180181;; ({:path (:a :b) :message "..."} ...) → "a.b: ...; ..."182(define (format-error e)183(string-append184(string/join (map (fn (k) (if (keyword? k) (keyword->string k) (str k)))185(get e :path))186".")187": " (get e :message)))188189(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)193data194(error (string-append195"validate/assert!: validation failed — "196(string/join (map format-error errs) "; ")))))))