Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

json-schema-to-zod

Package Overview
Dependencies
Maintainers
1
Versions
46
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

json-schema-to-zod - npm Package Compare versions

Comparing version 2.0.0 to 2.0.1

45

dist/cjs/cli.js
#!/usr/bin/env node
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });

@@ -30,4 +39,4 @@ const jsonSchemaToZod_1 = require("./jsonSchemaToZod");

{
name: "recursion-depth",
short: "rd",
name: "depth",
short: "d",
value: "number",

@@ -48,20 +57,22 @@ description: "Maximum depth of recursion before falling back to z.any() - defaults to 0",

];
async function main() {
function main() {
var _a;
const args = (0, args_1.parseArgs)(params, process.argv, {});
const input = (_a = args.input) !== null && _a !== void 0 ? _a : (await (0, args_1.readPipe)());
const jsonSchema = (0, args_1.parseOrReadJSON)(input);
const zodSchema = (0, jsonSchemaToZod_1.jsonSchemaToZod)(jsonSchema, {
module: args.module,
name: args.name,
recursionDepth: args["recursion-depth"],
return __awaiter(this, void 0, void 0, function* () {
const args = (0, args_1.parseArgs)(params, process.argv, {});
const input = (_a = args.input) !== null && _a !== void 0 ? _a : (yield (0, args_1.readPipe)());
const jsonSchema = (0, args_1.parseOrReadJSON)(input);
const zodSchema = (0, jsonSchemaToZod_1.jsonSchemaToZod)(jsonSchema, {
module: args.module,
name: args.name,
recursionDepth: args["recursion-depth"],
});
if (args.output) {
(0, fs_1.mkdirSync)((0, path_1.dirname)(args.output), { recursive: true });
(0, fs_1.writeFileSync)(args.output, zodSchema);
}
else {
console.log(zodSchema);
}
});
if (args.output) {
(0, fs_1.mkdirSync)((0, path_1.dirname)(args.output), { recursive: true });
(0, fs_1.writeFileSync)(args.output, zodSchema);
}
else {
console.log(zodSchema);
}
}
void main();

@@ -1,6 +0,3 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.printParams = exports.readPipe = exports.parseOrReadJSON = exports.parseArgs = void 0;
const fs_1 = require("fs");
function parseArgs(params, args, help) {
import { statSync, readFileSync } from "fs";
export function parseArgs(params, args, help) {
const result = {};

@@ -63,13 +60,11 @@ if (help) {

}
exports.parseArgs = parseArgs;
function parseOrReadJSON(jsonOrPath) {
export function parseOrReadJSON(jsonOrPath) {
var _a;
jsonOrPath = jsonOrPath.trim();
if ((_a = (0, fs_1.statSync)(jsonOrPath, { throwIfNoEntry: false })) === null || _a === void 0 ? void 0 : _a.isFile()) {
jsonOrPath = (0, fs_1.readFileSync)(jsonOrPath, "utf-8");
if ((_a = statSync(jsonOrPath, { throwIfNoEntry: false })) === null || _a === void 0 ? void 0 : _a.isFile()) {
jsonOrPath = readFileSync(jsonOrPath, "utf-8");
}
return JSON.parse(jsonOrPath);
}
exports.parseOrReadJSON = parseOrReadJSON;
function readPipe() {
export function readPipe() {
return new Promise((resolve, reject) => {

@@ -89,4 +84,3 @@ let buf = "";

}
exports.readPipe = readPipe;
function printParams(params) {
export function printParams(params) {
var _a;

@@ -106,2 +100,1 @@ const longest = params.reduce((n, p) => (p.name.length > n ? p.name.length : n), 5);

}
exports.printParams = printParams;
#!/usr/bin/env node
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

@@ -12,7 +11,6 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }

};
Object.defineProperty(exports, "__esModule", { value: true });
const jsonSchemaToZod_1 = require("./jsonSchemaToZod");
const fs_1 = require("fs");
const path_1 = require("path");
const args_1 = require("./args");
import { jsonSchemaToZod } from "./jsonSchemaToZod";
import { writeFileSync, mkdirSync } from "fs";
import { dirname } from "path";
import { parseArgs, parseOrReadJSON, readPipe } from "./args";
const params = [

@@ -40,4 +38,4 @@ {

{
name: "recursion-depth",
short: "rd",
name: "depth",
short: "d",
value: "number",

@@ -61,6 +59,6 @@ description: "Maximum depth of recursion before falling back to z.any() - defaults to 0",

return __awaiter(this, void 0, void 0, function* () {
const args = (0, args_1.parseArgs)(params, process.argv, {});
const input = (_a = args.input) !== null && _a !== void 0 ? _a : (yield (0, args_1.readPipe)());
const jsonSchema = (0, args_1.parseOrReadJSON)(input);
const zodSchema = (0, jsonSchemaToZod_1.jsonSchemaToZod)(jsonSchema, {
const args = parseArgs(params, process.argv, {});
const input = (_a = args.input) !== null && _a !== void 0 ? _a : (yield readPipe());
const jsonSchema = parseOrReadJSON(input);
const zodSchema = jsonSchemaToZod(jsonSchema, {
module: args.module,

@@ -71,4 +69,4 @@ name: args.name,

if (args.output) {
(0, fs_1.mkdirSync)((0, path_1.dirname)(args.output), { recursive: true });
(0, fs_1.writeFileSync)(args.output, zodSchema);
mkdirSync(dirname(args.output), { recursive: true });
writeFileSync(args.output, zodSchema);
}

@@ -75,0 +73,0 @@ else {

@@ -1,8 +0,5 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseSchema = exports.jsonSchemaToZod = void 0;
const jsonSchemaToZod_1 = require("./jsonSchemaToZod");
Object.defineProperty(exports, "jsonSchemaToZod", { enumerable: true, get: function () { return jsonSchemaToZod_1.jsonSchemaToZod; } });
const parseSchema_1 = require("./parsers/parseSchema");
Object.defineProperty(exports, "parseSchema", { enumerable: true, get: function () { return parseSchema_1.parseSchema; } });
exports.default = jsonSchemaToZod_1.jsonSchemaToZod;
import { jsonSchemaToZod } from "./jsonSchemaToZod";
export { jsonSchemaToZod };
import { parseSchema } from "./parsers/parseSchema";
export { parseSchema };
export default jsonSchemaToZod;

@@ -1,2 +0,1 @@

"use strict";
var __rest = (this && this.__rest) || function (s, e) {

@@ -13,8 +12,6 @@ var t = {};

};
Object.defineProperty(exports, "__esModule", { value: true });
exports.jsonSchemaToZod = void 0;
const parseSchema_1 = require("./parsers/parseSchema");
const jsonSchemaToZod = (schema, _a = {}) => {
import { parseSchema } from "./parsers/parseSchema";
export const jsonSchemaToZod = (schema, _a = {}) => {
var { module = true, name } = _a, rest = __rest(_a, ["module", "name"]);
let result = (0, parseSchema_1.parseSchema)(schema, Object.assign({ module,
let result = parseSchema(schema, Object.assign({ module,
name, path: [], seen: new Map() }, rest));

@@ -40,2 +37,1 @@ if (module) {

};
exports.jsonSchemaToZod = jsonSchemaToZod;

@@ -1,6 +0,3 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseAllOf = void 0;
const parseSchema_1 = require("./parseSchema");
const half_1 = require("../utils/half");
import { parseSchema } from "./parseSchema";
import { half } from "../utils/half";
const originalIndex = Symbol("Original index");

@@ -23,3 +20,3 @@ const ensureOriginalIndex = (arr) => {

};
function parseAllOf(schema, refs) {
export function parseAllOf(schema, refs) {
if (schema.allOf.length === 0) {

@@ -30,6 +27,6 @@ return "z.never()";

const item = schema.allOf[0];
return (0, parseSchema_1.parseSchema)(item, Object.assign(Object.assign({}, refs), { path: [...refs.path, "allOf", item[originalIndex]] }));
return parseSchema(item, Object.assign(Object.assign({}, refs), { path: [...refs.path, "allOf", item[originalIndex]] }));
}
else {
const [left, right] = (0, half_1.half)(ensureOriginalIndex(schema.allOf));
const [left, right] = half(ensureOriginalIndex(schema.allOf));
return `z.intersection(${parseAllOf({ allOf: left }, refs)}, ${parseAllOf({

@@ -40,2 +37,1 @@ allOf: right,

}
exports.parseAllOf = parseAllOf;

@@ -1,14 +0,10 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseAnyOf = void 0;
const parseSchema_1 = require("./parseSchema");
const parseAnyOf = (schema, refs) => {
import { parseSchema } from "./parseSchema";
export const parseAnyOf = (schema, refs) => {
return schema.anyOf.length
? schema.anyOf.length === 1
? (0, parseSchema_1.parseSchema)(schema.anyOf[0], Object.assign(Object.assign({}, refs), { path: [...refs.path, "anyOf", 0] }))
? parseSchema(schema.anyOf[0], Object.assign(Object.assign({}, refs), { path: [...refs.path, "anyOf", 0] }))
: `z.union([${schema.anyOf
.map((schema, i) => (0, parseSchema_1.parseSchema)(schema, Object.assign(Object.assign({}, refs), { path: [...refs.path, "anyOf", i] })))
.map((schema, i) => parseSchema(schema, Object.assign(Object.assign({}, refs), { path: [...refs.path, "anyOf", i] })))
.join(", ")}])`
: `z.any()`;
};
exports.parseAnyOf = parseAnyOf;

@@ -1,14 +0,11 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseArray = void 0;
const withMessage_1 = require("../utils/withMessage");
const parseSchema_1 = require("./parseSchema");
const parseArray = (schema, refs) => {
import { withMessage } from "../utils/withMessage";
import { parseSchema } from "./parseSchema";
export const parseArray = (schema, refs) => {
if (Array.isArray(schema.items)) {
return `z.tuple([${schema.items.map((v, i) => (0, parseSchema_1.parseSchema)(v, Object.assign(Object.assign({}, refs), { path: [...refs.path, "items", i] })))}])`;
return `z.tuple([${schema.items.map((v, i) => parseSchema(v, Object.assign(Object.assign({}, refs), { path: [...refs.path, "items", i] })))}])`;
}
let r = !schema.items
? "z.array(z.any())"
: `z.array(${(0, parseSchema_1.parseSchema)(schema.items, Object.assign(Object.assign({}, refs), { path: [...refs.path, "items"] }))})`;
r += (0, withMessage_1.withMessage)(schema, "minItems", ({ json }) => [
: `z.array(${parseSchema(schema.items, Object.assign(Object.assign({}, refs), { path: [...refs.path, "items"] }))})`;
r += withMessage(schema, "minItems", ({ json }) => [
`.min(${json}`,

@@ -18,3 +15,3 @@ ", ",

]);
r += (0, withMessage_1.withMessage)(schema, "maxItems", ({ json }) => [
r += withMessage(schema, "maxItems", ({ json }) => [
`.max(${json}`,

@@ -26,2 +23,1 @@ ", ",

};
exports.parseArray = parseArray;

@@ -1,7 +0,3 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseBoolean = void 0;
const parseBoolean = (_schema) => {
export const parseBoolean = (_schema) => {
return "z.boolean()";
};
exports.parseBoolean = parseBoolean;

@@ -1,7 +0,3 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseConst = void 0;
const parseConst = (schema) => {
export const parseConst = (schema) => {
return `z.literal(${JSON.stringify(schema.const)})`;
};
exports.parseConst = parseConst;

@@ -1,7 +0,3 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseDefault = void 0;
const parseDefault = (_schema) => {
export const parseDefault = (_schema) => {
return "z.any()";
};
exports.parseDefault = parseDefault;

@@ -1,5 +0,2 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseEnum = void 0;
const parseEnum = (schema) => {
export const parseEnum = (schema) => {
if (schema.enum.length === 0) {

@@ -21,2 +18,1 @@ return "z.never()";

};
exports.parseEnum = parseEnum;

@@ -1,9 +0,6 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseIfThenElse = void 0;
const parseSchema_1 = require("./parseSchema");
const parseIfThenElse = (schema, refs) => {
const $if = (0, parseSchema_1.parseSchema)(schema.if, Object.assign(Object.assign({}, refs), { path: [...refs.path, "if"] }));
const $then = (0, parseSchema_1.parseSchema)(schema.then, Object.assign(Object.assign({}, refs), { path: [...refs.path, "then"] }));
const $else = (0, parseSchema_1.parseSchema)(schema.else, Object.assign(Object.assign({}, refs), { path: [...refs.path, "else"] }));
import { parseSchema } from "./parseSchema";
export const parseIfThenElse = (schema, refs) => {
const $if = parseSchema(schema.if, Object.assign(Object.assign({}, refs), { path: [...refs.path, "if"] }));
const $then = parseSchema(schema.then, Object.assign(Object.assign({}, refs), { path: [...refs.path, "then"] }));
const $else = parseSchema(schema.else, Object.assign(Object.assign({}, refs), { path: [...refs.path, "else"] }));
return `z.union([${$then}, ${$else}]).superRefine((value,ctx) => {

@@ -18,2 +15,1 @@ const result = ${$if}.safeParse(value).success

};
exports.parseIfThenElse = parseIfThenElse;

@@ -1,10 +0,6 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseMultipleType = void 0;
const parseSchema_1 = require("./parseSchema");
const parseMultipleType = (schema, refs) => {
import { parseSchema } from "./parseSchema";
export const parseMultipleType = (schema, refs) => {
return `z.union([${schema.type
.map((type) => (0, parseSchema_1.parseSchema)(Object.assign(Object.assign({}, schema), { type }), refs))
.map((type) => parseSchema(Object.assign(Object.assign({}, schema), { type }), refs))
.join(", ")}])`;
};
exports.parseMultipleType = parseMultipleType;

@@ -1,8 +0,4 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseNot = void 0;
const parseSchema_1 = require("./parseSchema");
const parseNot = (schema, refs) => {
return `z.any().refine((value) => !${(0, parseSchema_1.parseSchema)(schema.not, Object.assign(Object.assign({}, refs), { path: [...refs.path, "not"] }))}.safeParse(value).success, "Invalid input: Should NOT be valid against schema")`;
import { parseSchema } from "./parseSchema";
export const parseNot = (schema, refs) => {
return `z.any().refine((value) => !${parseSchema(schema.not, Object.assign(Object.assign({}, refs), { path: [...refs.path, "not"] }))}.safeParse(value).success, "Invalid input: Should NOT be valid against schema")`;
};
exports.parseNot = parseNot;

@@ -1,7 +0,3 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseNull = void 0;
const parseNull = (_schema) => {
export const parseNull = (_schema) => {
return "z.null()";
};
exports.parseNull = parseNull;

@@ -1,12 +0,8 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseNullable = void 0;
const omit_1 = require("../utils/omit");
const parseSchema_1 = require("./parseSchema");
import { omit } from "../utils/omit";
import { parseSchema } from "./parseSchema";
/**
* For compatibility with open api 3.0 nullable
*/
const parseNullable = (schema, refs) => {
return `${(0, parseSchema_1.parseSchema)((0, omit_1.omit)(schema, "nullable"), refs)}.nullable()`;
export const parseNullable = (schema, refs) => {
return `${parseSchema(omit(schema, "nullable"), refs)}.nullable()`;
};
exports.parseNullable = parseNullable;

@@ -1,12 +0,9 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseNumber = void 0;
const withMessage_1 = require("../utils/withMessage");
const parseNumber = (schema) => {
import { withMessage } from "../utils/withMessage";
export const parseNumber = (schema) => {
let r = "z.number()";
if (schema.type === "integer") {
r += (0, withMessage_1.withMessage)(schema, "type", () => [".int(", ")"]);
r += withMessage(schema, "type", () => [".int(", ")"]);
}
else {
r += (0, withMessage_1.withMessage)(schema, "format", ({ value }) => {
r += withMessage(schema, "format", ({ value }) => {
if (value === "int64") {

@@ -17,3 +14,3 @@ return [".int(", ")"];

}
r += (0, withMessage_1.withMessage)(schema, "multipleOf", ({ value, json }) => {
r += withMessage(schema, "multipleOf", ({ value, json }) => {
if (value === 1) {

@@ -29,3 +26,3 @@ if (r.startsWith("z.number().int(")) {

if (schema.exclusiveMinimum === true) {
r += (0, withMessage_1.withMessage)(schema, "minimum", ({ json }) => [
r += withMessage(schema, "minimum", ({ json }) => [
`.gt(${json}`,

@@ -37,3 +34,3 @@ ", ",

else {
r += (0, withMessage_1.withMessage)(schema, "minimum", ({ json }) => [
r += withMessage(schema, "minimum", ({ json }) => [
`.gte(${json}`,

@@ -46,3 +43,3 @@ ", ",

else if (typeof schema.exclusiveMinimum === "number") {
r += (0, withMessage_1.withMessage)(schema, "exclusiveMinimum", ({ json }) => [
r += withMessage(schema, "exclusiveMinimum", ({ json }) => [
`.gt(${json}`,

@@ -55,3 +52,3 @@ ", ",

if (schema.exclusiveMaximum === true) {
r += (0, withMessage_1.withMessage)(schema, "maximum", ({ json }) => [
r += withMessage(schema, "maximum", ({ json }) => [
`.lt(${json}`,

@@ -63,3 +60,3 @@ ", ",

else {
r += (0, withMessage_1.withMessage)(schema, "maximum", ({ json }) => [
r += withMessage(schema, "maximum", ({ json }) => [
`.lte(${json}`,

@@ -72,3 +69,3 @@ ", ",

else if (typeof schema.exclusiveMaximum === "number") {
r += (0, withMessage_1.withMessage)(schema, "exclusiveMaximum", ({ json }) => [
r += withMessage(schema, "exclusiveMaximum", ({ json }) => [
`.lt(${json}`,

@@ -81,2 +78,1 @@ ", ",

};
exports.parseNumber = parseNumber;

@@ -1,9 +0,6 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseObject = void 0;
const parseAnyOf_1 = require("./parseAnyOf");
const parseOneOf_1 = require("./parseOneOf");
const parseSchema_1 = require("./parseSchema");
const parseAllOf_1 = require("./parseAllOf");
function parseObject(objectSchema, refs) {
import { parseAnyOf } from "./parseAnyOf";
import { parseOneOf } from "./parseOneOf";
import { its, parseSchema } from "./parseSchema";
import { parseAllOf } from "./parseAllOf";
export function parseObject(objectSchema, refs) {
let properties = undefined;

@@ -19,3 +16,3 @@ if (objectSchema.properties) {

const propSchema = objectSchema.properties[key];
const result = `${JSON.stringify(key)}: ${(0, parseSchema_1.parseSchema)(propSchema, Object.assign(Object.assign({}, refs), { path: [...refs.path, "properties", key] }))}`;
const result = `${JSON.stringify(key)}: ${parseSchema(propSchema, Object.assign(Object.assign({}, refs), { path: [...refs.path, "properties", key] }))}`;
const hasDefault = (typeof propSchema === "object" &&

@@ -37,3 +34,3 @@ propSchema.default !== undefined) ||

const additionalProperties = objectSchema.additionalProperties !== undefined
? (0, parseSchema_1.parseSchema)(objectSchema.additionalProperties, Object.assign(Object.assign({}, refs), { path: [...refs.path, "additionalProperties"] }))
? parseSchema(objectSchema.additionalProperties, Object.assign(Object.assign({}, refs), { path: [...refs.path, "additionalProperties"] }))
: undefined;

@@ -45,3 +42,3 @@ let patternProperties = undefined;

key,
(0, parseSchema_1.parseSchema)(value, Object.assign(Object.assign({}, refs), { path: [...refs.path, "patternProperties", key] })),
parseSchema(value, Object.assign(Object.assign({}, refs), { path: [...refs.path, "patternProperties", key] })),
];

@@ -144,4 +141,4 @@ }, {}));

: "z.record(z.any())";
if (parseSchema_1.its.an.anyOf(objectSchema)) {
output += `.and(${(0, parseAnyOf_1.parseAnyOf)(Object.assign(Object.assign({}, objectSchema), { anyOf: objectSchema.anyOf.map((x) => typeof x === "object" &&
if (its.an.anyOf(objectSchema)) {
output += `.and(${parseAnyOf(Object.assign(Object.assign({}, objectSchema), { anyOf: objectSchema.anyOf.map((x) => typeof x === "object" &&
!x.type &&

@@ -151,4 +148,4 @@ (x.properties || x.additionalProperties || x.patternProperties)

}
if (parseSchema_1.its.a.oneOf(objectSchema)) {
output += `.and(${(0, parseOneOf_1.parseOneOf)(Object.assign(Object.assign({}, objectSchema), { oneOf: objectSchema.oneOf.map((x) => typeof x === "object" &&
if (its.a.oneOf(objectSchema)) {
output += `.and(${parseOneOf(Object.assign(Object.assign({}, objectSchema), { oneOf: objectSchema.oneOf.map((x) => typeof x === "object" &&
!x.type &&

@@ -158,4 +155,4 @@ (x.properties || x.additionalProperties || x.patternProperties)

}
if (parseSchema_1.its.an.allOf(objectSchema)) {
output += `.and(${(0, parseAllOf_1.parseAllOf)(Object.assign(Object.assign({}, objectSchema), { allOf: objectSchema.allOf.map((x) => typeof x === "object" &&
if (its.an.allOf(objectSchema)) {
output += `.and(${parseAllOf(Object.assign(Object.assign({}, objectSchema), { allOf: objectSchema.allOf.map((x) => typeof x === "object" &&
!x.type &&

@@ -167,2 +164,1 @@ (x.properties || x.additionalProperties || x.patternProperties)

}
exports.parseObject = parseObject;

@@ -1,12 +0,9 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseOneOf = void 0;
const parseSchema_1 = require("./parseSchema");
const parseOneOf = (schema, refs) => {
import { parseSchema } from "./parseSchema";
export const parseOneOf = (schema, refs) => {
return schema.oneOf.length
? schema.oneOf.length === 1
? (0, parseSchema_1.parseSchema)(schema.oneOf[0], Object.assign(Object.assign({}, refs), { path: [...refs.path, "oneOf", 0] }))
? parseSchema(schema.oneOf[0], Object.assign(Object.assign({}, refs), { path: [...refs.path, "oneOf", 0] }))
: `z.any().superRefine((x, ctx) => {
const schemas = [${schema.oneOf
.map((schema, i) => (0, parseSchema_1.parseSchema)(schema, Object.assign(Object.assign({}, refs), { path: [...refs.path, "oneOf", i] })))
.map((schema, i) => parseSchema(schema, Object.assign(Object.assign({}, refs), { path: [...refs.path, "oneOf", i] })))
.join(", ")}];

@@ -31,2 +28,1 @@ const errors = schemas.reduce(

};
exports.parseOneOf = parseOneOf;

@@ -1,21 +0,18 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.its = exports.parseSchema = void 0;
const parseAnyOf_1 = require("./parseAnyOf");
const parseBoolean_1 = require("./parseBoolean");
const parseDefault_1 = require("./parseDefault");
const parseMultipleType_1 = require("./parseMultipleType");
const parseNot_1 = require("./parseNot");
const parseNull_1 = require("./parseNull");
const parseAllOf_1 = require("./parseAllOf");
const parseArray_1 = require("./parseArray");
const parseConst_1 = require("./parseConst");
const parseEnum_1 = require("./parseEnum");
const parseIfThenElse_1 = require("./parseIfThenElse");
const parseNumber_1 = require("./parseNumber");
const parseObject_1 = require("./parseObject");
const parseString_1 = require("./parseString");
const parseOneOf_1 = require("./parseOneOf");
const parseNullable_1 = require("./parseNullable");
const parseSchema = (schema, refs = { seen: new Map(), path: [] }) => {
import { parseAnyOf } from "./parseAnyOf";
import { parseBoolean } from "./parseBoolean";
import { parseDefault } from "./parseDefault";
import { parseMultipleType } from "./parseMultipleType";
import { parseNot } from "./parseNot";
import { parseNull } from "./parseNull";
import { parseAllOf } from "./parseAllOf";
import { parseArray } from "./parseArray";
import { parseConst } from "./parseConst";
import { parseEnum } from "./parseEnum";
import { parseIfThenElse } from "./parseIfThenElse";
import { parseNumber } from "./parseNumber";
import { parseObject } from "./parseObject";
import { parseString } from "./parseString";
import { parseOneOf } from "./parseOneOf";
import { parseNullable } from "./parseNullable";
export const parseSchema = (schema, refs = { seen: new Map(), path: [] }) => {
if (typeof schema !== "object")

@@ -51,3 +48,2 @@ return schema ? "z.any()" : "z.never()";

};
exports.parseSchema = parseSchema;
const addMeta = (schema, parsed) => {

@@ -66,53 +62,53 @@ if (schema.description) {

const selectParser = (schema, refs) => {
if (exports.its.a.nullable(schema)) {
return (0, parseNullable_1.parseNullable)(schema, refs);
if (its.a.nullable(schema)) {
return parseNullable(schema, refs);
}
else if (exports.its.an.object(schema)) {
return (0, parseObject_1.parseObject)(schema, refs);
else if (its.an.object(schema)) {
return parseObject(schema, refs);
}
else if (exports.its.an.array(schema)) {
return (0, parseArray_1.parseArray)(schema, refs);
else if (its.an.array(schema)) {
return parseArray(schema, refs);
}
else if (exports.its.an.anyOf(schema)) {
return (0, parseAnyOf_1.parseAnyOf)(schema, refs);
else if (its.an.anyOf(schema)) {
return parseAnyOf(schema, refs);
}
else if (exports.its.an.allOf(schema)) {
return (0, parseAllOf_1.parseAllOf)(schema, refs);
else if (its.an.allOf(schema)) {
return parseAllOf(schema, refs);
}
else if (exports.its.a.oneOf(schema)) {
return (0, parseOneOf_1.parseOneOf)(schema, refs);
else if (its.a.oneOf(schema)) {
return parseOneOf(schema, refs);
}
else if (exports.its.a.not(schema)) {
return (0, parseNot_1.parseNot)(schema, refs);
else if (its.a.not(schema)) {
return parseNot(schema, refs);
}
else if (exports.its.an.enum(schema)) {
return (0, parseEnum_1.parseEnum)(schema); //<-- needs to come before primitives
else if (its.an.enum(schema)) {
return parseEnum(schema); //<-- needs to come before primitives
}
else if (exports.its.a.const(schema)) {
return (0, parseConst_1.parseConst)(schema);
else if (its.a.const(schema)) {
return parseConst(schema);
}
else if (exports.its.a.multipleType(schema)) {
return (0, parseMultipleType_1.parseMultipleType)(schema, refs);
else if (its.a.multipleType(schema)) {
return parseMultipleType(schema, refs);
}
else if (exports.its.a.primitive(schema, "string")) {
return (0, parseString_1.parseString)(schema);
else if (its.a.primitive(schema, "string")) {
return parseString(schema);
}
else if (exports.its.a.primitive(schema, "number") ||
exports.its.a.primitive(schema, "integer")) {
return (0, parseNumber_1.parseNumber)(schema);
else if (its.a.primitive(schema, "number") ||
its.a.primitive(schema, "integer")) {
return parseNumber(schema);
}
else if (exports.its.a.primitive(schema, "boolean")) {
return (0, parseBoolean_1.parseBoolean)(schema);
else if (its.a.primitive(schema, "boolean")) {
return parseBoolean(schema);
}
else if (exports.its.a.primitive(schema, "null")) {
return (0, parseNull_1.parseNull)(schema);
else if (its.a.primitive(schema, "null")) {
return parseNull(schema);
}
else if (exports.its.a.conditional(schema)) {
return (0, parseIfThenElse_1.parseIfThenElse)(schema, refs);
else if (its.a.conditional(schema)) {
return parseIfThenElse(schema, refs);
}
else {
return (0, parseDefault_1.parseDefault)(schema);
return parseDefault(schema);
}
};
exports.its = {
export const its = {
an: {

@@ -119,0 +115,0 @@ object: (x) => x.type === "object",

@@ -1,8 +0,5 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseString = void 0;
const withMessage_1 = require("../utils/withMessage");
const parseString = (schema) => {
import { withMessage } from "../utils/withMessage";
export const parseString = (schema) => {
let r = "z.string()";
r += (0, withMessage_1.withMessage)(schema, "format", ({ value }) => {
r += withMessage(schema, "format", ({ value }) => {
switch (value) {

@@ -25,3 +22,3 @@ case "email":

});
r += (0, withMessage_1.withMessage)(schema, "pattern", ({ json }) => [
r += withMessage(schema, "pattern", ({ json }) => [
`.regex(new RegExp(${json})`,

@@ -31,3 +28,3 @@ ", ",

]);
r += (0, withMessage_1.withMessage)(schema, "minLength", ({ json }) => [
r += withMessage(schema, "minLength", ({ json }) => [
`.min(${json}`,

@@ -37,3 +34,3 @@ ", ",

]);
r += (0, withMessage_1.withMessage)(schema, "maxLength", ({ json }) => [
r += withMessage(schema, "maxLength", ({ json }) => [
`.max(${json}`,

@@ -45,2 +42,1 @@ ", ",

};
exports.parseString = parseString;

@@ -1,2 +0,1 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
export {};

@@ -1,7 +0,3 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.half = void 0;
const half = (arr) => {
export const half = (arr) => {
return [arr.slice(0, arr.length / 2), arr.slice(arr.length / 2)];
};
exports.half = half;

@@ -1,5 +0,1 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.omit = void 0;
const omit = (obj, ...keys) => Object.fromEntries(Object.entries(obj).filter(([key]) => !keys.includes(key)));
exports.omit = omit;
export const omit = (obj, ...keys) => Object.fromEntries(Object.entries(obj).filter(([key]) => !keys.includes(key)));

@@ -1,5 +0,2 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.withMessage = void 0;
function withMessage(schema, key, get) {
export function withMessage(schema, key, get) {
var _a;

@@ -24,2 +21,1 @@ const value = schema[key];

}
exports.withMessage = withMessage;
{
"name": "json-schema-to-zod",
"version": "2.0.0",
"version": "2.0.1",
"description": "Converts JSON schema objects or files into Zod schemas",

@@ -5,0 +5,0 @@ "types": "dist/types/index.d.ts",

@@ -10,4 +10,8 @@ # Json-Schema-to-Zod

A runtime package and CLI tool to convert JSON schema (draft 4+) objects or files into Zod schemas in the form of JavaScript code. Uses Prettier for formatting.
A runtime package and CLI tool to convert JSON schema (draft 4+) objects or files into Zod schemas in the form of JavaScript code.
Before v2 it used [`prettier`](https://www.npmjs.com/package/prettier) for formatting and [`json-refs`](https://www.npmjs.com/package/json-refs) to resolve schemas. To replicate the previous behaviour, please use their respective CLI tools.
Since v2 the CLI supports piped JSON.
## Usage

@@ -21,25 +25,27 @@

Installation:
#### Simplest example
> `npm i -g json-schema-to-zod`
Example:
> `json-schema-to-zod -i mySchema.json -o mySchema.ts`
> `json-schema-to-zod -s myJson.json -t mySchema.ts`
#### Example with $refs resolved and output formatted
> `npm i -g json-schema-to-zod json-refs prettier`
> `json-refs resolve mySchema.json | json-schema-to-zod | prettier --parser typescript > mySchema.ts`
#### Options
| Flag | Shorthand | Function |
| -------------------- | --------- | --------------------------------------------------------------------------------------- |
| `--source` | `-s` | Source file name (required) |
| `--target` | `-t` | Target file name |
| `--name` | `-n` | The name of the schema in the output |
| `--deref` | `-d` | Uses `json-schema-ref-parser` to dereference the schema |
| `--without-defaults` | `-wd` | Ignore default values in the schema |
| `--recursionDepth` | `-rd` | Maximum depth of recursion in schema before falling back to `z.any()`. Defaults to 0. ` |
| `--module` | `-m` | Force module syntax (`"esm"` or `"cjs"`) |
| Flag | Shorthand | Function |
| ---------- | --------- | --------------------------------------------------------------------------------------- |
| `--input` | `-i` | JSON or a source file path (required if no data is piped) |
| `--output` | `-t` | Target file name |
| `--name` | `-n` | The name of the schema in the output |
| `--depth` | `-d` | Maximum depth of recursion in schema before falling back to `z.any()`. Defaults to 0. ` |
| `--module` | `-m` | Force module syntax (`"esm"` or `"cjs"`) |
### Programmatic
`jsonSchemaToZod` will output the full module code, including a Zod import. If you only need the Zod schema itself, try one of the parsers directly. If you need to deref your JSON schema, try awaiting `jsonSchemaDereffed`.
`jsonSchemaToZod` will output the full module code, including a Zod import. If you only need the Zod schema itself, try one of the parsers directly. If you need to deref your JSON schema, try using `json-refs` `resolve` function before passing in the schema.

@@ -49,3 +55,2 @@ ```typescript

jsonSchemaToZod,
jsonSchemaToZodDereffed,
parseSchema,

@@ -65,8 +70,6 @@ } from "json-schema-to-zod";

const dereffed = await jsonSchemaToZodDereffed(myObject);
const schema = parseSchema(myObject);
```
`module`/`dereffed` =
#### `module`

@@ -79,3 +82,3 @@ ```typescript

`schema` =
#### `schema`

@@ -86,11 +89,11 @@ ```typescript

#### Overriding a parser
### Overriding a parser
You can pass a `ParserOverride` to the `overrideParser` option, which is a function that receives the current schema node and the reference object, and should return a string when it wants to replace a default output. If the default output should be used for the node, just return nothing.
### At Runtime
### Use at Runtime
The output of this package is not meant to be used at runtime. JSON Schema and Zod does not overlap 100% and the scope of the parsers are purposefully limited in order to help the author avoid a permanent state of chaotic insanity. As this may cause some details of the original schema to be lost in translation, it is instead recommended to use tools such as (Ajv)[https://ajv.js.org/] to validate your runtime values directly against the original JSON Schema.
That said, it's possible to use `eval`. Here's an example that you shouldn't use:
That said, it's possible in most cases to use `eval`. Here's an example that you shouldn't use:

@@ -97,0 +100,0 @@ ```typescript

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc