Suretype

Typesafe JSON (Schema) validator

README


Suretype is a JSON validator targeting TypeScript and JSON Schema. It is ridiculously type safe when used in TypeScript, which is good for accuraccy, but also for aiding IDE auto-complete.

It's as easy as Joi, but ~70x faster.

It's (at least) as typesafe as Superstruct, but 100x faster. 2500x faster than Zod and ~1600x faster than ow.

These are x (times) not %

Benchmark results.


  1. ```
  2. yarn benchmark
  3. Joi x 123,593 ops/sec ±0.60% (94 runs sampled)
  4. Superstruct x 87,898 ops/sec ±0.33% (92 runs sampled)
  5. Zod x 3,498 ops/sec ±1.15% (91 runs sampled)
  6. ow x 5,533 ops/sec ±0.93% (85 runs sampled)
  7. SureType x 8,982,429 ops/sec ±0.53% (91 runs sampled)
  8. -----
  9. 73x faster than Joi
  10. 102x faster than Superstruct
  11. 2568x faster than Zod
  12. 1623x faster than ow
  13. ```


It supports most (if not all) of JSON schema, and nothing beyond that, so that the validator schemas written in TypeScript (or JavaScript) can be ensured to be convertible into JSON schema. This also prevents suretype from becoming feature bloated - it has a small and extremely simple API.

Errors are prettified using [awesome-ajv-errors][awesome-ajv-errors-url].

From a validator schema defined with suretype, you can trivially:

Compile a validator function (using the very fast Ajv)
Extract the corresponding JSON Schema
Deduce a TypeScript type corresponding to the validator schema (at compile-time!)
Using typeconv:
   Export (convert) the validator schema into JSON Schema, Open API, TypeScript types or GraphQL, or;
   The opposite (!); convert JSON Schema, Open API, TypeScript types or GraphQL into suretype validators! 🎉

The above makes it ideal in TypeScript environments. When used in RESTful applications, the exported schema can be used to document the APIs using OpenAPI. When used in libraries / clients, the TypeScript interfaces can be extracted to well-documented standalone files (including JSDoc comments).


Versions


Since version 3;
   This is a [pure ESM][pure-esm] package. It requires at least Node 14.13.1, and cannot be used from CommonJS.
   This package can be used in browsers without special hacks. It will not pretty-print codeframes or use colors if the bundling setup doesn't support it, but will to try to load support for it.
   You can control colorized/stylized output globally or per validator


Minimal example


The following is a validator schema using suretype:

  1. ```ts
  2. import { v } from "suretype"

  3. const userSchema = v.object( {
  4.     firstName: v.string( ).required( ),
  5.     lastName: v.string( ),
  6.     age: v.number( ).gte( 21 ),
  7. } );
  8. ```

This schema object can be compiled into validator functions, and it can be used to deduce the corresponding TypeScript type:

  1. ```ts
  2. import type { TypeOf } from "suretype"

  3. type User = TypeOf< typeof userSchema >;
  4. ```

This type is compile-time constructed (or deduced), and is semantically identical to:

  1. ```ts
  2. interface User {
  3.     firstName: string;
  4.     lastName?: string;
  5.     age?: number;
  6. }
  7. ```

Note the ? for the optional properties, i.e. those that aren't followed by required().

There are three ways of compiling a validator function; choose the one that best fits your application and situation. Given:

  1. ```ts
  2. import { compile } from "suretype"

  3. const data = ... // get data from somewhere, e.g. as a TypeScript unknown
  4. ```


Standard validator


The default behaviour of compile is to return a validator function returning extended Ajv output.

  1. ```ts
  2. const userValidator = compile( userSchema );
  3. userValidator( data );
  4. // { ok: true } or
  5. // { ok: false, errors: [Ajv errors...], explanation: string }
  6. ```

The explanation is a pretty-printed error.


Type-guarded validator


Use the second optional argument to specify simple mode. The return is a boolean, type guarded.

  1. ```ts
  2. const isUser = compile( userSchema, { simple: true } );
  3. isUser( data ); // true | false, usable as guard:

  4. // Realistic usage:

  5. if ( isUser( data ) ) {
  6.     // Valid TypeScript, is now typed(!) as the User type above
  7.     data.firstName;
  8. } else {
  9.      // TypeScript compile error(!), is unknown
  10.     data.firstName;
  11. }
  12. ```


Type-ensured validator


Specify ensure mode to get a validator function which returns the exact same output as the input (referentially equal), but with a deduced type. This is often the most practical mode.

  1. ```ts
  2. const ensureUser = compile( userSchema, { ensure: true } );
  3. ensureUser( data ); // returns data or throws an error if the data isn't valid.

  4. // Realistic usage:

  5. const user = ensureUser( data );
  6. // is ensured to be valid, *and* is of type User (as above)
  7. user.firstName; // string
  8. user.foo; // TypeScript compile-time error, there is no `foo` in User
  9. ```

