@amritk/generate-validators
v0.2.3
Published
Generate TypeScript validation functions from JSON Schemas.
Maintainers
Readme
@amritk/generate-validators
Programmatic API for generating predicate-style TypeScript validators from JSON Schemas.
Overview
@amritk/generate-validators produces lightweight runtime validators from a JSON Schema. Where @amritk/generate-parsers coerces and parses unknown input into a typed value, this package emits cheaper predicate-style functions that simply tell you whether a value matches a schema (and where it doesn't).
Each generated file exports:
- A TypeScript
typedefinition for the schema - A
validateFoo(input: unknown, _path?: string): ValidationResultfunction
A shared validation-result.ts template and an index.ts barrel are emitted alongside the generated files.
Installation
npm install @amritk/generate-validators
# or
pnpm add @amritk/generate-validators
# or
yarn add @amritk/generate-validators
# or
bun add @amritk/generate-validatorsUsage
import { buildValidatorSchema } from '@amritk/generate-validators'
import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
const schema: JSONSchema = {
type: 'object',
properties: {
info: { $ref: '#/$defs/info' },
},
$defs: {
info: {
type: 'object',
properties: { title: { type: 'string' } },
required: ['title'],
},
},
}
const files = await buildValidatorSchema(schema, 'Document')
// → [{ filename: 'document.ts', content: '...' }, { filename: 'info.ts', ... }, { filename: 'validation-result.ts', ... }, { filename: 'index.ts', ... }]Write the resulting files to disk and import the validators where you need them:
import { validateDocument } from './generated'
const result = validateDocument(input)
if (!result.valid) {
console.error(result.errors)
}API
buildValidatorSchema(rootSchema, rootTypeName)
| Parameter | Type | Description |
|:---|:---|:---|
| rootSchema | JSONSchema | The root schema to traverse. $ref and $dynamicRef are resolved recursively. Draft-07 schemas are upgraded to 2020-12 automatically. |
| rootTypeName | string | Name used for the root type (e.g. "Document"). |
Returns: Promise<GeneratedFile[]> where GeneratedFile = { filename: string; content: string }.
Related packages
@amritk/generate-parsers— type definitions plus parsers that coerce input@amritk/mjst— CLI wrapper around the generators@amritk/helpers— shared schema-traversal utilities
