npm.io
1.23.0 • Published yesterday

runcheck

Licence
MIT
Version
1.23.0
Deps
0
Size
586 kB
Vulns
0
Weekly
0

Runcheck

A lib for js/typescript runtime type checks with autofix support. Runcheck has the goal of being very lightweight and fast . Because of that, it has only around 2.9kb Gzipped (at v0.30), has no dependencies and is tree-shakeable!

Installation

pnpm add runcheck

Basic types:

runcheck type ts type equivalent
rc_string string
rc_number number
rc_coerce_number number (coerces numeric strings)
rc_coerce_string string (coerces numbers)
rc_coerce_boolean boolean (coerces boolean like inputs)
rc_coerce_date Date (coerces date strings and epoch numbers)
rc_boolean boolean
rc_any any
rc_unknown unknown
rc_null null
rc_undefined undefined
rc_date Date
rc_instanceof(instance: T) Classes typecheck in general
rc_literals(...literals: T[]) Type literal in general like hello, true, 1
rc_string_starts_with(p) `${p}${string}`
rc_string_ends_with(s) `${string}${s}`
rc_string_contains(s) `${string}${s}${string}`
rc_union(...types: T[]) Union types in general like string | 1
rc_array<T>(type: T) T[]
rc_loose_array<T>(type: T) T[] (filters invalid items)
rc_tuple<T>(...types: T[]) [T, T]
rc_record<T>(type: T) Record<string, T>
rc_loose_record<T>(type: T) Record<string, T> (filters invalid values)
rc_intersection(...types: T[]) Intersection types like {a:string} & {b:string}
rc_readonly<T>(type: T) Readonly<T>, e.g. readonly T[]

rc_readonly

Marks the inferred type of a schema as Readonly, so it matches readonly arrays, tuples and objects without a transform. It is type-only: parsing is unchanged and the result is not frozen.

type RecordsSort = readonly [string, 'asc' | 'desc']

const recordsSortSchema: RcType<RecordsSort> = rc_readonly(
  rc_tuple([rc_string, rc_literals('asc', 'desc')]),
)

rc_readonly(rc_array(rc_string)) // RcType<readonly string[]>
rc_readonly(rc_object({ a: rc_string })) // RcType<{ readonly a: string }>

Array types:

Array loose check

You can also use rc_loose_array to reject the wrong elements of an array and return the valid ones.

const shape = rc_loose_array(rc_string)

const input = ['hello', 1, 'world']

const result = rc_parse(input, shape)

// result.data will be ['hello', 'world']
// result.warnings will return the warnings about the invalid elements

Array length bounds

Use minLength and maxLength with rc_array, rc_loose_array, or rc_array_filter_from_schema:

const filters = rc_array(rc_string, { minLength: 1, maxLength: 10 })

filters.parse([]) // error: Array length must be at least 1 (got 0)
filters.optional().parse(undefined) // ok

Bounds are inclusive and apply to the parsed array, after filtering, loose item rejection, and duplicate removal in loose arrays. Strict arrays reject length violations. Loose arrays return the retained items with a warning, including when the result is empty or exceeds maxLength. This also applies to rc_array_filter_from_schema with loose: true. Disabling loose validation or using noWarnings: true makes length violations errors.

maxLength: Infinity means no upper bound. Bounds are used as supplied, without validating the configuration.

Checking unique values

With the rc_array or rc_loose_array type you can also use the unique option to check if the array has no duplicated values.

const shape = rc_array(rc_string, { unique: true })

For arrays of objects, you can provide a string to unique option to check if the array items has no duplicated values of a specific property.

const shape = rc_array(rc_object({ id: rc_string }), { unique: 'id' })

You can also provide a function to unique option to check if the array items has no duplicated values based on a custom function return.

const shape = rc_array(
  rc_object({ id: rc_string, meta_id: rc_string.optional() }),
  {
    unique: (item) => item.meta_id || item.id,
  },
)

Union errors

Simple unions such as string | number and literal unions keep a single compact type mismatch message. Plain type mismatches at the same property with the same received type are combined, for example: $.type: Type 'string(guest)' is not assignable to 'string(user) | string(admin)'. Other structured or custom failures retain property paths, member labels, and predicate errors. Deeper object failures (members that matched earlier properties) are reported first and never hidden by the default limit. Up to five other members are detailed; additional members are summarized. Every member is still checked for a match, regardless of this reporting limit.

Set unionErrorLimit per parse to change the limit, or use Infinity to show all members' errors in schema order without collapsing them, including simple type mismatches. The option also applies to nested unions and .or() schemas:

schema.parse(input, { unionErrorLimit: Infinity })
rc_parse(input, schema, { unionErrorLimit: 10 })
schema.parseJson(json, { unionErrorLimit: Infinity })

The limit counts shallow union members, not individual error messages. Use a positive integer or Infinity. By default, object members stop at their first invalid property. Infinity also disables that shortcut to report all object property errors within union members.

Object types:

rc_object

const shape = rc_object({
  name: rc_string,
  age: rc_number,
  isCool: rc_boolean,
  // nested objects
  address: {
    street: rc_string,
    number: rc_number,
  },
})

The rc_object will allow extra properties but any extra properties will be stripped in parsing. To allow extra properties in parsing, use rc_obj_extends.

Marking optional keys

Optional keys can be marked with the optionalKey() method.

const shape = rc_object({
  name: rc_string.optionalKey(),
  age: rc_number,
  isCool: rc_boolean,
})

/*
inferred type will be:
{
  name?: string | undefined,
  age: number,
  isCool: boolean,
}

instead of:
{
  name: string | undefined,
  age: number,
  isCool: boolean,
}
*/

rc_obj_strict

The same as rc_object but, any extra properties will be throw an error in parsing.

rc_obj_merge

Allow to merge two rc_object types. Example:

const shape = rc_obj_merge(
  rc_object({
    name: rc_string,
    age: rc_number,
    isCool: rc_boolean,
  }),
  rc_object({
    address: rc_string,
    phone: rc_string,
  }),
)

rc_record

Validates only the values of a object, equivalent to Record<string, T> in typescript.

const shape = rc_record(rc_number)

// shape type is `Record<string, number>`

// `rc_record` also accepts the following options:
const shape = rc_record(rc_number, {
  checkKey: (key) => key !== 'a', // Check if the key is valid
  looseCheck: true, // If true, the invalid keys will be striped
})

rc_loose_record

Validates only the values of a object, equivalent to Record<string, T> in typescript. But, it will reject invalid keys and return the valid ones.

const shape = rc_loose_record(rc_number)

Parsing

import { rc_parse } from 'runcheck'

const input = JSON.parse(jsonInput)

const parseResult = rc_parse(input, rc_array(rc_string))

if (parseResult.error) {
  throw new Error(parseResult.errors.join('\n'))
  // Errors are a array of strings
}

const result = parseResult.data
// Do something with result

You can also use rc_parser to create a reusable parser.

import { rc_parser } from 'runcheck'

const parser = rc_parser(rc_array(rc_string))

const parseResult = parser(jsonInput)
const parseResult2 = parser(jsonInput2)

Strict parsing

Use the strict option to disable autofix and fallback

const parseResult = rc_parse(
  input,
  // fallback will be ignored
  rc_array(rc_string).withFallback([]),
  {
    strict: true,
  },
)

Type assertion

Use rc_is_valid and rc_validator to do a simple type assertion.

import { rc_is_valid } from 'runcheck'

const input = JSON.parse(jsonInput)

if (rc_is_valid(input, rc_array(rc_string))) {
  // input will be inferred by ts as `string[]`
}

Type assertion in a parse result

Use rc_assert_is_valid to do a simple type assertion in a parse result.

import { rc_assert_is_valid } from 'runcheck'

const input = JSON.parse(jsonInput)

const result = rc_parse(input, rc_array(rc_string))

rc_assert_is_valid(result)
// will throw an error if the result is invalid, otherwise will narrow the result type to a valid result

Loose parsing

You can now use the result methods unwrapOr and unwrapOrNull for more convenient loose parsing:

import { rc_parse } from 'runcheck'

const input = JSON.parse(jsonInput)

// Using unwrapOr method
const result = rc_parse(input, rc_array(rc_string)).unwrapOr([])
// will fallback to [] if the input is invalid

// Using unwrapOrNull method
const result2 = rc_parse(input, rc_array(rc_string)).unwrapOrNull()
// will fallback to null if the input is invalid

Strict parsing

You can use the unwrap() method directly on the parse result:

import { rc_parse, RcValidationError } from 'runcheck'

const input = JSON.parse(jsonInput)

try {
  const result = rc_parse(input, rc_array(rc_string)).unwrap()
  // result will be the parsed data or throw RcValidationError
} catch (error) {
  if (error instanceof RcValidationError) {
    // handle error
  }
}

Autofixing and fallback values in parsing

Values can be autofixed and fallback values can be provided for parsing. The checks will pass but the result will return warnings messages.

type SuccessResult = {
  error: false
  data: T
  warnings: string[] | false
}

Fallback

