Skip to content

rune ​

@c9up/rune: validation: fluent rule chains, object schemas with inferred types, transforms, custom and async rules, database rules, file checks, error messages and JSON Schema output, run by a native Rust engine. Guide: Validating input.

Installation ​

bash
pnpm add @c9up/rune

The native engine comes as one small package per platform, @c9up/rune-<platform>, for linux x64 and arm64 (glibc), macOS x64 and arm64, and Windows x64. @c9up/rune lists them as optional dependencies, and your package manager installs only the one that matches your machine. No Rust toolchain is needed. Do not install with optional dependencies turned off (--no-optional, --omit=optional): the engine would be left out.

A schema the engine can run is run by it or not at all: without the engine, it throws E_RUNE_NAPI_REQUIRED, and its message names the package to install, for example @c9up/rune-linux-x64-gnu. Custom rules, a translator and a messages provider run in TypeScript.

Entry points ​

ImportContents
@c9up/runerune (default export), rules, schema, create, compile, rule factories, global bindings, errors, types
@c9up/rune/typesThe types only
@c9up/rune/errorsThe error classes, one per code, and RuneErrorNode
@c9up/rune/defaultsThe default message templates
@c9up/rune/testingrunRule, runRuleAsync, fieldContext, to test a custom rule

Exports ​

@c9up/rune ​

ExportKindDescription
defaultconstrune: every rules factory plus schema, create, compile, createRule, createAsyncRule, group, the bind* and set* functions, helpers, validate, tryValidate, withMetaData, and the errorReporter, messagesProvider and convertEmptyStringsToNull properties
rulesconstThe type factories that start a chain (see below)
schemafunctionschema<S extends Record<string, RuleChain>>(fields: S, rootChain?: RuleChain): ValidationSchema<Infer<S>>
createfunctioncreate<S extends Record<string, RuleChain>>(fields: S): ValidationSchema<Infer<S>>, or create<C extends RuleChain>(chain: C): ValidationSchema<OutputOf<C>>
compilefunctionSame as create; returns a ValidationSchema given one unchanged
createRulefunctioncreateRule<Options>(validator: RuleValidator<Options>, options?: CreateRuleOptions): (options: Options) => CompiledRule; an async validator or { isAsync: true } gives an AsyncCompiledRule
createAsyncRulefunctioncreateAsyncRule<Options>(validator: AsyncRuleValidator<Options>, options?): (options: Options) => AsyncCompiledRule
bindDatabasefunctionbindDatabase(resolver: DatabaseResolver | null): void, the lookup behind unique() and exists()
bindFileReaderfunctionbindFileReader(reader: FileContentReader | null): void, how verifyContent reads an upload
bindHostResolverfunctionbindHostResolver(resolver: HostResolver | null): void, the DNS check behind activeUrl()
bindRosettafunctionbindRosetta(rosetta: { t(key, params?): string }): void, messages from a translator
setValidationTranslatorfunctionsetValidationTranslator(translator?: ValidationTranslator): void
setGlobalErrorReporterfunctionsetGlobalErrorReporter(reporter: ErrorReporterFactory | ((error: ValidationErrorNode) => void) | null): void
setConvertEmptyStringsToNullfunctionsetConvertEmptyStringsToNull(enabled: boolean): void; "" then reads as absent
setDateTransformfunctionsetDateTransform(fn: ((value: Date) => unknown) | null): void, what a validated date becomes
SimpleMessagesProviderclassnew SimpleMessagesProvider(messages: Record<string, string>, fields?: Record<string, string>)
SimpleErrorReporterclassnew SimpleErrorReporter(): collects each failure as a ValidationErrorNode, { hasErrors, errors, report(message, rule, field, meta?), createError() }; pass errorReporter: () => new SimpleErrorReporter() or extend it
ValidationErrorclassThe validation exception under its class name: the same class as errors.E_VALIDATION_ERROR
readHeadfunctionreadHead(path: string, length?: number): Promise<Uint8Array>, the first bytes of a file (32 by default), for content checks
isNativeAvailablefunctionisNativeAvailable(): boolean
assertNativeAvailablefunctionassertNativeAvailable(): void; throws E_RUNE_NAPI_REQUIRED
errorsnamespaceThe package's errors, one class per code, see Errors; the same as @c9up/rune/errors

Types (also in @c9up/rune/types):

