5.0.4 • Published 16 days ago

@skyleague/therefore v5.0.4

Weekly downloads
-
License
MIT
Repository
github
Last release
16 days ago

∴ Therefore @skyleague/therefore

Such is the advantage of a well-constructed language that its simplified notation often becomes the source of profound theories.

  • Pierre-Simon de Laplace

Therefore empowers you to generate JSON Schemas and typescript types.

It is hard to keep JSON Schemas and types aligned, especially in a world of growing api complexity. Therefore, we want to simplify the most frustrating problems associated with JSON validation and typing.

Therefore is:

  • clean schema definition that reads similar to typescript interfaces
  • handwritten types look very similar to the generated schemas
  • easily (re)generate schemas with a simple CLI command
  • no runtime dependencies; Therefore is designed such that it only has to be a development package
  • strict by default; less api-surface, less confusion, happier code

Documentation

The documentation can be found here.

Security

Therefore internally uses Ajv for its validation. That means that the security considerations of using Therefore become a superset of those of Ajv. By default Therefore tries to implement the strictest interface and validation given a schema.

Background

Having runtime validation of your typescript types is not supported out of the box. More than one has tried to solve this problem. However, many of those implementations - we felt - are too complex. We wanted to separate the validation (a challenging situation in itself) and the schema part. And thus, we looked at the different schema validation implementations, where only one stood out: JSON Schema.

The usage of JSON Schema has grown incredibly over the last few years. Most languages now have a stable validator implementation, and OpenAPI (the successor of swagger) fully adopted the JSON Schema specification. As a result, we now have good tools to define and validate API interfaces.

So why not take advantage? As we found out, there is a problem with successful schema validation in typescript - keeping your schemas synchronized with your code can be incredibly hard without proper tooling. Writing JSON Schema is verbose, but reading it requires more effort than just glancing at a typescript definition. That is not the most significant problem, but we firmly believe schema definitions should be strict, readable and concise.

This is where Therefore comes in. Therefore itself does not do any validation. At all. Therefore allows you to write very concise JSON Schemas supported by excellent tooling to help you wherever it can—creating a reference to another variable? No problem. You don't want to export that particular object? Consider it done. Do you want to reuse the JSON Schema in an OpenAPI specification? Of course, go ahead!

In a nutshell:

  1. You define your schema definitions in files with a specific extension (.schema.ts by default)
  2. You run Therefore on the folder npx therefore -f src
  3. Therefore will generate a type file with extension .type.ts for you with helper functions of all exported symbols, and in a subfolder schemas you will find all generated JSON Schemas waiting for you.
  4. No runtime dependency on Therefore :)

Install

Install Therefore using npm:

 $ npm install --save-dev @skyleague/therefore

Usage

Let's get started with a simple JSON Schema taken as an example:

example.schema.ts

import { $number, $object, $string, $validator } from '@skyleague/therefore'

export const person = $validator(
    $object({
        firstName: $string({
            description: "The person's first name.",
        }),
        lastName: $string,
        age: $number,
    })
)

With this schema defined, we can generate the typescript types and JSON schema file:

 $ therefore -f examples/json-schema/
scanning examples/json-schema/example.schema.ts
 - found Person
$ prettier --write examples/json-schema/example.type.ts examples/json-schema/schemas/person.schema.json
examples/json-schema/example.type.ts 149ms
examples/json-schema/schemas/person.schema.json 17ms
Done in 0.41s.

example.type.ts

export interface Person {
    /**
     * The person's first name.
     */
    firstName: string
    lastName: string
    age: number
}

export const Person = {
    validate: require('./schemas/person.schema.js') as ValidateFunction<Person>,
    get schema() {
        return Person.validate.schema
    },
    source: `${__dirname}example.schema`,
    sourceSymbol: 'person',
    is: (o: unknown): o is Person => Person.validate(o) === true,
} as const

schemas/person.schema.json

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "properties": {
        "firstName": {
            "type": "string",
            "description": "The person's first name."
        },
        "lastName": {
            "type": "string"
        },
        "age": {
            "type": "number"
        }
    },
    "required": ["firstName", "lastName", "age"],
    "additionalProperties": false
}

Examples

CLI

You can run Therefore directly from the CLI

USAGE
 $ therefore

