npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@jeremy-bankes/schema

v5.0.16

Published

A schema module for compile-time and runtime type checking.

Downloads

12

Readme

Schema


| TECHNICAL | | |:-:|-| | noun | a representation of a plan or theory in the form of an outline or model.|

This library allows you to specify the schema for your data, and get compile time typings (help from your IDE) and runtime validation (throw errors if your data isn't in the right format).

With this library, everything is built from "Schema Primitives" (henceforth referred to as "Primitives"), out of the box, all of the JavaScript primitive types are implemented, but this set of Primitives can be extended for your use case. The JavaScript Date is also a supported Primitive. All of your schema objects will be built from this extensible set of Primitives.

|Primitives| |:-:| |undefined| |boolean| |number| |bigint| |string| |symbol| |any| |Date|

Validation with a Primitive

import { Schema } from "@jeremy-bankes/schema";

const dataOfUnknownType: any = 123;
const dataOfNumberType = Schema.validate("number", dataOfUnknownType);

With Primitives, you can now start building more complex data structures. There are multiple way to represent different scenarios. This is done with the following constructs.

| Constructs |Structure|TLDR| |:-:|:-:|:-:| |Meta|{ type: <Primitive or another Construct>, required: boolean, default?: <default value>, validate: <validator> }|A meta object to describe the nature of a section within a schema.| |Array|[ <Primitive or another Construct> ]|Represents an array within a schema.| |Hierarcy|{ [ <Any keys needed> ]: <Primitive or another Construct> }|Represents nested object hierarcy within a schema.| |Compound|[ <Primitive or another Construct>, "or", <Primitive or another Construct> ]| Represents union types. Currently can be used with "and" or "or". | |Dynamic|{ $: <Primitive or another Construct> }|Represents a object with dynamic keys. (Produces the TypeScript type { [Key: string]: any })|

Creating Schema

These primitives and constructs can come together to allow you to define your own schema.

import { Schema } from "@jeremy-bankes/schema";

/* ↓ Schema Definition */
const PersonSchema = Schema.build({
    name: /* ← Hierarcy ↓ */ {
        first: /* ← Meta ↓ */ {
            type: "string" /* ← Primitive */,
            required: true
        },
        middle: { type: "string", required: false },
        last: { type: "string", required: true }
    },
    favoriteNumber: ["bigint" /* ← Primitive */, "or", "number"] /* ← Compound */,
    age: {
        type: "number",
        required: false,
        validate: (age: number, rawData: any) => {
            const birthDate = Schema.validate({ type: "Date", required: false }, rawData.birthDate);
            if (birthDate === undefined) {
                return undefined;
            } else {
                const now = new Date();
                const expectedAge = (now.getTime() - birthDate.getTime()) / 1000 / 60 / 60 / 24 / 365.25;
                Schema.assert(Math.floor(expectedAge) === age);
                return age;
            }
        }
    },
    birthDate: {
        type: "Date",
        required: false
    }
});

const WeaponSchema = Schema.build({
    damage: "number" /* ← Primitive */,
    owners: ["string"] /* ← Array */,
    forged: /* ← Meta ↓ */ {
        type: "Date",
        required: false
    },
    affixtures: /* ← Dynamic ↓ */ {
        $: "string"
    }
});

Using Schema

With the schema definitions created, they can be used to validate data where the types are unknown. This data might come from fetch requests, information read from disk, or even JavaScript libraries that don't export their own type definitions, just to name a few examples.

import fs from "fs";

const personData = JSON.parse(fs.readFileSync("person.json", "utf8"));
const person = Schema.validate(PersonSchema, personData);

person now has the following compile-time type annotation based on PersonSchema.

const person: {
    name: {
        first: string;
        last: string;
    } & {
        middle?: string | undefined;
    };
    favoriteNumber: number | bigint;
}

At runtime, the object parsed from the person.json file will be validated to match this generated typing. If it does not match, a Schema.ValidationError will be thrown.

To-Do

  • Documentation:
    • Extending Primitive set.
    • Defining a default value / function in Meta
    • Defining a validator in Meta