ExportKindDescription
ValidationSchemainterfaceA validator (see below)
RuleChaintypeA chain of rules (see below)
InfertypeInfer<S>, the output type of a shape
ValidationResulttype{ valid: true; errors; data: T } | { valid: false; errors; data?: undefined }
ValidationErrorNodeinterface{ field, rule, message, index?, meta? }, one failure
ValidateOptionsinterface{ meta?, messagesProvider?, errorReporter? }
FieldContextinterfaceWhat a rule receives: value, data, parent, field, meta, name, wildCardPath, isValid, isDefined, isArrayMember, isValidDataType, getFieldPath(), mutate(value), report(message, rule, field, args?)
RuleValidatortype(value: unknown, options: Options, field: FieldContext) => void
AsyncRuleValidatortypeThe same, returning void | Promise<void>
CompiledRule, AsyncCompiledRuleinterfaceWhat createRule returns; passed to use() / useAsync()
CreateRuleOptionsinterface{ implicit?, name?, toJSONSchema?, isAsync?, async? }
ValidationMessageParamstypeRecord<string, string | number | boolean>
ValidationTranslatortype(key: string, params?) => string | undefined
MessagesProviderContractinterface{ getMessage(rawMessage, rule, field: MessageFieldContext, args?): string }
MessageFieldContextinterfaceThe field a message is for
DatabaseResolverinterface{ exists(query: DatabaseLookup): Promise<boolean> }
DatabaseLookupinterface{ table, column, value, where?, whereNot?, … }
DatabaseRuleOptionsinterface{ table, column?, where?, whereNot? }
FileLikeinterface{ size, type?, content?, buffer?, extname?, clientName?, name?, … }
FileContentReadertype(file: FileLike) => Uint8Array | null | Promise<Uint8Array | null>
UnionNoMatchCallbacktype(value: unknown, field: FieldContext) => void
RecordKeysCallbacktype(keys: string[], field: FieldContext) => void
DateFormattype'iso8601' | 'x' | 'X' | string
AlphaOptions, EmailOptions, UrlOptions, NormalizeEmailOptions, NormalizeUrlOptionsinterfaceOptions of alpha(), email(), url(), normalizeEmail(), normalizeUrl()

@c9up/rune/types also exports ConditionalBranch, ConditionalGroup, ErrorReporterContract, ErrorReporterFactory, HostResolver, JsonSchemaModifier, ParseContext, RuleDef, SchemaIntrospection, UnionBranch, MessageArgs, ValidationFields and ValidationMessages.

rules ​

FactorySignatureStarts
stringstring(): RuleChain<string>A string
numbernumber(options?: { strict?: boolean }): RuleChain<number>A number; a numeric string is accepted unless strict
booleanboolean(options?: { strict?: boolean }): RuleChain<boolean>A boolean; 'true', 'false', 'on', 'off', '1', '0', 1 and 0 are accepted unless strict
datedate(options?: { formats?: DateFormat[] }): RuleChain<Date>A date
acceptedaccepted(): RuleChain<true>A checked checkbox
anyany(): RuleChain<unknown>Any value
literalliteral(value: string | number | boolean): RuleChain<V>Exactly value
enumenum(values | ((field) => values) | nativeEnum): RuleChainOne of the values
objectobject(shape: Record<string, RuleChain>): RuleChain<Infer<Sh>>An object of that shape
arrayarray(item?: RuleChain): RuleChain<T[]>An array
recordrecord(valueChain: RuleChain): RuleChain<Record<string, T>>An object with any keys
tupletuple(items: readonly RuleChain[]): RuleChainA fixed-length array
unionunion(branches: readonly UnionBranch[]): RuleChain; union.if(predicate, chain), union.else(chain)The first branch whose predicate is true, else the union.else branch, else the value is refused (union)
unionOfTypesunionOfTypes(chains: readonly RuleChain[]): RuleChainThe branch whose type matches
optionaloptional(): RuleChain<undefined>Absent only
nullnull(): RuleChain<null>null only
filefile(options?: { size?; extnames?; verifyContent? }): RuleChain<FileLike>An uploaded file
nativeFilenativeFile(options?: { minSize?; maxSize?; mimeTypes? }): RuleChain<FileLike>A File / Blob

rune.group(branches) with group.if(predicate, shape) and group.else(shape) adds fields to an object depending on the data. When no branch applies, the object is refused (unionGroup). group(...).otherwise(callback) and union(...).otherwise(callback) take a UnionNoMatchCallback that decides instead.

RuleChain ​

Every method returns the chain it is called on, except optional, nullable, nullish, transform and clone, which return a new chain and leave theirs unchanged. A validator keeps its own copy of its chains when it is built. The Rules guide describes each method.

