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

zod-factory

v0.0.10

Published

Typescript compiler API factory abstractions for creating zod validation schemas.

Downloads

454

Readme

zod-factory

An abstraction of the Typescript Compiler API factory for generating zod validator expressions.

Installation

You can install zod-factory with NPM, Yarn, pnpm or other package managers, for example:

npm install zod-factory     # npm
yarn add zod-factory        # yarn
pnpm install zod-factory    # pnpm

Usage

You can use zod-factory to generate Typescript code for zod validator schemas as follows:

import { zf, zfl, zfs } from "zod-factory";

const result = zf.printStatements([
  zf.zodImport(),

  // Using zf
  zf.schemaExport(
    "Person",
    zf.object({
      name: zf.string({ required_error: "Name is required" }),
      age: zf.number.of.nonnegative(
        zf.number.of.int(zf.number({ required_error: "Age is required" }))
      )
    })
  ),

  // Using zfl
  zf.schemaExport(
    "Car",
    zfl()
      .object({
        type: zfl().enum(["SUV", "Sedan", "Minivan"]).create(),
        color: zfl().string().optional().default("black").create()
      })
      .create()
  ),

  // Using zfs
  zf.schemaExport(
    "Book",
    zfs([
      [
        "object",
        {
          title: zfs([["string"], ["max", 40]]),
          author: zfs([["string", { required_error: "Author is required" }]])
        }
      ]
    ])
  )
]);

console.log(result);

Generated Code

import { z } from "zod";

export const Person = z.object({
  name: z.string({ required_error: "Name is required" }),
  age: z.number({ required_error: "Age is required" }).int().nonnegative()
});

export const Car = z.object({
  type: z.enum(["SUV", "Sedan", "Minivan"]),
  color: z.string().optional().default("black")
});

export const Book = z.object({
  title: z.string().max(40),
  author: z.string({ required_error: "Author is required" })
});

Playground

The playground directory contains some early scripts for converting different validator/specification formats into zod validators.

Scripts

Each of the playground scripts supports the following arguments:

codegen.ts [flags] [patterns]

Options:
  patterns             patterns to match files and expressions against. e.g "fileA:.*" "fileB:schema$" "fileC:^expression.*"
  
  Flags:
  -d, --directory <dir>  directory to search for files

codegen.ts

This script generates Typescript code directly from zod validator expressions created with zf, zfs or zfl.

To run codegen.ts script, run the following, pointing it to the sources directory with the files and expressions:

$ cd playground
$ ts-node "./codegen/codegen.ts" -d "sources" "with-zf:.*" "with-zfl:.*" "with-zfs:.*"

codegen-custom.ts

This generates zod validators from a "custom-format" I came up with for defining validation rules. This format is a POC for code generation from other validation specifications.

To use this script, run the following command with the sources directory containing custom-format definitions:

$ cd playground
$ ts-node "./codegen/codegen-custom.ts" -d "sources" "custom-schema:.*"

This custom format, explores references to other schemas defined earlier in the file. The reference is replaced with zod validator expression for the referenced schema.

Example

export const name = {
  $kind: "string",
  $messages: {
    $required: "Name is required",
    $invalid: "Name is invalid",
  }
};

export const age = {
  $kind: "number",
};

export const email = {
  $kind: "string",
  $extensions: [{ $kind: "email" }],
};

export const person = {
  $refs: ["name", "age", "email"],
  $kind: "object",
  $fields: {
    name: "$ref:name", // Referencing name
    age: "$ref:age", // Referencing age
    emails: {
      $kind: "array",
      $element: "$ref:email", // Referencing email
    },
  },
};

Generated Code

import { z } from "zod";

export const name = z
  .string({
    required_error: "Name is required",
    invalid_type_error: "Name is invalid",
  })

export const age = z.number();

export const email = z.string().email();

export const person = z.object({
  name: z.string({
      required_error: "Name is required",
      invalid_type_error: "Name is invalid",
    }),
  age: z.number(),
  emails: z.array(z.string().email()),
});

codegen-openapi.ts

This script generates zod schemas from OpenAPI schema components. Similar to the above, this script takes the filename:schemaNameRegex arguments, and generates zod schemas from the schema AST node definitions in the file that match the regex.

Run the script as follows, point it to the sources directory with the openapi-schema.json file.

$ cd playground
$ ts-node "./codegen/codegen-openapi.ts" -d "sources" "openapi-schema:.*" 

For OpenApi schemas, references are resolved by replacing them with the name of the referenced schema (notice the "favoriteEmoji" property below).

Example

{
  "components": {
    "schemas": {
      "Emoji": {
        "type": "string",
        "format": "emoji",
        "description": "An emoji",
        "example": "👍",
        "maxLength": 1
      },
      "Person": {
        "description": "A person",
        "required": [
          "name",
          "age"
        ],
        "type": "object",
        "properties": {
          "name": {
            "type": "string",
            "description": "The name of the person",
            "example": "John Doe"
          },
          "age": {
            "type": "number",
            "description": "The age of the person",
            "example": 30
          },
          "favoriteEmoji": {
            "$ref": "#/components/schemas/Emoji"
          }
        }
      }  
    }
  }
}

Generated Code

import { z } from "zod";

export const Emoji = z.string().emoji().max(1).describe("An emoji");

export const Person = z.object({
  name: z.string().describe("The name of the person"),
  age: z.number().describe("The age of the person"),
  favoriteEmoji: z.optional(Emoji),
});

Motivation

The Typescript Compiler API is very powerful, and heavily featured to handle a variety of use cases, but it can also be verbose, complex, difficult to extend, "type-unsafe" and very dissimilar from zod's API.

zod-factory aims to reduce this complexity by introducing abstractions on top of the TS Compiler API to make zod code generation simple, more type-safe, scriptable, and extensible.

Acknowledgements

This library was birthed from an independent study course project I am undertaking with my advisor, professor Garret Morris at the University of Iowa.