@gcornut/valibot-json-schema

中文文档
0.42.0发布于 2024/09/17TypeScriptESM + CJS构建来源已验证近 30 天下载 13万

[!CAUTION] > This project is now deprecated as Valibot now has an official JSON schema converter in the @valibot/to-json-schema. > The command line interface is moved to the p

原始使用文档
文档目录11 节
  1. Command Line Tool
  2. ESM and TypeScript input module
  3. CLI parameters
  4. Programmatic usage
  5. Advanced options
  6. Strict object types
  7. Ignore unknown validation
  8. Common type strategies
  9. Custom schema conversion
  10. Custom validation conversion
  11. Supported features

[!CAUTION] This project is now deprecated as Valibot now has an official JSON schema converter in the @valibot/to-json-schema. The command line interface is moved to the project @gcornut/cli-valibot-to-json-schema.

@gcornut/valibot-json-schema

CLI and JS utility to convert Valibot schemas to JSON schema (draft 07).

Some of the features of Valibot can't be converted to JSON schema. JS-specific types like blob or nan obviously can't have an equivalent.
See supported features for more info.

Command Line Tool

This lib exports a CLI that can be used to quickly convert JS modules defining valibot schemas into a JSON schema.

# Convert valibot schemas to JSON schema
npx @gcornut/valibot-json-schema to-json-schema ./schemas.js

This outputs a conversion of the Valibot schemas into JSON schema. If the default export is a Valibot schemas, it is used as the root definition. Other exported Valibot schemas are converted in the JSON schema definitions section.

See detailed input and output:

Input file ./schemas.js:

import * as v from 'valibot';

export const AString = v.string();
const AnObject = v.object({ aString: AString });
export default AnObject;

Output conversion:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "definitions": {
    "AString": {
      "type": "string"
    }
  },
  "properties": {
    "aString": {
      "$ref": "#/definitions/AString"
    }
  },
  "required": [
    "aString"
  ],
  "type": "object"
}

AnObject is the default export in the source module, so it is converted as the root definition. AString is exported separately, so it is exported to the definitions section.

ESM and TypeScript input module

The valibot-json-schema CLI loads the input JS module using standard NodeJS CommonJS require. This means you will have issues with ESM or TypeScript modules.

To remedy that, you will either have to preinstall ebuild-runner and esbuild (so that the program can use them) or use a Node-compatible runtime that support these modules (ex: bun, replacing npx with bunx).

Example:

# Convert from TS/ESM module using bunx
bunx @gcornut/valibot-json-schema to-json-schema ./schemas.ts

# Convert from TS/ESM module with esbuild-runner preinstalled
npm install esbuild esbuild-runner
npx @gcornut/valibot-json-schema to-json-schema ./schemas.ts

# Convert from TS/ESM module using `yarn dlx` multi-package feature 
yarn dlx -p esbuild -p esbuild-runner -p @gcornut/valibot-json-schema valibot-json-schema to-json-schema ./schemas.ts

CLI parameters

Use -o <file> option to output the JSON schema to a file instead of stdout.

Use -t <type> option to select the root definitions from the module exports (defaults to the "default" export). Example: -t foo.bar will get the property bar on the foo export of the input JS module.

Use -d <type> option to select the definitions from the module exports (instead of using all non-default export). Example: -d foo.bar will get the property bar on the foo export of the input JS module.

See Advanced options for more options.

Programmatic usage

Use the toJSONSchema function to convert a Valibot schema into JSON schema (v7):

import { toJSONSchema } from '@gcornut/valibot-json-schema';
import { string } from 'valibot';

toJSONSchema({ schema: string() })
// {
//    $schema: 'http://json-schema.org/draft-07/schema#',
//    type: 'string',
// }

If you have many named schemas to convert, you can use the definitions option schema to list as a plain object so that both the schema names (object keys) and schema definitions (object values) are exported to JSON schema.

import { toJSONSchema } from '@gcornut/valibot-json-schema';
import { number } from 'valibot';

const Number = number();
toJSONSchema({ definitions: { Number } });
// {
//    $schema: 'http://json-schema.org/draft-07/schema#',
//    definitions: { Number: { type: 'number' } },
// }

See Advanced options for more options.

Advanced options

Strict object types

Using the strictObjectTypes option (--strictObjectTypes in the CLI), you can force all object type block unknown keys (additionalProperties: false).

Ignore unknown validation

You might want to have advanced validation in your valibot schema that JSON schema can't support ( like custom()). By default, toJSONSchema() will throw an error to let you know these can't be converted to JSON schema.

Using the ignoreUnknownValidation option (--ignoreUnknownValidation in the CLI), you can ignore unsupported valibot validations.

If you preferred to only ignore a specific type of validation, you can use the customValidationConversion option.

Common type strategies

Many JS types don't have a direct equivalent in JSON and toJSONSchema() will throw an error when encountering any of those. However, some of these types have common strategies to convert them.