Use the method rc_[type].withFallback(fallback) to provide a fallback value if the input is not valid.

const input = 'hello'

const result = rc_parse(input, rc_string.withFallback('world'))

AutoFix

You can also use rc_[type].autoFix() to automatically fix the input if it is not valid.

const input = 1

const result = rc_parse(
  input,
  rc_string.autoFix((input) => input.toString()),
)

There are also some predefined autofixed types that you can import:

import {
  rc_string_autofix,
  rc_boolean_autofix,
  rc_number_autofix,
} from 'runcheck/autofixable'

// use like any other type
Autofix type Equivalent to Autofixes
rc_boolean_autofix boolean 0 | 1 | 'true' | 'false' | null | undefined
rc_string_autofix string valid number inputs
rc_number_autofix number valid numeric string inputs

Coerce types

If loose inputs are expected instead of being errors, use the coerce types. Unlike autofix, they coerce inputs without emitting warnings and also work in noWarnings mode:

import { rc_coerce_number, rc_coerce_string } from 'runcheck'

rc_parse('12', rc_coerce_number) // { data: 12, warnings: false }
rc_parse(12, rc_coerce_string) // { data: '12', warnings: false }
Coerce type Equivalent to Coerces
rc_coerce_number number finite numeric string inputs (excludes '')
rc_coerce_string string number inputs (excludes NaN)
rc_coerce_boolean boolean 0 | 1 | 'true' | 'false' inputs
rc_coerce_date Date date string and epoch number inputs (new Date() parse rules)

rc_try_fix

Use rc_try_fix to try to fix an invalid input and revalidate the fixed value with the same schema. Unlike withAutofix, the fix function doesn't need to return an already valid value, as the fixed value is validated again.

const schema = rc_try_fix(
  rc_object({ name: rc_string, age: rc_number }),
  (input, { errors, warnings }) => {
    // try to fix stringified json inputs
    if (typeof input === 'string') {
      const parsed: unknown = JSON.parse(input)
      return { fixed: parsed }
    }

    // return false to skip fixing
    return false
  },
)

const result = rc_parse('{"name":"John","age":30}', schema)
// passes, with the fixed errors reported as warnings:
// `Fixed error -> Type 'string' is not assignable to 'object{ name: string, age: number }'`

The fix is attempted only once: if the fixed value is still invalid, the original result is returned. If the fix succeeds, the errors of the original parse are reported as warnings (Fixed error -> ...) alongside any warnings from the revalidation, deduplicated.

Performing custom checks

You can also use rc_[type].where(customCheckFunction) to perform custom checks.

const input = 1

const positiveNumberType = rc_number.where((input) => input > 0)

Modifiers added after .where() are respected: for example, rc_array(rc_string).where(items => items.length > 0).optional() accepts undefined without running the predicate. The same applies to .optionalKey(), .orNull(), and .orNullish() for their accepted missing or null values.

Infer types from schemas

You can use RcInferType<typeof schema> to infer the types from a schema.

const schema = rc_object({
  name: rc_string,
  age: rc_number,
  isCool: rc_boolean,
})

export type Person = RcInferType<typeof schema>

You can also use the RcPrettyInferType<typeof schema> to get a more readable type.

Type modifiers

You can use also modifiers like rc_string.optional() to extend the rc types:

runcheck modifier ts type equivalent
rc_[type].optional() T | undefined
rc_[type].orNull() T | null
rc_[type].orNullish() T | null | undefined

Recursive types

You can use rc_recursive to create recursive types. But the types can't be inferred in this case. So you need to provide the type manually.

type MenuTree = {
  name: string
  children: MenuTree[]
}

// the type should be provided manually to the variable in this case
const menuTreeSchema: RcType<MenuTree[]> = rc_array(
  rc_object({
    name: rc_string,
    // you can safely auto-reference the schema here
    children: rc_recursive(() => menuTreeSchema),
  }),
)

const result = rc_parse(input, menuTreeSchema)

Transform types

You can use rc_transform to validate an input and transform it to another data.

const input = 'hello'

const result = rc_parse(
  input,
  rc_transform(rc_string, (input) => input.length),
)

rc_unsafe_transform

For simpler cases where you don't need output validation, use rc_unsafe_transform:

const schema = rc_unsafe_transform(rc_string, (input) => input.toUpperCase())

const result = rc_parse('hello', schema)
if (result.ok) {
  console.log(result.data) // 'HELLO'
}

Transformed types which result can be validated with same schema

You may want to create a transformed type which result can be validated with the same schema. For this you can use the rc_narrow type. Example:

const stringOrArrayOfStrings = rc_union(rc_string, rc_array(rc_string))