GroupMethods
Presenceoptional, nullable, nullish, requiredWhen, requiredIfExists, requiredIfMissing, bail
StringsminLength, maxLength, fixedLength, min, max, regex, email, url, activeUrl, alpha, alphaNumeric, ascii, hexCode, uuid, ulid, jwt, ipAddress, creditCard, iban, coordinates, passport, postalCode, mobile, vat, startsWith, endsWith, sameAs, notSameAs, confirmed, in, notIn
Numbersmin, max, range, positive, negative, nonNegative, nonPositive, decimal, withoutDecimals
Datesequals, after, before, afterOrEqual, beforeOrEqual, afterField, beforeField, afterOrSameAs, beforeOrSameAs, weekday, weekend
Arrays, records, objectsminLength, maxLength, fixedLength, notEmpty, distinct, compact, validateKeys, allowUnknownProperties, denyUnknownProperties, merge, partial, pick, omit, toCamelCaseKeys, getProperties, getChoices, otherwise
FilesminSize, maxSize, mimeTypes, verifyContent
Databaseunique(options: DatabaseRuleOptions | callback), exists(options | callback)
Before the rulesparse (first, on the raw input), then trim, escape, toLowerCase, toUpperCase, toCamelCase, normalizeEmail, normalizeUrl (after the type rule)
After the rulestransform(fn): runs last, on the validated value of a valid payload
Custom rulesuse(rule: CompiledRule), useAsync(rule: AsyncCompiledRule), custom(name: string, validate: (value: unknown) => boolean, message?: string)
Messages and schemamessage(text), meta(object), clone

ValidationSchema ​

MemberSignatureDescription
validatevalidate(data: unknown, options?: ValidateOptions): Promise<T>The validated data; throws errors.E_VALIDATION_ERROR
tryValidatetryValidate(data: unknown, options?): Promise<[errors.E_VALIDATION_ERROR, null] | [null, T]>Never throws on invalid data
tryValidateSynctryValidateSync(data: unknown, options?): [errors.E_VALIDATION_ERROR, null] | [null, T]
validateResultvalidateResult(data: unknown, options?): ValidationResult<T>Synchronous; throws only for a schema with async rules (E_RUNE_ASYNC_RULE_NOT_AWAITED)
validateResultAsyncvalidateResultAsync(data: unknown, options?): Promise<ValidationResult<T>>
validateOrThrowvalidateOrThrow(data: unknown, options?): TSynchronous, throws errors.E_VALIDATION_ERROR
validateOrThrowAsyncvalidateOrThrowAsync(data: unknown, options?): Promise<T>
fieldsfields: Record<string, RuleChain>The shape the validator was built from
schemaschema: RuleChainThe chain the validator was built from, for partial(), pick(), omit(); changing it does not change the validator
errorReportererrorReporter: ErrorReporterFactory | ((error) => void) | nullThis validator's reporter
messagesProvidermessagesProvider: MessagesProviderContract | nullThis validator's messages; a per-call option wins
toJSONtoJSON(): { schema: SchemaIntrospection; refs: string[] }Introspection
toJSONSchematoJSONSchema(): Record<string, unknown>JSON Schema of the accepted shape
~standardStandard Schema v1For libraries that accept any Standard Schema

rune.validate({ schema, data, ...options }) and rune.tryValidate(...) validate once without keeping a validator. rune.withMetaData<M>(check?) returns { create, compile } whose validators require { meta }.

@c9up/rune/errors ​

ExportKindDescription
E_VALIDATION_ERRORerrornew E_VALIDATION_ERROR(messages: RuneErrorNode[], options?: ErrorOptions): code E_VALIDATION_ERROR, status 422, messages
E_RUNE_*errorOne class per code of the table below; an advice to fix it is on help
RuneErrorNodeinterface{ message, rule, field, index?, meta? }

@c9up/rune/defaults ​

ExportKindDescription
messagesconstRecord<string, string>, the default template of each rule ('array.minLength'…), interpolated with {{ field }} and the rule's arguments
fieldsconst{ '': 'data' }, the label of the root
requiredMessageconst'The {{ field }} field must be defined'

@c9up/rune/testing ​

ExportKindDescription
runRulefunctionrunRule(rule: CompiledRule | AsyncCompiledRule, value: unknown, options?: FieldContextOptions): RuleRunResult
runRuleAsyncfunctionrunRuleAsync(rule, value, options?): Promise<RuleRunResult>
fieldContextfunctionfieldContext(value: unknown, options?: FieldContextOptions): FieldContext
RuleRunResultinterface{ valid: boolean; errors: ValidationErrorNode[]; value: unknown }
FieldContextOptionsinterface{ path?, data?, parent?, … }
ts
import { runRule } from '@c9up/rune/testing'

const result = runRule(isEven(), 3)
result.valid             // false
result.errors[0]?.rule   // 'isEven'

Errors ​

