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-auto-type

v0.0.0

Published

Automatically infer TypeScript types from schema definitions in popular libraries like Zod, TypeBox, Valibot, and more!

Downloads

9

Readme

📘 schema-auto-type

Automatically infer TypeScript types from schema definitions in popular libraries like Zod, TypeBox, Valibot, and more!

🚀 Features

  • Automatic Type Generation: No need to manually write type definitions for your schemas.
  • Supports Multiple Libraries: Works with Zod, TypeBox, Valibot, and any custom schema libraries.
  • Customizable: Easily extendable to support additional schema libraries via configuration.
  • TypeScript Transformer: Integrates seamlessly into your TypeScript compilation process.

📦 Installation

Install the transformer via npm:

npm install --save-dev auto-schema-type

🔧 Configuration

To use the transformer, you need to configure it in your tsconfig.json file under the plugins section.

Basic Setup with Predefined Libraries

Here's how to set it up using predefined library configurations:

{
  "compilerOptions": {
    "plugins": [
      {
        "transform": "auto-schema-type",
        "libraries": ["zod", "tinybuf"] // List of libraries to support
      }
    ]
  }
}

Advanced Setup with Custom Libraries

You can also add custom library configurations directly in your tsconfig.json:

{
  "compilerOptions": {
    "plugins": [
      {
        "transform": "auto-schema-type",
        "libraries": ["zod"], // Use predefined 'zod' library config
        "customLibraries": [   // Add custom library configs
          {
            "name": "myCustomLibrary",
            "baseTypes": ["MyBaseSchema"],
            "modulePath": "my-custom-library",
            "inference": {
              "template": "MyInfer<typeof {schema}>",
              "imports": [
                { "name": "MyInfer", "path": "my-custom-library" }
              ]
            },
            "transformOptions": {
              "addInferenceImport": true
            }
          }
        ]
      }
    ]
  }
}

🛠️ Usage

Once configured, the transformer will automatically generate type aliases for your schemas during compilation.

Example with Zod

import { z } from 'zod';

const UserSchema = z.object({
  name: z.string(),
  email: z.string().email(),
});

After running the transformer, the following type alias will be generated:

export type UserSchema = z.infer<typeof UserSchema>;

Example with Custom Library

Assuming you have a custom schema library my-custom-library:

import { MyBaseSchema, defineSchema } from 'my-custom-library';

const ProductSchema = defineSchema({
  id: 'number',
  name: 'string',
  price: 'number',
});

With the custom library configuration, the transformer will generate:

import { MyInfer } from 'my-custom-library';

export type ProductSchema = MyInfer<typeof ProductSchema>;

✨ Customization

You can extend the transformer to support any schema library by providing custom LibraryConfig objects in the customLibraries array in your tsconfig.json.

LibraryConfig Structure

interface LibraryConfig {
  name: string;
  baseTypes: string[];
  modulePath: string;
  inference: {
    template: string;
    imports?: Array<{ name: string; path: string }>;
  };
  transformOptions?: {
    addInferenceImport?: boolean;
  };
}

Example Configuration

{
  "name": "myCustomLibrary",
  "baseTypes": ["MyBaseSchema"],
  "modulePath": "my-custom-library",
  "inference": {
    "template": "MyInfer<typeof {schema}>",
    "imports": [
      { "name": "MyInfer", "path": "my-custom-library" }
    ]
  },
  "transformOptions": {
    "addInferenceImport": true
  }
}

⚙️ How It Works

  • The transformer scans your TypeScript files for schema definitions.
  • It uses type-checking to identify variables that extend or satisfy a specified base type from a given module.
  • It generates a type alias for each schema using the provided template.
  • It adds necessary imports if they are not already present.

📝 Notes

  • The transformer only processes TypeScript files (.ts and .tsx).
  • It integrates with the TypeScript compiler API and works during the compilation process.
  • Ensure all properties in your custom LibraryConfig are serializable to JSON.

🐞 Troubleshooting

  • Library Not Recognized: If you receive a warning about an unrecognized library, ensure the library name matches the predefined ones or is correctly defined in your custom configurations.
  • No Type Aliases Generated: Check that your schemas are correctly extending or satisfying the base types specified in the configurations.
  • Compilation Errors: Ensure that the transformer is correctly configured in your tsconfig.json and that all dependencies are installed.

📄 License

This project is licensed under the MIT License.

🙏 Acknowledgments

Special thanks to all contributors and the TypeScript community for making such integrations possible.

📫 Contact

For questions or support, please open an issue on the GitHub repository or reach out to the maintainer.


Happy coding! 🎉