const schema = rc_narrow(stringOrArrayOfStrings, (input) =>
  Array.isArray(input) ? input : [input],
)

const result = rc_parse('hello', schema)

if (result.ok) {
  // the schema can safely be used to validate the result too
  const transformedResult = rc_parse(result.data, schema)
}

Default types

You can use rc_default to provide a default value if the input is undefined.

const input = {
  name: 'John',
}

const result = rc_parse(
  input,
  rc_object({
    name: rc_string,
    age: rc_default(rc_number, 20),
  }),
)

if (result.ok) {
  result.data.age // = 20
}

If you need to use default in nullish values you can use rc_nullish_default.

Safe fallback types

You can use rc_safe_fallback to provide a fallback value that is validated against the schema, ensuring type safety.

const input = 'invalid'

const result = rc_parse(
  input,
  rc_safe_fallback(rc_number, 42), // 42 must be a valid number
)

if (result.ok) {
  result.data // = 42 (type-safe)
}

Advanced object types

rc_get_from_key_as_fallback

Allows to rename a key in a object. Example:

const shape = rc_object({
  // name will use the value of oldName if name is not present in input
  // which will rename `oldName` to `name` in the result
  name: rc_get_from_key_as_fallback('oldName', rc_string),
  age: rc_number,
  isCool: rc_boolean,
})

Snake case normalization

you can use rc_object with the normalizeKeysFrom option to normalize the keys of a object to snake case.

const shape = rc_object(
  {
    name: rc_string,
    age: rc_number,
    isCool: rc_boolean,
  },
  { normalizeKeysFrom: 'snake_case' },
)

rc_parse({ name: 'John', age: 20, is_cool: true }, shape) // will not return an error and will normalize the response to { name: 'John', age: 20, isCool: true }

rc_get_obj_shape

Extracts the object shape from an object type for inspection or manipulation:

const shape = rc_object({
  name: rc_string,
  age: rc_number,
  isCool: rc_boolean,
})

const objShape = rc_get_obj_shape(shape)
// objShape = { name: RcType<string>, age: RcType<number>, isCool: RcType<boolean> }
const nameSchema = objShape.name

rc_enable_obj_strict

Enables strict object validation for a type, rejecting excess properties:

const userSchema = rc_object({ name: rc_string, age: rc_number })
const strictUser = rc_enable_obj_strict(userSchema)
// Now rejects objects with excess properties

const result = strictUser.parse({ name: 'John', age: 30 }) // valid
const result2 = strictUser.parse({ name: 'John', age: 30, extra: 'data' }) // invalid

Use the nonRecursive option to only affect the immediate object type:

const strictUser = rc_enable_obj_strict(userSchema, { nonRecursive: true })

rc_obj_extends

Don't strip unchecked keys from the result. Example:

const shape = rc_object({
  name: rc_string,
})

const result = rc_parse(
  { name: 'John', age: 20, is_cool: true },
  rc_obj_extends(shape),
)

// keys `age` and `is_cool` will be present in the result
result.data // { name: 'John', age: 20, is_cool: true }

rc_obj_pick

Allows to pick a subset of a object schema. Example:

const shape = rc_object({
  name: rc_string,
  age: rc_number,
  isCool: rc_boolean,
})

const nameSchema = rc_obj_pick(shape, ['name'])

rc_obj_omit

Allows to omit a subset of a object schema. Example:

const shape = rc_object({
  name: rc_string,
  age: rc_number,
  isCool: rc_boolean,
})

const baseSchema = rc_obj_omit(shape, ['isCool'])

rc_obj_builder

Creates a rc_object from a type. This gives better error messages and autocompletion.

type SchemaType = {
  level1: {
    level2: {
      level3: {
        level4: {
          level5: number
        }
      }
    }
  }
  optionalObj?: {
    a: string
  }
  objOrNull: null | {
    a: string
  }
  objOrNullish:
    | null
    | undefined
    | {
        a: string
      }
}

const schema = rc_obj_builder<SchemaType>()({
  level1: {
    level2: {
      level3: {
        level4: {
          level5: rc_string,
          // better error here
        },
      },
    },
  },
  optionalObj: [
    'optional',
    {
      a: rc_string,
      // better error here and autocompletion :)
    },
  ],
  objOrNull: [
    'null_or',
    {
      a: rc_string,
    },
  ],
  objOrNullish: [
    'nullish_or',
    {
      a: rc_string,
    },
  ],
})

rc_discriminated_union

Creates a discriminated union type with faster check performance compared to rc_union.