CodeRaised when
E_VALIDATION_ERRORThe data is invalid (422)
E_RUNE_META_REQUIREDA withMetaData() validator was called without { meta }
E_RUNE_NOT_A_REGULAR_FILEA file() value is not a regular file
E_RUNE_INVALID_SIZEA file size option cannot be read
E_RUNE_INVALID_ERROR_REPORTERAn errorReporter factory did not return a reporter
E_RUNE_INVALID_RULEuse() got something other than a compiled rule
E_RUNE_NO_RULEmessage() was called before any rule
E_RUNE_NOT_AN_OBJECTmerge() or another shape method was called on a chain that is not an object()
E_RUNE_PARTIAL_NOT_APPLICABLEpartial() on a shape with groups or allowUnknownProperties()
E_RUNE_NO_TYPE_RULEA unionOfTypes() branch declares no type
E_RUNE_DUPLICATE_UNION_TYPETwo unionOfTypes() branches declare the same type
E_RUNE_ASYNC_RULE_NOT_AWAITEDA synchronous method met an async rule
E_RUNE_NO_DATABASE_RESOLVERunique() or exists() ran with no resolver bound and no callback
E_RUNE_NO_HOST_RESOLVERactiveUrl() ran with no host resolver bound
E_RUNE_UNSUPPORTED_LOCALEmobile() has no numbering plan for the locale
E_RUNE_UNSUPPORTED_COUNTRYpostalCode(), passport() or vat() has no pattern for the country
E_RUNE_CONFLICTING_URL_OPTIONSnormalizeUrl() was given both forceHttp and forceHttps
E_RUNE_UNSUPPORTED_JSON_SCHEMA_TARGETA JSON Schema target rune does not emit
E_RUNE_NO_OUTPUT_SCHEMAThe output shape cannot be described: a transform may produce anything
E_RUNE_NAPI_REQUIREDThe native engine is not loaded. The message names the package to install
E_RUNE_NAPI_NOT_FOUNDThe native engine binary is not found. The message names the package to install
E_RUNE_NAPI_REQUEST_REFUSEDThe native engine refused the request. A validator does not raise it: it validates that payload in TypeScript
E_RUNE_NAPI_INVALID_RESPONSEThe native engine answered an unexpected shape

Each one is a class of errors, a flare Exception: read error.code, or test error instanceof errors.E_VALIDATION_ERROR.

Migration ​

  • RuneValidationError is errors.E_VALIDATION_ERROR, which already existed as its alias: replace instanceof RuneValidationError with instanceof errors.E_VALIDATION_ERROR. Its name is now E_VALIDATION_ERROR.
  • RuneError is gone: each E_RUNE_* code is its own class. Test error.code, or instanceof errors.E_RUNE_UNSUPPORTED_COUNTRY and the like.
  • RuneNativeRequiredError is errors.E_RUNE_NAPI_REQUIRED.
  • The advice an error carried as hint is on help.
  • The ValidationError interface ({ field, rule, message, index?, meta? }) is now ValidationErrorNode: ValidationError is the exception class, the same as errors.E_VALIDATION_ERROR. Replace import type { ValidationError } with ValidationErrorNode where it typed a failure node.
  • SimpleErrorReporter is new.
  • url() and helpers.isURL() now refuse a value whose scheme is not in protocols even when no // follows it: javascript:…@host, myapp:host. The host is checked as validator.js checks it: its TLD must be two letters or more (http://example.c1 is now refused), and http://[::1] is now accepted. To accept another scheme, list it: url({ protocols: ['https', 'myapp'] }).
  • transform() now runs after the rules, on a valid payload, instead of before them. A rule no longer judges what the callback returns: number().max(100).transform((n) => n / 100) now refuses 5000. If you used transform() to prepare a value for the rules, use parse() instead: it runs before them.
  • optional(), nullable() and nullish() now return a new chain instead of changing the one they are called on. Use what they return: write const nickname = name.optional(), not name.optional() on a line of its own.
  • A validator now keeps its own copy of its chains when it is built. A rule added to a chain after create() or schema() no longer reaches that validator: build the validator after the chain is complete.
  • A union built with union.if() now refuses a value when no predicate is true and there is no union.else branch; it no longer tries the branches whose predicate was false. A group with no matching branch now refuses the object with unionGroup. Add a union.else(chain) or group.else(shape) branch, or an .otherwise(callback), to accept the other cases.
  • The items of an array, the values of a record, the positions of a tuple and the properties of an object are no longer validated when the container fails one of its own rules: the errors then list the container's rule only. Call .bail(false) on the container to validate them anyway.
  • requiredWhen(field, '<' | '>' | '<=' | '>=', n) now compares a numeric string as a number: the field becomes required for "17" < 18, as it already was for 17.
  • decimal() now refuses a number that JavaScript prints with an exponent (1e-7, 1e21).
  • On a number() or boolean() chain, sameAs(), notSameAs() and confirmed() now coerce the other field before comparing: "7" and 7 are the same value. distinct() does the same for the items of array(number()), and distinct('id') holds "7" and 7 as one value.

See also ​