Using the dateStrategy option (--dateStrategy in the CLI), you can choose to convert JS Date objects into a string ( with the date-time format) or into an integer (with the unix-time format).

Using the undefinedStrategy option (--undefinedStrategy in the CLI), you can choose to convert undefined to the " any" schema (no validation) or to the null type.

Using the bigintStrategy option (--bigintStrategy in the CLI), you can choose to convert JS BigInt values to an integer (with the int64 format) or into a string.

Custom schema conversion

In some cases, you might want to provide custom schema conversion to override standard schema conversion or to add conversion of unsupported schemas.

Using the customSchemaConversion option, you can provide a custom schema converter for any valibot schema type.

Example: converting JS Set schema into an array schema

import { set, string } from 'valibot';

toJSONSchema({
    schema: set(string()),
    customSchemaConversion: {
        // Treat set type like an array
        set: (schema, converter) => converter(array(schema.value))
    },
})
// => { type: 'array', items: { type: 'string' } }

Custom validation conversion

Using the customValidationConversion option, you can provide a custom validation converter for any valibot validation type.

Example: ignoring the valibot custom() validation on all string schema

import { string, custom, pipe } from 'valibot';

toJSONSchema({
    schema: pipe(string(), custom(myCustomStringValidation)),
    customValidationConversion: {
        string: { custom: () => ({}) }
    },
})
// => { type: 'string' }

Supported features

Some converted schema might have slightly different behavior in a JSON schema validator, especially on string formats (email, ipv4, date, etc.) since their implementation is different from valibot implementation.

Here is the list of supported Valibot features (some have partial support):

featurestatus
any schema✅ supported
null schema✅ supported
number schema✅ supported
bigint schema⚠️ with bigintStrategy option provided
string schema✅ supported
boolean schema✅ supported
literal schema⚠️ partial: only JSON-compatible literal are supported
nullable schema✅ supported
nullish schema✅ supported
optional schema✅ supported
never schema⚠️ partial: only inside object rest or tuple rest params
picklist schema⚠️ partial: only JSON-compatible literal are supported
enum_ schema✅ supported
union schema✅ supported
variant schema⚠️ partial: converted just like an union
intersect schema✅ supported
array schema✅ supported
tuple schema✅ supported
object schema✅ supported
record schema⚠️ partial: only string key are allowed, applicable to plain object only, not arrays
lazy schema⚠️ partial: only if the schema inside is referenced in definitions
date schema⚠️ with dateStrategy option provided
length validation✅ supported
maxLength validation✅ supported
minLength validation✅ supported
regex validation⚠️ partial: only on RegExp features supported by JSON schema
value validation⚠️ partial: only on string, number and boolean
minValue validation⚠️ partial: only on number
maxValue validation⚠️ partial: only on number
multipleOf validation✅ supported
integer validation✅ supported
email validation✅ supported (JSON schema format)
isoDate validation✅ supported (JSON schema format)
isoTimestamp validation✅ supported (JSON schema format)
ipv4 validation✅ supported (JSON schema format)
ipv6 validation✅ supported (JSON schema format)
uuid validation✅ supported (JSON schema format)
description metadata✅ supported

版本与发布记录

@gcornut/valibot-json-schema 共发布 77 个版本,首次发布于 2023/10/15;过去 12 个月发布了 0 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.42.0latest2024/09/172 年前
0.41.2-snapshot.2snapshot2024/09/172 年前
0.41.2-snapshot.12024/09/172 年前
0.41.2-snapshot.02024/09/172 年前
0.41.12024/09/062 年前
0.41.1-snapshot.22024/09/052 年前

其他发布通道:alpha → 0.0.27-alpha.0,prerelease → 0.0.28-rc.3,snapshot → 0.41.2-snapshot.2。

关于 @gcornut/valibot-json-schema 的常见问题

@gcornut/valibot-json-schema 是什么?

[!CAUTION] > This project is now deprecated as Valibot now has an official JSON schema converter in the @valibot/to-json-schema. > The command line interface is moved to the p

如何安装 @gcornut/valibot-json-schema?

在项目目录运行 npm install @gcornut/valibot-json-schema,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 valibot-json-schema,可以用 npx valibot-json-schema 直接运行。

@gcornut/valibot-json-schema 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@gcornut/valibot-json-schema 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@gcornut/valibot-json-schema 可以商用吗?

@gcornut/valibot-json-schema 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@gcornut/valibot-json-schema 的下载量有多少?

根据 npm 官方下载统计,@gcornut/valibot-json-schema 在 2026/10/16 – 2026/11/14 这 30 天内被下载 130,167 次,日均约 4,339 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gcornut/valibot-json-schema 还在维护吗?

最新版本 0.42.0 发布于 2024/09/17(2 年前);至今共发布 77 个版本,其中过去 12 个月发布了 0 个;首次发布于 2023/10/15。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。