On validation failure, the error thrown will be of the class ValidationError, which has both the raw Ajv errors as an errors property, and the pretty explanation in the property explanation.

Note: The returned ensurer function can optionally take a type parameter as long as it is equal to or compatible with the deduced type. This means that if the type is exported from suretype to decorated TypeScript declaration files (with annotations), those types can be used as a type parameter, and the returned type will be that type. Example:

  1. ```ts
  2. import type { User } from './generated/user'
  3. const user = ensureUser< User >( data );
  4. // user is now of type User
  5. ```


Validate or ensure without compiling


Instead of creating a validator from compile, you can use the shorthands validate, isValid and ensure. They correspond to compiling without options, compiling in simple-mode and in ensure-mode.

  1. ```ts
  2. import { validate, isValid, ensure } from 'suretype'

  3. const validation = validate( userSchema, data ); // -> Validation object
  4. const isUser = isValid( userSchema, data );      // -> Type-guarded boolean
  5. const user = ensure( userSchema, data );         // -> user is data of type userSchema
  6. ```


Raw JSON Schema validator


Sometimes it's handy to not describe the validator schema programmatically, but rather use a raw JSON Schema. There will be no type deduction, so the corresponding interface must be provided explicitly. Only use this if you know the JSON Schema maps to the interface! raw works just like the v.* functions and returns a validator schema. It can also be annotated.

  1. ```ts
  2. import { raw, compile } from 'suretype'

  3. type User = ...; // Get this type from somewhere
  4. const userSchema = raw< User >( { type: 'object', properties: { /* ... */ } } );

  5. // Compile as usual
  6. const ensureUser = compile( userSchema, { ensure: true } );
  7. ```


Configure


You can configure colorization and styling, instead of relying on support detection.

Either globally:
  1. ```ts
  2. import { setSuretypeOptions } from 'suretype'

  3. setSuretypeOptions( {
  4.     colors: true | false,
  5.     location: true | false,
  6.     bigNumbers: true | false,
  7. } );
  8. ```

and/or per validator, e.g.:
  1. ```ts
  2. import { compile } from 'suretype'

  3. const ensureThing = compile(
  4.     schemaThing,
  5.     { ensure: true, color: true, location: false }
  6. );
  7. ```


Annotating schemas


You can annotate a validator schema using suretype() or annotate(). The return value is still a validator schema, but when exporting it, the annotations will be included.

The difference between suretype() and annotate() is that suretype() requires the name property, where as it's optional in annotate(). Use suretype() to annotate top-level schemas so that they have proper names in the corresponding JSON Schema.

Annotations are useful when exporting the schema to other formats (e.g. JSON Schema or pretty TypeScript interfaces).

  1. ```ts
  2. import { suretype, annotate, v } from "suretype"

  3. const cartItemSchema = suretype(
  4.     // Annotations
  5.     { name: "CartItem" },
  6.     // The validator schema
  7.     v.object( {
  8.         productId: annotate( { title: "The product id string" }, v.string( ) ),
  9.         // ...
  10.     } )
  11. );
  12. ```

The interface (i.e. the fields you can use) is called Annotations:

  1. ```ts
  2. interface Annotations {
  3. name: string;
  4. title?: string;
  5. description?: string;
  6. examples?: Array< string >;
  7. }
  8. ```

where only the name is required.


Thorough example


The following are two types, one using (or depending on) the other. They are named, which will be reflected in the JSON schema, shown below.

The userSchema is the same as in the above example, although it's wrapped in suretype() which annotates it with a name and other attributes.

Given these validation schemas:


  1. ```ts
  2. import { suretype, v } from "suretype"

  3. const userSchema = suretype(
  4.     {
  5.         name: "V1User",
  6.         title: "User type, version 1",
  7.         description: `
  8.             A User object must have a firstName property,
  9.             all other properties are optional.
  10.         `,
  11.         examples: [
  12.             {
  13.                 firstName: "John",
  14.                 lastName: "Doe",
  15.             }
  16.         ],
  17.     },
  18.     v.object( {
  19.         firstName: v.string( ).required( ),
  20.         lastName: v.string( ),
  21.         age: v.number( ).gte( 21 ),
  22.     } )
  23. );

  24. const messageSchema = suretype(
  25.     {
  26.         name: "V1Message",
  27.         title: "A message from a certain user",
  28.     },
  29.     v.object( {
  30.         user: userSchema.required( ),
  31.         line: v.string( ).required( ),
  32.     } )
  33. );
  34. ```


