Technical Documentation: open-circle/valibot
โน๏ธ Provenance: Multi-Tier Ingestion ยท CodeWiki Reference
Overview (`codemod/README.md`)
Codemod
Run options
The preferred way to run these codemods is via the codemod registry, but as a fallback you can also run them from the source file by running the following command.
npx codemod@latest path-to-source-file.ts --engine=workflowOverview (`library/README.md`)
Valibot
Hello, I am Valibot and I would like to help you validate data easily using a schema. No matter if it is incoming data on a server, a form or even configuration files. I have no dependencies and can run in any JavaScript environment.
I highly recommend you read the announcement post, and if you are a nerd like me, the bachelor's thesis I am based on.
Highlights
- Fully type safe with static type inference
- Small bundle size starting at less than 700 bytes
- Validate everything from strings to complex objects
- Open source and fully tested with 100 % coverage
- Many transformation and validation actions included
- Well structured source code without dependencies
- Minimal, readable and well thought out API
Example
First you create a schema that describes a structured data set. A schema can be compared to a type definition in TypeScript. The big difference is that TypeScript types are "not executed" and are more or less a DX feature. A schema on the other hand, apart from the inferred type definition, can also be executed at runtime to guarantee the type safety of unknown data.
import * as v from 'valibot'; // 1.31 kB
// Create login schema with email and password
const LoginSchema = v.object({
email: v.pipe(v.string(), v.email()),
password: v.pipe(v.string(), v.minLength(8)),
});
// Infer output TypeScript type of login schema as
// { email: string; password: string }
type LoginData = v.InferOutput<typeof LoginSchema>;
// Throws error for email and password
const output1 = v.parse(LoginSchema, { email: '', password: '' });
// Returns data as { email: string; password: string }
const output2 = v.parse(LoginSchema, {
email: '[email protected]',
password: '12345678',
});Apart from parse I also offer a non-exception-based API with safeParse and a type guard function with is. You can read more about it here.
Comparison
Instead of relying on a few large functions with many methods, my API design and source code is based on many small and independent functions, each with just a single task. This modular design has several advantages.
For example, this allows a bundler to use the import statements to remove code that is not needed. This way, only the code that is actually used gets into your production build. This can reduce the bundle size by up to 95 % compared to Zod.
In addition, it allows you to easily extend my functionality with external code and makes my source code more robust and secure because the functionality of the individual functions can be tested much more easily through unit tests.
Coming from Zod? Read our migration article to see the benefits of Valibot, and use our migration guide to migrate your schemas with confidence.
Partners
Thanks to our partners who support my development! Join them and contribute to the sustainability of open source software!
Credits
My friend Fabian created me as part of his bachelor thesis at Stuttgart Media University, supervised by Walter Kriha, Miลกko Hevery and Ryan Carniato. My role models also include Colin McDonnell, who had a big influence on my API design with Zod.
Feedback
Find a bug or have an idea how to improve my code? Please fill out an issue. Together we can make the library even better!
License
I am completely free and licensed under the MIT license. But if you like, you can feed me with a star on GitHub.
Overview (`website/README.md`)
Website
Our website contains guides, an API reference and a playground to quickly learn and understand Valibot.
Getting started
Step 1: Clone repository
git clone [email protected]:open-circle/valibot.gitStep 2: Install dependencies
pnpm installStep 3: Build library
cd ./library && pnpm buildStep 4: Start website
cd ../website && pnpm startOverview (`codemod/migrate-to-v0.31.0/README.md`)
Migrate to v0.31.0
You can use Codemod to automatically update your code to the new API. See the migration guide for more details on the changes.
Examples
Before
import * as v from 'valibot';
v.object({
email: v.string([v.email(), v.endsWith('@gmail.com')]),
password: v.string([v.minLength(8)]),
other: v.union([v.string([v.decimal()]), v.number()]),
});After
import * as v from 'valibot';
v.object({
email: v.pipe(v.string(), v.email(), v.endsWith('@gmail.com')),
password: v.pipe(v.string(), v.minLength(8)),
other: v.union([v.pipe(v.string(), v.decimal()), v.number()]),
});Before
import * as v from 'valibot';
import { object, tuple } from 'valibot';
const ObjectSchema = object({ key: v.string() }, v.null_());
const TupleSchema = tuple([v.string()], v.null_());After
import * as v from 'valibot';
import { objectWithRest, tupleWithRest } from 'valibot';
const ObjectSchema = objectWithRest({ key: v.string() }, v.null_());
const TupleSchema = tupleWithRest([v.string()], v.null_());Before
import * as v from 'valibot';
const ObjectSchema1 = v.object({ foo: v.string() });
const ObjectSchema2 = v.object({ bar: v.number() });
const MergedObject = v.merge([ObjectSchema1, ObjectSchema2]);After
import * as v from 'valibot';
const ObjectSchema1 = v.object({ foo: v.string() });
const ObjectSchema2 = v.object({ bar: v.number() });
const MergedObject = v.object({
...ObjectSchema1.entries,
...ObjectSchema2.entries,
});Before
import * as v from 'valibot';
const BrandedSchema = v.brand(v.string(), 'foo');
const TransformedSchema = v.transform(v.string(), (input) => input.length);After
import * as v from 'valibot';
const BrandedSchema = v.pipe(v.string(), v.brand('foo'));
const TransformedSchema = v.pipe(
v.string(),
v.transform((input) => input.length)
);Overview (`codemod/zod-to-valibot/README.md`)
Zod to Valibot Codemod
Official codemod for automatically converting Zod schemas to Valibot schemas.
Usage
npx @valibot/zod-to-valibot src/**/*Options
# Dry run (preview changes)
npx @valibot/zod-to-valibot --dry src/**/*
# Verbose output
npx @valibot/zod-to-valibot --verbose=2 src/**/*
# Use a different parser (default is --parser=ts)
npx @valibot/zod-to-valibot --parser=babel src/**/*
# Use different extensions (default is --extensions=ts,tsx,js,jsx)
npx @valibot/zod-to-valibot --extensions=ts src/**/*For all available options, see jscodeshift documentation.
What Gets Converted
The codemod converts Zod schemas to Valibot, including:
- Basic schemas (
string,number,boolean,date,bigint) - Validation rules (
email,min,max, etc.) - Coercion (
z.coerce.*โv.pipe(v.unknown(), v.toX())) - Objects, arrays, unions, optionals, and more
Support
For issues or questions, open an issue on the Valibot repository.
Overview (`packages/to-json-schema/README.md`)
Valibot to JSON Schema
Utility to convert Valibot schemas to JSON Schema. Supports JSON Schema draft-07, draft-2020-12, and OpenAPI 3.0 Schema Object formats.
import { toJsonSchema } from '@valibot/to-json-schema';
import * as v from 'valibot';
toJsonSchema(v.string()); // { $schema: "http://json-schema.org/draft-07/schema#", type: "string" }This package is particularly popular for:
- API Documentation: Generate OpenAPI specifications from your Valibot schemas
- Code Generation: Create client SDKs and types from your validation schemas
- LLM Integration: Generate structured outputs for Large Language Models
- Schema Sharing: Share validation logic between different programming languages
Some Valibot features can't be mapped to JSON schema. For example, transformation actions have no equivalent in JSON schema. Also, some Valibot schemas or validations are too JS-specific and do not have an equivalent JSON schema attribute.
Supported features
Note: Converted schemas may behave slightly differently in JSON schema validators (especially for string format) because their implementation is different from Valibot's.
| Schema | Status | Note |
|---|---|---|
any |
โ | |
array |
โ | |
boolean |
โ | |
enum |
โ ๏ธ | Only JSON compatible values are supported |
exactOptional |
โ | |
intersect |
โ | |
lazy |
โ ๏ธ | The .getter function is always executed with undefined as input |
literal |
โ ๏ธ | Only JSON compatible values are supported |
looseObject |
โ | |
looseTuple |
โ | |
never |
โ | |
null |
โ | |
nullable |
โ | |
nullish |
โ | |
number |
โ | |
objectWithRest |
โ | |
object |
โ | |
optional |
โ | |
picklist |
โ ๏ธ | Only JSON compatible values are supported |
record |
โ ๏ธ | Only string schemas for the key of the record are supported. Adds propertyNames for key validation (not available in OpenAPI 3.0) |
strictObject |
โ | |
strictTuple |
โ | |
string |
โ | |
tupleWithRest |
โ | |
tuple |
โ | |
union |
โ | |
undefinedable |
โ | |
unknown |
โ | |
variant |
โ ๏ธ | The discriminator key will be ignored |
| Actions | Status | Note |
|---|---|---|
base64 |
โ | |
bic |
โ | |
cuid2 |
โ | |
decimal |
โ | |
description |
โ | |
digits |
โ | |
domain |
โ | |
email |
โ | |
emoji |
โ | |
empty |
โ | |
endsWith |
โ | |
entries |
โ | |
examples |
โ | |
gtValue |
โ ๏ธ | Only in combination with number and integer schema |
hash |
โ | |
hexadecimal |
โ | |
hexColor |
โ | |
includes |
โ | |
integer |
โ | |
ipv4 |
โ | |
ipv6 |
โ | |
isoDate |
โ | |
isoDateTime |
โ | |
isoTime |
โ | |
isoTimeSecond |
โ | |
isoTimestamp |
โ | |
isoWeek |
โ | |
isrc |
โ | |
jwsCompact |
โ | |
ksuid |
โ | |
length |
โ ๏ธ | Only in combination with string and array schema |
ltValue |
โ ๏ธ | Only in combination with number and integer schema |
mac |
โ | |
mac48 |
โ | |
mac64 |
โ | |
maxEntries |
โ | |
maxLength |
โ ๏ธ | Only in combination with string and array schema |
maxValue |
โ ๏ธ | Only in combination with number schema |
metadata |
โ | Additional properties are added without validation |
minEntries |
โ | |
minLength |
โ ๏ธ | Only in combination with string and array schema |
minValue |
โ ๏ธ | Only in combination with number schema |
multipleOf |
โ | |
nanoid |
โ | |
nonEmpty |
โ | |
notValue |
โ ๏ธ | Only JSON compatible values are supported |
notValues |
โ ๏ธ | Only JSON compatible values are supported |
octal |
โ | |
regex |
โ ๏ธ | RegExp flags are not supported in JSON Schema |
rfcEmail |
โ | |
safeInteger |
โ | |
slug |
โ | |
startsWith |
โ | |
title |
โ | |
ulid |
โ | |
url |
โ | |
uuid |
โ | |
value |
โ ๏ธ | Only JSON compatible values are supported |
values |
โ ๏ธ | Only JSON compatible values are supported |
For
length,minLength, andmaxLength, string constraints have different length semantics in Valibot and JSON Schema. Valibot checks JavaScript string length (value.length, UTF-16 code units), while JSON SchemaminLengthandmaxLengthcount Unicode code points. This can differ for non-BMP code points such as emoji and for multi-code-point grapheme clusters such as combining marks or ZWJ sequences.
Configurations
| Option | Type | Note |
|---|---|---|
| target | 'draft-07' | 'draft-2020-12' | 'openapi-3.0' |
The target JSON Schema format. Defaults to 'draft-07'. |
| typeMode | 'ignore' | 'input' | 'output' |
Whether to convert the input or output type of the Valibot schema to JSON Schema. |
| errorMode | 'throw' | 'warn' | 'ignore' |
The policy for handling incompatible schemas and actions. |
| definitions | Record<string, GenericSchema> |
The schema definitions for constructing recursive schemas. If not specified, the definitions are generated automatically. |
| overrideSchema | (context: OverrideSchemaContext) => JsonSchema | null | undefined |
Overrides the JSON Schema conversion for a specific Valibot schema. |
| ignoreActions | string[] |
The actions that should be ignored during the conversion. |
| overrideAction | (context: OverrideActionContext) => JsonSchema | null | undefined |
Overrides the JSON Schema reference for a specific Valibot action. |
| overrideRef | (context: OverrideRefContext) => string | null | undefined |
Overrides the JSON Schema reference for a specific reference ID. |
Target format
The target configuration allows you to specify which JSON Schema format to generate. Different targets have different capabilities and syntax:
import { toJsonSchema } from '@valibot/to-json-schema';
import * as v from 'valibot';
const schema = v.nullable(v.string());
// JSON Schema draft-07 (default)
toJsonSchema(schema);
// { $schema: "http://json-schema.org/draft-07/schema#", anyOf: [{ type: "string" }, { type: "null" }] }
// JSON Schema draft-2020-12
toJsonSchema(schema, { target: 'draft-2020-12' });
// { $schema: "https://json-schema.org/draft/2020-12/schema", anyOf: [{ type: "string" }, { type: "null" }] }
// OpenAPI 3.0 Schema Object
toJsonSchema(schema, { target: 'openapi-3.0' });
// { type: "string", nullable: true }Note: Some features like propertyNames for record schemas are not available in OpenAPI 3.0.
Type mode
The typeMode configuration controls whether to convert the input or output type of the Valibot schema to JSON Schema.
- When set to
'input', conversion stops before the first potential type transformation action or second schema in any pipeline. - When set to
'output', conversion of any pipelines starts from the last schema in the pipeline. Therefore, the output type must be specified explicitly with a schema after the last type transformation action. - When set to
'ignore'(default), the entire pipeline is converted.
This is particularly useful when defining API endpoints where external developers need different schema information for requests vs responses:
import { toJsonSchema } from '@valibot/to-json-schema';
import * as v from 'valibot';
const ValibotSchema = v.pipe(
v.string(),
v.decimal(),
v.transform(Number),
v.number(),
v.maxValue(100)
);
toJsonSchema(ValibotSchema, { typeMode: 'input' });
// {
// $schema: "http://json-schema.org/draft-07/schema#",
// type: "string",
// pattern: "^[+-]?(?:\\d*\\.)?\\d+$"
// }
toJsonSchema(ValibotSchema, { typeMode: 'output' });
// {
// $schema: "http://json-schema.org/draft-07/schema#",
// type: "number",
// maximum: 100
// }Error mode
The errorMode configuration controls how the converter handles unsupported schemas and actions. By default, the error mode is set to 'throw'. To force the conversion of unsupported Valibot features, you can set it to 'ignore'.
Unsupported schemas usually return an empty JSON schema (
{}) and unsupported actions are usually ignored.
import { toJsonSchema } from '@valibot/to-json-schema';
import * as v from 'valibot';
toJsonSchema(v.file(), { errorMode: 'ignore' }); // {}
toJsonSchema(v.pipe(v.string(), v.creditCard()), { errorMode: 'ignore' }); // { type: "string" }Override functions
The package provides powerful override capabilities to customize the JSON Schema conversion process. You can override the conversion of specific schemas, actions, or references.
Override schema conversion
Handle unsupported schemas or customize conversion behavior:
import { toJsonSchema } from '@valibot/to-json-schema';
import * as v from 'valibot';
const ValibotSchema = v.object({ createdAt: v.date() });
toJsonSchema(ValibotSchema, {
overrideSchema(context) {
if (context.valibotSchema.type === 'date') {
return { type: 'string', format: 'date-time' };
}
},
});
// {
// $schema: "http://json-schema.org/draft-07/schema#",
// type: "object",
// properties: {
// createdAt: { type: "string" format: "date-time" }
// },
// required: ["createdAt"]
// }Override reference IDs
Customize reference IDs for OpenAPI or other specifications:
import { toJsonSchemaDefs } from '@valibot/to-json-schema';
import * as v from 'valibot';
const UserSchema = v.object({ name: v.string() });
toJsonSchemaDefs(
{ UserSchema },
{ overrideRef: (context) => `#/schemas/${context.referenceId}` }
);Enhanced metadata support
Use the generic metadata action to add title, description, and examples to your schemas or the individual title and description actions. Any other properties of the metadata action are added to the JSON Schema without further validation. This allows you to specify custom annotations and standard keywords such as format:
import { toJsonSchema } from '@valibot/to-json-schema';
import * as v from 'valibot';
const ValibotSchema = v.pipe(
v.string(),
v.email(),
v.metadata({
title: 'Email Schema',
description: 'A schema that validates email addresses.',
examples: ['[email protected]'],
'x-category': 'auth',
})
);
toJsonSchema(ValibotSchema);
// {
// $schema: "http://json-schema.org/draft-07/schema#",
// type: "string",
// format: "email",
// title: "Email Schema",
// description: "A schema that validates email addresses.",
// examples: ["[email protected]"],
// "x-category": "auth"
// }Definitions
Nested and recursive schemas can be broken in multiple reusable definitions.
import { toJsonSchema } from '@valibot/to-json-schema';
import * as v from 'valibot';
const EmailSchema = v.pipe(v.string(), v.email());
toJsonSchema(v.object({ email: EmailSchema }), {
definitions: { EmailSchema },
});
// {
// $schema: "http://json-schema.org/draft-07/schema#",
// type: "object",
// properties: {
// email: {
// $ref: "#/$defs/EmailSchema"
// }
// },
// required: ["email"],
// $defs: {
// EmailSchema: {
// type: "string",
// format: "email"
// }
// }
// }Definitions are not required for converting lazy schemas. Missing definitions will be generated automatically.
import { toJsonSchema } from '@valibot/to-json-schema';
import * as v from 'valibot';
const StringSchema = v.string();
toJsonSchema(v.object({ key: v.lazy(() => StringSchema) }));
// {
// $schema: "http://json-schema.org/draft-07/schema#",
// type: "object",
// properties: {
// key: {
// $ref: "#/$defs/0"
// }
// },
// required: ["key"],
// $defs: {
// 0: {
// type: "string"
// }
// }
// }Additional functions
`toStandardJsonSchema`
Converts a Valibot schema to the Standard JSON Schema format. This format is useful when working with tools and libraries that support the Standard JSON Schema specification.
import { toStandardJsonSchema } from '@valibot/to-json-schema';
import * as v from 'valibot';
const schema = toStandardJsonSchema(
v.object({
id: v.pipe(v.string(), v.uuid()),
name: v.pipe(v.string(), v.nonEmpty()),
age: v.optional(v.number()),
})
);`toJsonSchemaDefs`
Converts only the provided Valibot schema definitions to JSON Schema definitions, without wrapping them in a root schema. This is particularly useful for OpenAPI specifications where you need only the schema definitions.
import { toJsonSchemaDefs } from '@valibot/to-json-schema';
import * as v from 'valibot';
const EmailSchema = v.pipe(v.string(), v.email());
const UserSchema = v.object({
name: v.string(),
email: EmailSchema,
});
toJsonSchemaDefs({ EmailSchema, UserSchema });
// {
// EmailSchema: {
// type: "string",
// format: "email"
// },
// UserSchema: {
// type: "object",
// properties: {
// name: {
// type: "string"
// },
// email: {
// $ref: "#/$defs/EmailSchema"
// }
// },
// required: ["name", "email"]
// }
// }OpenAPI integration
For OpenAPI specifications, you can customize reference IDs:
import { toJsonSchemaDefs } from '@valibot/to-json-schema';
import * as v from 'valibot';
const ValibotSchema1 = v.string();
const ValibotSchema2 = v.number();
const ValibotSchema3 = v.tuple([ValibotSchema1, ValibotSchema2]);
toJsonSchemaDefs(
{ ValibotSchema1, ValibotSchema2, ValibotSchema3 },
{ overrideRef: (context) => `#/schemas/${context.referenceId}` }
);
// {
// ValibotSchema1: { type: "string" },
// ValibotSchema2: { type: "number" },
// ValibotSchema3: {
// type: "array",
// items: [
// { $ref: "#/schemas/ValibotSchema1" },
// { $ref: "#/schemas/ValibotSchema2" }
// ],
// minItems: 2
// }
// }Global definitions
For advanced use cases, you can manage global schema definitions that will be automatically used when converting schemas. This is particularly useful for larger projects with many reusable schemas.
import { addGlobalDefs, toJsonSchema } from '@valibot/to-json-schema';
import * as v from 'valibot';
const ValibotSchema1 = v.string();
const ValibotSchema2 = v.number();
addGlobalDefs({ ValibotSchema1, ValibotSchema2 });
const ValibotSchema3 = v.tuple([ValibotSchema1, ValibotSchema2]);
toJsonSchema(ValibotSchema3);
// {
// $schema: "http://json-schema.org/draft-07/schema#",
// type: "array",
// items: [
// { $ref: "#/$defs/ValibotSchema1" },
// { $ref: "#/$defs/ValibotSchema2" }
// ],
// minItems: 2,
// $defs: {
// ValibotSchema1: { type: "string" },
// ValibotSchema2: { type: "number" }
// }
// }You can also convert global definitions directly using toJsonSchemaDefs:
const globalDefs = getGlobalDefs();
if (globalDefs) {
const schemaDefs = toJsonSchemaDefs(globalDefs);
}--- METRICS ---
- Files Extracted: 6
- Estimated Token Budget: ~8167 tokens
- Canonical Reference: https://codewiki.google/github.com/open-circle/valibot