const networkState = rc_discriminated_union('state', {
  loading: {},
  success: {
    response: rc_string,
  },
  error: {
    code: rc_number,
  },
})

const result = rc_unwrap(
  rc_parse({ state: 'success', response: 'hello' }, networkState),
)
// result will be inferred as:
// | { state: 'loading' }
// | { state: 'success', response: string }
// | { state: 'error', code: number }

rc_discriminated_union_builder

Creates a type-safe discriminated union builder that enforces the structure matches a TypeScript type:

type Shape =
  | { type: 'circle'; radius: number }
  | { type: 'rectangle'; width: number; height: number }

const shapeSchema = rc_discriminated_union_builder<Shape, 'type'>('type')({
  circle: { radius: rc_number },
  rectangle: { width: rc_number, height: rc_number },
})

rc_array_filter_from_schema

Creates a two passes array validation. The first will validate the items against the filter schema and filter the item. The second will perform the type check against the filtered items.

const schema = rc_array_filter_from_schema(
  // 1 validate the items against a filter schema
  rc_object({
    deleted: rc_boolean,
  }),
  // Then filter the items based on the filter schema result
  (item) => !item.deleted,

  // 2 validate the filtered items
  rc_object({
    value: rc_string,
  }),
)

const result = rc_parse(
  [
    { deleted: false, value: 'hello' },
    { deleted: true, value: 'world' },
  ],
  schema,
)

// result.value === [{ value: 'hello' }]

JSON Parsing

You can use rc_parse_json to parse and validate JSON strings directly:

import { rc_parse_json } from 'runcheck'

const userSchema = rc_object({ name: rc_string, age: rc_number })
const result = rc_parse_json('{"name":"John","age":30}', userSchema)

if (result.ok) {
  console.log(result.data) // { name: 'John', age: 30 }
}

Standard Schema Integration

Runcheck supports Standard Schema V1 for interoperability with other validation libraries:

Converting to Standard Schema

import { rc_to_standard } from 'runcheck'

const rcSchema = rc_object({ name: rc_string, age: rc_number })
const standardSchema = rc_to_standard(rcSchema)

// Use with other Standard Schema compatible libraries

Converting from Standard Schema

import { rc_from_standard } from 'runcheck'

// Convert a Standard Schema to runcheck type
const rcSchema = rc_from_standard(someStandardSchema)

Additional Utilities

Type Guards

Use isRcType to check if a value is a runcheck type:

import { isRcType } from 'runcheck'

if (isRcType(someValue)) {
  // someValue is now typed as RcType<any>
  const result = someValue.parse(input)
}

Schema Inspection

Use getSchemaKind to get the string representation of a schema:

import { getSchemaKind } from 'runcheck'

const kind = getSchemaKind(rc_string) // returns 'string'
const kind2 = getSchemaKind(rc_array(rc_number)) // returns 'number[]'

rc_get_shape

Use rc_get_shape to extract the full shape of a schema as a typed tree, for use in schema conversions (e.g. to zod or JSON Schema) and other schema introspection:

import { rc_get_shape, RcShape } from 'runcheck'

const schema = rc_object({
  name: rc_string,
  age: rc_number.optional(),
})

const shape: RcShape = rc_get_shape(schema)
// {
//   kind: 'object',
//   properties: {
//     name: { kind: 'string' },
//     age: { kind: 'optional', shape: { kind: 'number' } },
//   },
//   excessKeys: 'strip',
// }

RcShape is a discriminated union on kind:

  • 'string' | 'number' | 'boolean' | 'date' | 'null' | 'undefined' | 'any' | 'unknown': primitive types
  • literal: literal values with a values array
  • coerce: coerce types with a target of 'string' | 'number' | 'boolean' | 'date'
  • optional / nullable / nullish: modifier wrappers with the wrapped shape
  • object: properties record and excessKeys behavior ('strip' for rc_object, 'error' for rc_obj_strict, 'preserve' for rc_obj_extends)
  • record / array / tuple: with valueShape / itemShape / shapes
  • union / intersection: with member shapes
  • discriminated_union: with discriminatorKey and a shapes record mapping discriminator values to member shapes (the member shapes do not include the discriminator key)
  • recursive: with a lazy getShape() to support circular references, handle cycles when consuming it

Shape extraction is lazy and adds no overhead to schema creation or parsing.

Some notes:

  • where predicates, withFallback/withAutofix values and rc_default values are transparent: the shape of the underlying schema is returned
  • String template schemas (rc_string_starts_with, etc.) are represented as { kind: 'string' }
  • Schemas without a clear static shape (transforms, rc_instanceof, standard schemas, etc.) return { kind: 'unknown' }