Documentation
¶
Index ¶
- Constants
- Variables
- func FromJSONSchema(schema any) (any, error)
- func IsShape(v any) bool
- func MustFromJSONSchema(schema any) any
- type Argu
- type Context
- type FieldError
- type KeyExprOptions
- type Kind
- type MetaOptions
- type Node
- func Above(above any, spec ...any) *Node
- func After(fn func(val any, update *Update, state *State) bool, spec ...any) *Node
- func All(shapes ...any) *Node
- func Before(fn func(val any, update *Update, state *State) bool, spec ...any) *Node
- func Below(below any, spec ...any) *Node
- func Catch(fallback any, spec ...any) *Node
- func Check(check any, spec ...any) *Node
- func Child(child any, spec ...any) *Node
- func Closed(spec ...any) *Node
- func Coerce(spec ...any) *Node
- func DateTime(spec ...any) *Node
- func Default(dval any, spec ...any) *Node
- func Define(name string, spec ...any) *Node
- func Describe(description string, spec ...any) *Node
- func Discriminated(tag string, branches map[string]any) *Node
- func Email(spec ...any) *Node
- func Empty(spec ...any) *Node
- func Exact(vals ...any) *Node
- func Expr(src string) (*Node, error)
- func Extend(extra any, spec ...any) *Node
- func Fault(msg string, spec ...any) *Node
- func Func(spec ...any) *Node
- func GAbove(above any, spec ...any) *Node
- func GAfter(fn func(any, *Update, *State) bool, spec ...any) *Node
- func GAll(shapes ...any) *Node
- func GBefore(fn func(any, *Update, *State) bool, spec ...any) *Node
- func GBelow(below any, spec ...any) *Node
- func GCatch(fallback any, spec ...any) *Node
- func GCheck(check any, spec ...any) *Node
- func GChild(child any, spec ...any) *Node
- func GClosed(spec ...any) *Node
- func GCoerce(spec ...any) *Node
- func GDateTime(spec ...any) *Node
- func GDefault(d any, spec ...any) *Node
- func GDefine(name string, spec ...any) *Node
- func GDescribe(description string, spec ...any) *Node
- func GDiscriminated(tag string, branches map[string]any) *Node
- func GEmail(spec ...any) *Node
- func GEmpty(spec ...any) *Node
- func GExact(vals ...any) *Node
- func GExtend(extra any, spec ...any) *Node
- func GFault(msg string, spec ...any) *Node
- func GFunc(spec ...any) *Node
- func GIgnore(spec ...any) *Node
- func GIp(spec ...any) *Node
- func GIpv4(spec ...any) *Node
- func GIpv6(spec ...any) *Node
- func GKey(args ...any) *Node
- func GLen(length int, spec ...any) *Node
- func GMax(max any, spec ...any) *Node
- func GMin(min any, spec ...any) *Node
- func GNever(spec ...any) *Node
- func GNullable(spec ...any) *Node
- func GOmit(names any, spec ...any) *Node
- func GOne(shapes ...any) *Node
- func GOpen(spec ...any) *Node
- func GOptional(spec ...any) *Node
- func GPartial(spec ...any) *Node
- func GPick(names any, spec ...any) *Node
- func GRefer(name string, spec ...any) *Node
- func GRename(name string, spec ...any) *Node
- func GRequired(spec ...any) *Node
- func GRest(child any, spec ...any) *Node
- func GSkip(spec ...any) *Node
- func GSome(shapes ...any) *Node
- func GTransform(fn func(val any, state *State) any, spec ...any) *Node
- func GType(kind any, spec ...any) *Node
- func GUrl(spec ...any) *Node
- func GUuid(spec ...any) *Node
- func Ignore(spec ...any) *Node
- func Ip(spec ...any) *Node
- func Ipv4(spec ...any) *Node
- func Ipv6(spec ...any) *Node
- func Key(args ...any) *Node
- func Len(length int, spec ...any) *Node
- func Max(max any, spec ...any) *Node
- func Min(min any, spec ...any) *Node
- func MustExpr(src string) *Node
- func Never(spec ...any) *Node
- func Nullable(spec ...any) *Node
- func Omit(names any, spec ...any) *Node
- func One(shapes ...any) *Node
- func Open(spec ...any) *Node
- func Optional(spec ...any) *Node
- func Partial(spec ...any) *Node
- func Pick(names any, spec ...any) *Node
- func Refer(name string, spec ...any) *Node
- func ReferWith(name string, opts ReferOptions, spec ...any) *Node
- func Rename(name string, spec ...any) *Node
- func RenameWith(name string, opts RenameOptions, spec ...any) *Node
- func Required(spec ...any) *Node
- func Rest(child any, spec ...any) *Node
- func Skip(spec ...any) *Node
- func Some(shapes ...any) *Node
- func Transform(fn func(val any, state *State) any, spec ...any) *Node
- func Type(kind any, spec ...any) *Node
- func Url(spec ...any) *Node
- func Uuid(spec ...any) *Node
- func (n *Node) Above(above any) *Node
- func (n *Node) After(fn func(val any, update *Update, state *State) bool) *Node
- func (n *Node) Any() *Node
- func (n *Node) Array() *Node
- func (n *Node) Before(fn func(val any, update *Update, state *State) bool) *Node
- func (n *Node) Below(below any) *Node
- func (n *Node) Boolean() *Node
- func (n *Node) Catch(fallback any) *Node
- func (n *Node) Check(check any) *Node
- func (n *Node) Child(child any) *Node
- func (n *Node) Closed() *Node
- func (n *Node) Coerce() *Node
- func (n *Node) Date() *Node
- func (n *Node) DateTime() *Node
- func (n *Node) Default(dval any) *Node
- func (n *Node) Define(name string) *Node
- func (n *Node) Describe(description string) *Node
- func (n *Node) Email() *Node
- func (n *Node) Empty() *Node
- func (n *Node) Exact(vals ...any) *Node
- func (n *Node) Extend(extra any) *Node
- func (n *Node) Fault(msg string) *Node
- func (n *Node) Func() *Node
- func (n *Node) Function() *Node
- func (n *Node) Ignore() *Node
- func (n *Node) Inner() *node
- func (n *Node) Integer() *Node
- func (n *Node) Ip() *Node
- func (n *Node) Ipv4() *Node
- func (n *Node) Ipv6() *Node
- func (n *Node) JSONSchema() map[string]any
- func (n *Node) Kind() Kind
- func (n *Node) Len(length int) *Node
- func (n *Node) Max(max any) *Node
- func (n *Node) Meta() map[string]any
- func (n *Node) Min(min any) *Node
- func (n *Node) Never() *Node
- func (n *Node) Nullable() *Node
- func (n *Node) Number() *Node
- func (n *Node) Object() *Node
- func (n *Node) Omit(names any) *Node
- func (n *Node) Open() *Node
- func (n *Node) Optional() *Node
- func (n *Node) Partial() *Node
- func (n *Node) Pick(names any) *Node
- func (n *Node) Refer(name string) *Node
- func (n *Node) Rename(name string) *Node
- func (n *Node) Required() *Node
- func (n *Node) Rest(child any) *Node
- func (n *Node) Skip() *Node
- func (n *Node) Transform(fn func(val any, state *State) any) *Node
- func (n *Node) Type(kind any) *Node
- func (n *Node) Url() *Node
- func (n *Node) Uuid() *Node
- type ReferOptions
- type RenameOptions
- type Schema
- func (s *Schema) Error(input any) []FieldError
- func (s *Schema) JSON() (out any, err error)
- func (s *Schema) JSONSchema() map[string]any
- func (s *Schema) Match(input any) bool
- func (s *Schema) Node() *node
- func (s *Schema) Spec() any
- func (s *Schema) Standard() StandardSchema
- func (s *Schema) String() string
- func (s *Schema) Valid(input any) bool
- func (s *Schema) Validate(input any) (any, error)
- func (s *Schema) ValidateCtx(input any, ctx *Context) (any, error)
- func (s *Schema) ValidateInto(input any, out any) error
- type ShapeOptions
- type StandardIssue
- type StandardResult
- type StandardSchema
- type State
- type TypeToken
- type Update
- type ValExprOptions
- type ValidationError
Constants ¶
const ( WhyType = "type" WhyRequired = "required" WhyClosed = "closed" WhyCheck = "check" WhyOne = "One" WhySome = "Some" WhyAll = "All" WhyExact = "Exact" WhyMin = "Min" WhyMax = "Max" WhyAbove = "Above" WhyBelow = "Below" WhyLen = "Len" WhyNever = "never" WhyRegexp = "regexp" WhyEmpty = "empty" WhyEmail = "Email" WhyUrl = "Url" WhyUuid = "Uuid" WhyDateTime = "DateTime" WhyIp = "Ip" WhyIpv4 = "Ipv4" WhyIpv6 = "Ipv6" WhyDiscriminated = "Discriminated" )
Why codes mirror the TS implementation's why values.
const Version = "0.5.3"
Variables ¶
var ( GAny = Any GString = String GNumber = Number GBoolean = Boolean GObject = Object GArray = Array GFunction = Function GInteger = Integer GDate = Date )
G-prefixed aliases. Provided for users who want to dot-import the package without colliding with stdlib builtins (e.g. String/Number/Boolean tokens).
var ( Any = TypeToken{/* contains filtered or unexported fields */} String = TypeToken{/* contains filtered or unexported fields */} Number = TypeToken{/* contains filtered or unexported fields */} Boolean = TypeToken{/* contains filtered or unexported fields */} Object = TypeToken{/* contains filtered or unexported fields */} Array = TypeToken{/* contains filtered or unexported fields */} Function = TypeToken{/* contains filtered or unexported fields */} Integer = TypeToken{/* contains filtered or unexported fields */} // a number with no fractional part Date = TypeToken{/* contains filtered or unexported fields */} // a time.Time value )
Sentinel tokens for required fields (TS constructor-literal equivalent).
var Null any = nullT{}
Null is an explicit present null. Go cannot tell a missing argument from a nil one, so Validate(nil) means "no value supplied" (JS undefined) and defaults fill, mirroring TS Shape(x)(). Validate(Null) means the value is present and null (JS null), which is a type error against a typed shape. Inside a map or slice a plain nil already reads as present-null, because the key or index exists; Null is accepted there too and means the same thing.
Functions ¶
func FromJSONSchema ¶ added in v0.3.0
FromJSONSchema builds a spec from a JSON Schema document, as decoded by encoding/json (map[string]any, []any, float64, bool, string, nil). Compile it with Shape, or compose it further with the builders.
func MustFromJSONSchema ¶ added in v0.3.0
MustFromJSONSchema is FromJSONSchema, panicking on error.
Types ¶
type Argu ¶
type Argu struct {
// contains filtered or unexported fields
}
Argu is a positional-arguments validator returned from MakeArgu.
func MakeArgu ¶
MakeArgu creates an Argu validator with the given namespace name. Use the returned value to validate positional arguments against an ordered spec.
Argu := MakeArgu("mylib")
argmap, err := Argu([]any{2, "x"}, "foo", map[string]any{
"a": Number,
"b": String,
})
// argmap == map[string]any{"a": 2, "b": "x"}
Spec values may be type tokens, literal defaults, or builder *Node values. Skip(spec) makes a slot optional with positional shifting; Rest(spec) tail- captures remaining args into a slice.
type Context ¶
type Context struct {
Err []FieldError
Custom map[string]any
Refs map[string]*node
Match bool
// contains filtered or unexported fields
}
Context flows through validation. Custom validators may read/write Custom for cross-property state, and Refs is used by Define/Refer.
type FieldError ¶
type FieldError struct {
Path string // dot-notation property path (e.g. "users.0.email")
PathArr []any // path as array: array indices as ints, keys as strings
Key string // the immediate key/index that failed
Type Kind // node kind that ran the check
Value any // failing input value
Why string // why-code (type, required, closed, check, ...)
Mark int // numeric mark (mirrors TS marks 1010, 4000, ...)
Text string // human-readable message
Args map[string]any // extra context for custom checks
Check string // name of the failing check (TS ErrDesc.check)
// contains filtered or unexported fields
}
FieldError captures rich information about a single validation failure.
func (FieldError) Error ¶
func (e FieldError) Error() string
type KeyExprOptions ¶
type KeyExprOptions struct {
// Disable turns key-expression parsing off (default is on).
Disable bool
}
KeyExprOptions controls key-expression parsing.
type Kind ¶
type Kind string
Kind identifies a normalized schema/value kind.
const ( KindAny Kind = "any" KindString Kind = "string" KindNumber Kind = "number" KindBoolean Kind = "boolean" KindObject Kind = "object" KindArray Kind = "array" KindNull Kind = "null" KindNaN Kind = "nan" KindFunction Kind = "function" KindNever Kind = "never" KindCheck Kind = "check" KindRegexp Kind = "regexp" KindInteger Kind = "integer" KindDate Kind = "date" KindList Kind = "list" )
type MetaOptions ¶
MetaOptions controls metadata sidecar keys (e.g. "x$$" providing meta for "x").
type Node ¶
type Node struct {
// contains filtered or unexported fields
}
Node is the publicly exposed compiled-spec wrapper. Builders return *Node so users can chain (e.g. shape.Min(2, shape.String).Required()).
func Catch ¶ added in v0.2.0
Catch replaces whatever fails inside with the fallback, raising nothing.
func Check ¶
Check installs a custom validation. Accepts a function of (val, update, state) or a *regexp.Regexp.
func Coerce ¶ added in v0.2.0
Coerce converts the value to the node's kind where the conversion is unambiguous, before the type check: a decimal string to a number, "true"/"false"/"1"/"0" to a boolean, a number or boolean to a string, an ISO 8601 string or a time value to a Date. Anything else is left alone, so the usual type error speaks.
func DateTime ¶ added in v0.2.0
DateTime accepts a strict ISO 8601 / RFC 3339 date-time string. The value stays a string; Coerce(Date) is the one that produces a time.Time.
func Discriminated ¶ added in v0.2.0
Discriminated chooses the branch by the value of the tag property. An object-shaped branch without the tag property has it added, as the literal it is keyed by.
func Email ¶ added in v0.2.0
Email accepts a string in email address form: a dot-atom local part and a dotted domain (no quoted local parts or address literals).
func Expr ¶
Expr parses a string DSL into a *Node spec, mirroring TS Shape.expr.
Supported tokens:
- Builder names: Required, Optional, Min, Max, Above, Below, Len, Check, Open, Closed, Skip, Ignore, Empty, Default, Fault, Never, Type, Exact, One, Some, All, Child, Rest, Define, Refer, Rename, Func, Key.
- Type tokens: String, Number, Boolean, Object, Array, Function, Any.
- Literals: JSON values (numbers, strings, true, false, null) and undefined/NaN.
- Regexp: /pattern/.
- Method chaining via dot: "String.Min(2).Max(10)".
- Comma-separated args inside parentheses: "Min(2, String)".
func Extend ¶ added in v0.2.0
Extend adds the properties of extra, an object shape, to an object shape. The result is a new node; the source is unchanged.
func Func ¶
Func declares a function-typed value (best-effort: any reflect.Func value). It is a builder, not a type token, so it does not require a value of itself: TS Func() leaves the node optional, and { n: Func() } accepts an object without n. The Function token is the required form.
func GDiscriminated ¶ added in v0.2.0
func GNullable ¶ added in v0.2.0
G-prefixed aliases for the builders added since v10, for a dot-import.
func GTransform ¶ added in v0.2.0
func Key ¶
Key replaces the value with the validation key (or path slice).
- Key() → uses the immediate parent key as the value.
- Key(depth) → reads `depth` levels up the path.
- Key(depth, sep) → joins the path slice with sep into a string.
func Nullable ¶ added in v0.2.0
Nullable accepts an explicit null as the value. Whether the value may be absent is still governed by Required/Optional.
func Omit ¶ added in v0.2.0
Omit drops the named properties of an object shape. names is a string or a list of strings. The result is a new node; the source is unchanged.
func Partial ¶ added in v0.2.0
Partial makes every declared property of an object shape optional. The result is a new node; the source is unchanged.
func Pick ¶ added in v0.2.0
Pick keeps only the named properties of an object shape. names is a string or a list of strings. The result is a new node; the source is unchanged.
func ReferWith ¶
func ReferWith(name string, opts ReferOptions, spec ...any) *Node
ReferWith is Refer with explicit options.
func RenameWith ¶
func RenameWith(name string, opts RenameOptions, spec ...any) *Node
RenameWith is Rename with explicit options (Keep, Claim).
func Required ¶
Required marks the value as required. Single-arg form Required(spec) wraps an existing spec; zero-arg Required() yields a required Any.
func Transform ¶ added in v0.2.0
Transform replaces a valid value with a function of it. An invalid one fails as it would have, with the same errors.
func Url ¶ added in v0.2.0
Url accepts an absolute URL: scheme://host with optional user, port, path, query and fragment.
func (*Node) Define ¶ added in v0.2.0
Define (chained): name this node so a later Refer can clone it.
func (*Node) Extend ¶ added in v0.2.0
Extend (chained): returns a new node, leaving the receiver as it was.
func (*Node) Inner ¶
func (n *Node) Inner() *node
Inner exposes the underlying private node for advanced introspection.
func (*Node) JSONSchema ¶ added in v0.2.0
JSONSchema renders a built node as a JSON Schema document.
func (*Node) Meta ¶ added in v0.2.0
Meta returns the node's metadata: sidecar keys, and Describe's description.
func (*Node) Omit ¶ added in v0.2.0
Omit (chained): returns a new node, leaving the receiver as it was.
func (*Node) Partial ¶ added in v0.2.0
Partial (chained): returns a new node, leaving the receiver as it was.
func (*Node) Pick ¶ added in v0.2.0
Pick (chained): returns a new node, leaving the receiver as it was.
type ReferOptions ¶
type ReferOptions struct {
// Fill substitutes even when the value is absent (not for self-recursion).
Fill bool
// Strict makes a name with no Define an error, rather than a Refer that
// does nothing.
Strict bool
}
ReferOptions controls Refer behaviour. Fill substitutes the referenced node even when the input value is missing/nil, allowing recursive structure.
type RenameOptions ¶
RenameOptions controls Rename behaviour.
- Keep: retain the original key in addition to writing under the new name.
- Claim: list of alternative source keys to read from when the renamed key is missing on the input. Useful for migrating legacy property names.
type Schema ¶
type Schema struct {
// contains filtered or unexported fields
}
Schema is a compiled shape specification.
func Build ¶
Build reads the declarative JSON of a shape, what JSON() writes: every string is an expression (the example of a key expression is a value, so a string there is the string itself), and a "$$" key applies an expression to the object that holds it, with the "$$0", "$$1", ... sidecars beside it as the arguments an expression cannot spell inline.
func MustShapeWith ¶
func MustShapeWith(spec any, opts ShapeOptions) *Schema
MustShapeWith is ShapeWith that panics on error.
func Shape ¶
Shape compiles a schema-by-example specification with default options. Note: keyexpr is enabled by default — keys like "x: Min(1)" are parsed.
func ShapeWith ¶
func ShapeWith(spec any, opts ShapeOptions) (*Schema, error)
ShapeWith compiles a schema-by-example specification with the given options.
func (*Schema) Error ¶
func (s *Schema) Error(input any) []FieldError
Error returns the FieldErrors produced by validating input. Returns nil if the input is valid.
func (*Schema) JSON ¶ added in v0.5.1
JSON is the declarative JSON of the shape, which Build reads back.
func (*Schema) JSONSchema ¶ added in v0.2.0
JSONSchema renders the schema as a JSON Schema document.
func (*Schema) Match ¶
Match reports whether input satisfies the schema, without mutating input or returning errors. Mirrors TS .match().
func (*Schema) Node ¶
func (s *Schema) Node() *node
Node returns the underlying root node for advanced introspection.
func (*Schema) Standard ¶ added in v0.1.3
func (s *Schema) Standard() StandardSchema
Standard returns the Standard Schema V1-style interface for this schema. The returned Validate never panics; it reports failures as issues.
func (*Schema) Validate ¶
Validate validates and normalizes input. Returns the produced (defaults injected) value plus a *ValidationError if any errors occurred.
func (*Schema) ValidateCtx ¶
ValidateCtx is Validate with an explicit Context (custom validators may use it).
type ShapeOptions ¶
type ShapeOptions struct {
KeyExpr KeyExprOptions
Meta MetaOptions
ValExpr ValExprOptions
}
ShapeOptions configures schema compilation. Mirrors TS ShapeOptions.
Defaults:
- KeyExpr.Active = true (interpret object keys like "x: Min(1)")
- Meta.Active = false (sidecar metadata via "x$$" keys)
- Meta.Suffix = "$$"
- ValExpr.Active = false (string values become builder expressions)
- ValExpr.KeyMark = "$$"
type StandardIssue ¶ added in v0.1.3
StandardIssue mirrors a Standard Schema V1 issue: a human-readable message and the path to the offending value (array indices as ints, object keys as strings, matching FieldError.PathArr).
type StandardResult ¶ added in v0.1.3
type StandardResult struct {
Value any // produced value (defaults injected) when Issues is empty
Issues []StandardIssue // validation problems; empty on success
}
StandardResult is the outcome of StandardSchema.Validate: on success Value is set and Issues is empty; on failure Issues is populated. Mirrors the TS `~standard.validate()` result.
type StandardSchema ¶ added in v0.1.3
type StandardSchema struct {
Version int // always 1
Vendor string // always "shape"
Validate func(input any) StandardResult // non-throwing validation
}
StandardSchema is the Standard Schema V1-style interface for a compiled shape.
type State ¶
type State struct {
Path []string // path stack from root; current key at end
PathArr []any // path as array: array indices as ints, object keys as strings
Key string // immediate key/index name
Value any // current value being validated
Node *node // current node
Parent any // parent map/slice (for Rename and similar)
Match bool // true when invoked via .Match (no mutation, no error report)
Ctx *Context // user/custom context
// contains filtered or unexported fields
}
State is passed to custom validators and tracks the current validation cursor.
type TypeToken ¶
type TypeToken struct {
// contains filtered or unexported fields
}
TypeToken marks a required type in schema-by-example maps.
type Update ¶
type Update struct {
Done bool // stop running further checks
Why string // why code on failure
Mark int // numeric mark on failure
Err any // string, FieldError, or []FieldError
Val any // replacement value
HasVal bool // true if Val should override
Node *node // override node (used by Refer)
Replace bool // (compat marker, not currently consulted)
}
Update is the bag a custom validator fills in to influence validation.
type ValExprOptions ¶
ValExprOptions controls value-as-expression parsing.
type ValidationError ¶
type ValidationError struct {
Issues []FieldError
// contains filtered or unexported fields
}
ValidationError aggregates one or more FieldErrors. A terse one, the collector of a Match, only counts them.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string