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

schema-shift

v0.4.0

Published

💠 Modify and transform validation schema with a unified API

Downloads

231

Readme

Schema Shift

Schema shift provides a unified API for interacting with schema libraries programmatically and converting between schema libraries and formats. Modify, introspect and convert schemas defined using most popular validation libraries.

npm i schema-shift

Features

  • [x] Generate JSON Schema definitions
  • [x] Convert schema between various libraries
  • [x] Universal interface for parsing values and inferring types
  • [x] Traverse, introspect and transform schemas

Example Usage

// Define a schema
const MyZodSchema = z.object({ foo: z.string() });

// Generate intermediate representation of the schema
const mySchemaDef = ZodShift.toDef(MyZodSchema);

// Convert that into a different schema library...
const MyJoiSchema = JoiShift.fromDef(mySchemaDef);

// ...or into JSON Schema
const jsonSchema = JoiShift.toJsonSchema(MyJoiSchema);

Table of Contents

Why?

The JS ecosystem boasts countless schema validation libraries. While this offers the benefit of choice, it also leads to fragmentation of the ecosystem and makes it harder for libraries to integrate with one another.

Schema Shift unifies the ecosystem of validation libraries by making it trivial to manage, modify and transform schema between different forms. For library authors, this makes it easy to support many different validation/schema libraries without explicitly hand-rolling code for each.

How?

Schema Shift transforms a given schema, defined using one of the many supported schema libraries, into an intermediate JSON Schema-like representation. In turn, this can be used to produce the equivalent schema in another library, modify the schema shape without touching any internals, or generate a JSON schema definition.

{Schema A} --[.toDef()]--> {Abstract Definition} --[.fromDef()]--> {Schema B}

API Reference

Schema Shift currently supports the following libraries.

| | import | | ----------- | ------------------------------------------------------------- | | Zod | import { ZodShift } from "schema-shift/zod" | | Yup | import { YupShift } from "schema-shift/yup" | | Joi | import { JoiShift } from "schema-shift/joi" | | Valibot | import { ValibotShift } from "schema-shift/valibot" | | TypeBox | import { TypeBoxShift } from "schema-shift/typebox" | | Superstruct | import { SuperstructShift } from "schema-shift/superstruct" | | Runtypes | import { RuntypesShift } from "schema-shift/runtypes" |

Core Functionality

Schema Shift exports library-specific namespaces which expose the functions listed below.

<namespace>.toDef(schema)

Creates a definition (internal representation) for the given schema.

const def = ZodShift.toDef(MyZodSchema);

We can supply this definition to one of the various formatter functions below. Modifying the def allows us to produces changes in any schema produced by the formatting functions which accept a def as input, listed below.

<namespace>.fromDef(def)

Creates a schema from the given definition.

const MyZodSchema = ZodShift.fromDef(def);

By providing a def to a .fromDef function, we instantiate a schema corresponding to the namespace. In other words, ZodShift.fromDef creates a zod schema, and so forth.

Because .fromDef handles schema definitions programmatically, type information is not preserved as if you were describing a schema explicitly. Therefore, this process is intended for runtime-specific use-cases, like validating values conform to a specific shape.

<namespace>.toJsonSchema(schema)

Convert a schema to JSON Schema form.

const jsonSchema = ZodShift.toJsonSchema(MyZodSchema);

We can transform a schema into it's JSON Schema equivalent via .toJsonSchema, which can be used with OpenAPI specs, for example.

This function will require installing @sinclair/typebox.

Under the hood, this function is really just sugar for creating a def and passing it to TypeBoxShift.fromDef, which provides a JSON Schema representation.

<namespace>.isSchema(value)

Determine if an unknown value is a schema object.

const isZodSchema = ZodShift.isSchema(maybeZodSchema);

We might not always have control over or knowledge of certain values in our programs. We can verify whether an unknown value is in fact a schema or not using .isSchema.

Note that .isSchema is only a heuristic, and determining schema type is not an exact science.

Utilities

These utilities are not library-specific, and can be imported via the root package.

import { ... } from "schema-shift";

Infer

The Infer type utility enables inferring the output type of any supported schema. Additionally, the InferIn utility can be used to infer the "input" type, meaning the expected type before the schema performs any transformations.

import { Infer, InferIn } from "schema-shift";

const User = z.object({
    id: z.number().transform(String),
});

type User = Infer<typeof User>;
// { id: string }

type UserIn = InferIn<typeof User>;
// { id: number }

parse(value)

The parse function enables parsing any supported schema by providing the schema and value.

import { parse, Parser } from "schema-shift";

const FooZod = z.object({ foo: z.boolean() });
const BarJoi = J.object({ bar: J.boolean() });

parse(FooZod, { foo: true });
// { foo: boolean }

parse(BarJoi, { bar: true });
// { bar: boolean }

// Use the `Parser` type for custom functionality
const customParser = (parser: Parser, value: unknown) => {
    return parse(parser, value);
};

getParseFn(schema)

Given an unknown schema, returns a function that can parse values.

import { getParseFn } from "schema-shift";

const FooZod = z.object({ foo: z.boolean() });

const parser = getParseFn(FooZod);

parser({ foo: true });
// { foo: boolean }