Options:
      --version         Show version number                            [boolean]
      --help            Show help                                      [boolean]
  -f, --files           globs to scan for schemas             [array] [required]
  -i, --ignore-pattern  globs to exclude
                      [array] [required] [default: ["**/*.d.ts","node_modules"]]
      --compile                                        [boolean] [default: true]
      --ext                                     [string] [default: ".schema.ts"]
      --out-ext                                   [string] [default: ".type.ts"]

API

Alternative projects

In no particular order, the following libraries try to solve similar problems (albeit very different):

PR's are very welcome if you think your project is missing here.

When not to use Therefore?

  • By default, we create as strict a JSON Schema/type as possible. We are aware that this doesn't suit everyone's needs.
    • additional properties will result in validation errors without extra work
    • indexable types are always explicitly nullable, i.e. Record<string, string | undefined> instead of Record<string, string>
  • We only support JSON Schema validation through Ajv. If you do not want to/can't use Ajv, Therefore probably isn't for you.
  • Therefore is an insanely opinionated implementation of runtime validation of types; It will not fit everyone's needs.

This open source library package is part of the SkyLeague modern application delivery stack.

Support

SkyLeague provides Enterprise Support on this open-source library package at clients across industries. Please get in touch via https://skyleague.io.

If you are not under Enterprise Support, feel free to raise an issue and we'll take a look at it on a best-effort basis!

License & Copyright

This library is licensed under the MIT License (see LICENSE.md for details).

If you using this SDK without Enterprise Support, please note this (partial) MIT license clause:

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND

Copyright (c) 2022, SkyLeague Technologies B.V.. 'SkyLeague' and the astronaut logo are trademarks of SkyLeague Technologies, registered at Chamber of Commerce in The Netherlands under number 86650564.

All product names, logos, brands, trademarks and registered trademarks are property of their respective owners. All company, product and service names used in this website are for identification purposes only. Use of these names, trademarks and brands does not imply endorsement.

5.0.4

16 days ago

5.0.3

16 days ago

5.0.2

16 days ago

5.0.1

16 days ago

5.0.0

16 days ago

4.1.1

4 months ago

4.0.1

4 months ago

4.1.0

4 months ago

4.0.0

5 months ago

3.1.0

5 months ago

2.2.5

10 months ago

2.2.7

8 months ago

2.2.6

10 months ago

3.0.2

7 months ago

3.0.1

7 months ago

3.0.0

7 months ago

2.2.9

7 months ago

2.2.1

12 months ago

2.2.0

12 months ago

2.2.3

12 months ago

2.2.2

12 months ago

2.2.4

11 months ago

2.1.2

12 months ago

2.1.1

1 year ago

2.1.0

1 year ago

2.0.3

1 year ago

2.0.2

1 year ago

2.0.1

1 year ago

2.0.0

1 year ago

1.23.2

1 year ago

1.24.1

1 year ago

1.24.2

1 year ago

1.24.0

1 year ago

1.23.1

1 year ago

1.22.0

1 year ago

1.21.1

1 year ago

1.23.0

1 year ago

1.22.1

1 year ago

1.21.2

1 year ago

1.21.3

1 year ago

1.19.0

2 years ago

1.18.1

2 years ago

1.19.1

2 years ago

1.18.2

2 years ago

1.21.0

1 year ago

1.20.1

1 year ago

1.20.2

1 year ago

1.20.0

1 year ago

1.15.0

2 years ago

1.14.1

2 years ago

1.14.0

2 years ago

1.12.2

2 years ago

1.11.3

2 years ago

1.13.0

2 years ago

1.12.1

2 years ago

1.11.2

2 years ago

1.12.0

2 years ago

1.11.1

2 years ago

1.18.0

2 years ago

1.17.0

2 years ago

1.16.0

2 years ago

1.9.1

2 years ago

1.9.0

2 years ago

1.8.1

2 years ago

1.8.0

2 years ago

1.7.0

2 years ago

1.6.0

2 years ago

1.11.0

2 years ago

1.10.0

2 years ago

1.2.0

2 years ago

1.5.2

2 years ago

1.5.1

2 years ago

1.4.2

2 years ago

1.5.0

2 years ago

1.4.1

2 years ago

1.4.0

2 years ago

1.3.0

2 years ago

1.1.0

2 years ago

1.0.0

2 years ago