The JSON schema for these can be extracted, either each type by itself:

  1. ```ts
  2. import { extractSingleJsonSchema } from "suretype"

  3. // The JSON schema for User
  4. const { schema: jsonSchema } = extractSingleJsonSchema( userSchema );
  5. ```

or as all types at once, into one big JSON schema. In this case, all validation schemas provided must be wrapped with suretype(), as they will become JSON schema "definitions" and therefore must have at least a name.

  1. ```ts
  2. import { extractJsonSchema } from "suretype"

  3. const { schema: jsonSchema, lookup, schemaRefName } =
  4.     extractJsonSchema( [ userSchema, messageSchema ], { /* opts... */ } );
  5. ```

An optional second argument can be provided on the form:

  1. ```ts
  2. interface ExtractJsonSchemaOptions {
  3.     refMethod?: ExportRefMethod;
  4.     onTopLevelNameConflict?: OnTopLevelNameConflict;
  5.     onNonSuretypeValidator?: OnNonSuretypeValidator;
  6. }
  7. ```

The ExportRefMethod type is a string union defined as:
  1. ```ts
  2.     | 'no-refs'  // Don't ref anything. Inline all types to monolith types.
  3.     | 'provided' // Reference types that are explicitly provided.
  4.     | 'ref-all'  // Ref all provided types and those with names, suretype()'d.
  5. ```

The OnTopLevelNameConflict type is a string union defined as:
  1. ```ts
  2.     | 'error'  // Fail the operation
  3.     | 'rename' // Rename the validators to a unique name
  4. ```

The OnNonSuretypeValidator type is a string union defined as:
  1. ```ts
  2.     | 'error'       // Fail the operation
  3.     | 'ignore'      // Ignore, don't export
  4.     | 'create-name' // Create a name 'Unknown'
  5.     | 'lookup'      // Provide in lookup table
  6. ```

If lookup is specified, it allows unnamed validators. They won't exist in the resulting schema, but in a lookup table next to it. This lookup table will always exist, using this setting will simply allow unnamed validators.

The result is an object on the form:

  1. ```ts
  2. interface ExtractedJsonSchema {
  3.     schema: SchemaWithDefinitions; // Contains a 'definitions' property
  4.     lookup: Map< CoreValidator< unknown >, any >;
  5.     schemaRefName: Map< any, string >;
  6. }
  7. ```

The lookup is useful to lookup the json schema for a certain validator object reference, especially unnamed ones which are not included in the schema.

The schemaRefName contains a lookup map from (top-level) schema object to its name as used when referring to it, not necessarily the same as what it is internally named, if there where naming conflicts and OnTopLevelNameConflict is rename.

In the example above, the jsonSchema object (which can be JSON.stringify'd) will be something like:

JSON Schema


  1. ```js
  2. {
  3.     "$schema": "http://json-schema.org/draft-07/schema#",
  4.     "definitions": {
  5.         "V1User": { // <-- This corresponds to the "name" property in suretype()
  6.             "title": "User type, version 1",
  7.             "description": "A User object must have a firstName property,\nall other properties are optional.",
  8.             "examples": [
  9.                 {
  10.                     "firstName": "John",
  11.                     "lastName": "Doe"
  12.                 }
  13.             ],
  14.             "type": "object",
  15.             "properties": {
  16.                 "firstName": { "type": "string" },
  17.                 "lastName": { "type": "string" },
  18.                 "age": { "type": "number", "minimum": 13 }
  19.             },
  20.             "required": [ "firstName" ]
  21.         },
  22.         "V1Message": {
  23.             "title": "A message from a certain user",
  24.             "type": "object",
  25.             "properties": {
  26.                 "user": { "$ref": "#/definitions/V1User" }, // <-- Proper references
  27.                 "line": { "type": "string" }
  28.             },
  29.             "required": [ "user", "line" ]
  30.         }
  31.     }
  32. }
  33. ```



Exporting using typeconv



A better (well, often much more practical) way of converting suretype validator schemas into JSON Schema is by using [typeconv][typeconv-github-url] [![npm version][typeconv-image]][typeconv-npm-url].

You can convert from suretype validator schemas to:
TypeScript interfaces (pretty printed with JSDoc comments)
JSON Schema
Open API
GraphQL

When converting from suretype, typeconv will convert all exported validator schemas from the source files.

Example from SureType to TypeScript; `$ npx typeconv -f st -t ts -o generated 'src/validators/*/.ts'`

You can also convert from any of these formats into suretype validators!

Example from Open API to SureType; `$ npx typeconv -f oapi -t st -o generated 'schemas/*/.yml'`