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 0.6.2 to 0.6.3

0

cli.d.ts
#!/usr/bin/env node
export {};

218

cli.js

@@ -9,137 +9,157 @@ #!/usr/bin/env node

if (sourceArgumentIndex === -1) {
sourceArgumentIndex = process.argv.indexOf("-s");
sourceArgumentIndex = process.argv.indexOf("-s");
}
if (sourceArgumentIndex === -1) {
console.error("Must supply source file with --source [filename] or -s [filename}");
process.exit(1);
console.error(
"Must supply source file with --source [filename] or -s [filename}"
);
process.exit(1);
}
const sourceFilePath = process.argv[sourceArgumentIndex + 1];
if (!sourceFilePath) {
console.error(`No source path was provided after ${process.argv[sourceArgumentIndex]}`);
process.exit(1);
console.error(
`No source path was provided after ${process.argv[sourceArgumentIndex]}`
);
process.exit(1);
}
const sourceFileExists = (0, fs_1.existsSync)(sourceFilePath);
if (!sourceFileExists) {
console.error(`${sourceFilePath} doesn't exist`);
process.exit(1);
console.error(`${sourceFilePath} doesn't exist`);
process.exit(1);
}
let sourceFileContent;
try {
sourceFileContent = (0, fs_1.readFileSync)(sourceFilePath, "utf-8");
sourceFileContent = (0, fs_1.readFileSync)(sourceFilePath, "utf-8");
} catch (e) {
console.error("Failed to read sourcefile");
console.error(e);
process.exit(1);
}
catch (e) {
console.error("Failed to read sourcefile");
console.error(e);
process.exit(1);
}
let sourceFileData;
try {
sourceFileData = JSON.parse(sourceFileContent);
sourceFileData = JSON.parse(sourceFileContent);
} catch (e) {
console.error("Failed to parse sourcefile contents");
console.error(e);
process.exit(1);
}
catch (e) {
console.error("Failed to parse sourcefile contents");
console.error(e);
process.exit(1);
}
let targetArgumentIndex = process.argv.indexOf("--target");
if (targetArgumentIndex === -1) {
targetArgumentIndex = process.argv.indexOf("-t");
targetArgumentIndex = process.argv.indexOf("-t");
}
let targetFilePath = "";
if (targetArgumentIndex !== -1) {
targetFilePath = process.argv[targetArgumentIndex + 1];
if (!targetFilePath) {
console.error(`No target path was provided after ${process.argv[targetArgumentIndex]}`);
process.exit(1);
}
targetFilePath = process.argv[targetArgumentIndex + 1];
if (!targetFilePath) {
console.error(
`No target path was provided after ${process.argv[targetArgumentIndex]}`
);
process.exit(1);
}
}
let nameArgumentIndex = process.argv.indexOf("--name");
if (nameArgumentIndex === -1) {
nameArgumentIndex = process.argv.indexOf("-n");
nameArgumentIndex = process.argv.indexOf("-n");
}
let name = "schema";
if (nameArgumentIndex !== -1) {
name = process.argv[nameArgumentIndex + 1];
if (!name) {
console.error(`No schema name was provided after ${process.argv[nameArgumentIndex]}`);
process.exit(1);
}
name = process.argv[nameArgumentIndex + 1];
if (!name) {
console.error(
`No schema name was provided after ${process.argv[nameArgumentIndex]}`
);
process.exit(1);
}
}
let deref = process.argv.indexOf("--deref") !== -1 || process.argv.indexOf("-d") !== -1;
let withoutDefaults = process.argv.indexOf("--without-defaults") !== -1 && process.argv.indexOf("-wd") !== -1;
let deref =
process.argv.indexOf("--deref") !== -1 || process.argv.indexOf("-d") !== -1;
let withoutDefaults =
process.argv.indexOf("--without-defaults") !== -1 &&
process.argv.indexOf("-wd") !== -1;
if (targetFilePath) {
const targetFileDir = (0, path_1.dirname)(targetFilePath);
try {
(0, fs_1.mkdir)(targetFileDir, { recursive: true }, err => {
if (err)
throw err;
});
}
catch (e) {
console.error('Failed to create directory for target file');
const targetFileDir = (0, path_1.dirname)(targetFilePath);
try {
(0, fs_1.mkdir)(targetFileDir, { recursive: true }, (err) => {
if (err) throw err;
});
} catch (e) {
console.error("Failed to create directory for target file");
console.error(e);
process.exit(1);
}
if (deref) {
(0, jsonSchemaToZod_1.jsonSchemaToZodDereffed)(
sourceFileData,
name,
true,
withoutDefaults
)
.catch((e) => {
console.error("Failed to parse sourcefile content to Zod schema");
console.error(e);
process.exit(1);
}
if (deref) {
(0, jsonSchemaToZod_1.jsonSchemaToZodDereffed)(sourceFileData, name, true, withoutDefaults)
.catch((e) => {
console.error("Failed to parse sourcefile content to Zod schema");
console.error(e);
process.exit(1);
})
.then((result) => {
try {
(0, fs_1.writeFileSync)(targetFilePath, result);
}
catch (e) {
console.error(`Failed to write result to ${targetFilePath}`);
console.error(e);
process.exit(1);
}
});
}
else {
let result;
})
.then((result) => {
try {
result = (0, jsonSchemaToZod_1.jsonSchemaToZod)(sourceFileData, name, true, withoutDefaults);
(0, fs_1.writeFileSync)(targetFilePath, result);
} catch (e) {
console.error(`Failed to write result to ${targetFilePath}`);
console.error(e);
process.exit(1);
}
catch (e) {
console.error("Failed to parse sourcefile content to Zod schema");
console.error(e);
process.exit(1);
}
try {
(0, fs_1.writeFileSync)(targetFilePath, result);
}
catch (e) {
console.error(`Failed to write result to ${targetFilePath}`);
console.error(e);
process.exit(1);
}
});
} else {
let result;
try {
result = (0, jsonSchemaToZod_1.jsonSchemaToZod)(
sourceFileData,
name,
true,
withoutDefaults
);
} catch (e) {
console.error("Failed to parse sourcefile content to Zod schema");
console.error(e);
process.exit(1);
}
}
else {
if (deref) {
(0, jsonSchemaToZod_1.jsonSchemaToZodDereffed)(sourceFileData, name, false, withoutDefaults)
.catch((e) => {
console.error("Failed to parse sourcefile content to Zod schema");
console.error(e);
process.exit(1);
})
.then((result) => {
console.log(result);
});
try {
(0, fs_1.writeFileSync)(targetFilePath, result);
} catch (e) {
console.error(`Failed to write result to ${targetFilePath}`);
console.error(e);
process.exit(1);
}
else {
let result;
try {
result = (0, jsonSchemaToZod_1.jsonSchemaToZod)(sourceFileData, name, false, withoutDefaults);
}
catch (e) {
console.error("Failed to parse sourcefile content to Zod schema");
console.error(e);
process.exit(1);
}
}
} else {
if (deref) {
(0, jsonSchemaToZod_1.jsonSchemaToZodDereffed)(
sourceFileData,
name,
false,
withoutDefaults
)
.catch((e) => {
console.error("Failed to parse sourcefile content to Zod schema");
console.error(e);
process.exit(1);
})
.then((result) => {
console.log(result);
});
} else {
let result;
try {
result = (0, jsonSchemaToZod_1.jsonSchemaToZod)(
sourceFileData,
name,
false,
withoutDefaults
);
} catch (e) {
console.error("Failed to parse sourcefile content to Zod schema");
console.error(e);
process.exit(1);
}
console.log(result);
}
}

@@ -0,0 +0,0 @@ import { jsonSchemaToZod, jsonSchemaToZodDereffed } from "./jsonSchemaToZod";

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseSchema = exports.jsonSchemaToZodDereffed = exports.jsonSchemaToZod = void 0;
exports.parseSchema =
exports.jsonSchemaToZodDereffed =
exports.jsonSchemaToZod =
void 0;
const jsonSchemaToZod_1 = require("./jsonSchemaToZod");
Object.defineProperty(exports, "jsonSchemaToZod", { enumerable: true, get: function () { return jsonSchemaToZod_1.jsonSchemaToZod; } });
Object.defineProperty(exports, "jsonSchemaToZodDereffed", { enumerable: true, get: function () { return jsonSchemaToZod_1.jsonSchemaToZodDereffed; } });
Object.defineProperty(exports, "jsonSchemaToZod", {
enumerable: true,
get: function () {
return jsonSchemaToZod_1.jsonSchemaToZod;
},
});
Object.defineProperty(exports, "jsonSchemaToZodDereffed", {
enumerable: true,
get: function () {
return jsonSchemaToZod_1.jsonSchemaToZodDereffed;
},
});
const parseSchema_1 = require("./parsers/parseSchema");
Object.defineProperty(exports, "parseSchema", { enumerable: true, get: function () { return parseSchema_1.parseSchema; } });
Object.defineProperty(exports, "parseSchema", {
enumerable: true,
get: function () {
return parseSchema_1.parseSchema;
},
});
exports.default = jsonSchemaToZod_1.jsonSchemaToZod;
import { JSONSchema7 } from "json-schema";
export declare const jsonSchemaToZodDereffed: (schema: JSONSchema7, name?: string | undefined, module?: boolean, withoutDefaults?: boolean) => Promise<string>;
export declare const jsonSchemaToZod: (schema: JSONSchema7, name?: string | undefined, module?: boolean, withoutDefaults?: boolean) => string;
export declare const jsonSchemaToZodDereffed: (
schema: JSONSchema7,
name?: string | undefined,
module?: boolean,
withoutDefaults?: boolean
) => Promise<string>;
export declare const jsonSchemaToZod: (
schema: JSONSchema7,
name?: string | undefined,
module?: boolean,
withoutDefaults?: boolean
) => string;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var __importDefault =
(this && this.__importDefault) ||
function (mod) {
return mod && mod.__esModule ? mod : { default: mod };
};
Object.defineProperty(exports, "__esModule", { value: true });

@@ -9,8 +11,28 @@ exports.jsonSchemaToZod = exports.jsonSchemaToZodDereffed = void 0;

const format_1 = require("./utils/format");
const json_schema_ref_parser_1 = __importDefault(require("@apidevtools/json-schema-ref-parser"));
const jsonSchemaToZodDereffed = (schema, name, module = true, withoutDefaults = false) => json_schema_ref_parser_1.default
const json_schema_ref_parser_1 = __importDefault(
require("@apidevtools/json-schema-ref-parser")
);
const jsonSchemaToZodDereffed = (
schema,
name,
module = true,
withoutDefaults = false
) =>
json_schema_ref_parser_1.default
.dereference(schema)
.then((schema) => (0, exports.jsonSchemaToZod)(schema, name, module, withoutDefaults));
.then((schema) =>
(0, exports.jsonSchemaToZod)(schema, name, module, withoutDefaults)
);
exports.jsonSchemaToZodDereffed = jsonSchemaToZodDereffed;
const jsonSchemaToZod = (schema, name, module = true, withoutDefaults = false) => (0, format_1.format)(`${module ? `import {z} from 'zod'\n\nexport ` : ""}${name ? `const ${name}=` : module ? "default " : "const schema="}${(0, parseSchema_1.parseSchema)(schema, withoutDefaults)}`);
const jsonSchemaToZod = (
schema,
name,
module = true,
withoutDefaults = false
) =>
(0, format_1.format)(
`${module ? `import {z} from 'zod'\n\nexport ` : ""}${
name ? `const ${name}=` : module ? "default " : "const schema="
}${(0, parseSchema_1.parseSchema)(schema, withoutDefaults)}`
);
exports.jsonSchemaToZod = jsonSchemaToZod;
{
"name": "json-schema-to-zod",
"version": "0.6.2",
"version": "0.6.3",
"description": "Converts JSON schema objects or files into Zod schemas",
"main": "index.js",
"scripts": {
"build": "npm i && jest && rimraf ./dist && tsc && copyfiles package.json LICENSE readme.md ./dist",
"build": "npm i && jest && rimraf ./dist && tsc && copyfiles package.json LICENSE readme.md ./dist && prettier ./dist --write",
"dryrun": "npm run build && npm pub ./dist/ --dry-run",

@@ -9,0 +9,0 @@ "dev": "jest --watch",

import { JSONSchema7, JSONSchema7Definition } from "json-schema";
export declare function parseAllOf(schema: JSONSchema7 & {
export declare function parseAllOf(
schema: JSONSchema7 & {
allOf: JSONSchema7Definition[];
}, withoutDefaults?: boolean): string;
},
withoutDefaults?: boolean
): string;

@@ -7,15 +7,19 @@ "use strict";

function parseAllOf(schema, withoutDefaults) {
if (schema.allOf.length === 0) {
return "z.any()";
}
else if (schema.allOf.length === 1) {
return (0, parseSchema_1.parseSchema)(schema.allOf[0], withoutDefaults);
}
else {
const [left, right] = (0, half_1.half)(schema.allOf);
return `z.intersection(${parseAllOf({ allOf: left }, withoutDefaults)},${parseAllOf({
allOf: right,
}, withoutDefaults)})`;
}
if (schema.allOf.length === 0) {
return "z.any()";
} else if (schema.allOf.length === 1) {
return (0, parseSchema_1.parseSchema)(schema.allOf[0], withoutDefaults);
} else {
const [left, right] = (0, half_1.half)(schema.allOf);
return `z.intersection(${parseAllOf(
{ allOf: left },
withoutDefaults
)},${parseAllOf(
{
allOf: right,
},
withoutDefaults
)})`;
}
}
exports.parseAllOf = parseAllOf;
import { JSONSchema7, JSONSchema7Definition } from "json-schema";
export declare const parseAnyOf: (schema: JSONSchema7 & {
export declare const parseAnyOf: (
schema: JSONSchema7 & {
anyOf: JSONSchema7Definition[];
}, withoutDefaults?: boolean | undefined) => string;
},
withoutDefaults?: boolean | undefined
) => string;

@@ -6,8 +6,10 @@ "use strict";

const parseAnyOf = (schema, withoutDefaults) => {
return schema.anyOf.length
? schema.anyOf.length === 1
? (0, parseSchema_1.parseSchema)(schema.anyOf[0], withoutDefaults)
: `z.union([${schema.anyOf.map(schema => (0, parseSchema_1.parseSchema)(schema, withoutDefaults))}])`
: `z.any()`;
return schema.anyOf.length
? schema.anyOf.length === 1
? (0, parseSchema_1.parseSchema)(schema.anyOf[0], withoutDefaults)
: `z.union([${schema.anyOf.map((schema) =>
(0, parseSchema_1.parseSchema)(schema, withoutDefaults)
)}])`
: `z.any()`;
};
exports.parseAnyOf = parseAnyOf;
import { JSONSchema7 } from "json-schema";
export declare const parseArray: (schema: JSONSchema7 & {
export declare const parseArray: (
schema: JSONSchema7 & {
type: "array";
}, withoutDefaults?: boolean | undefined) => string;
},
withoutDefaults?: boolean | undefined
) => string;

@@ -6,13 +6,16 @@ "use strict";

const parseArray = (schema, withoutDefaults) => {
let r = !schema.items
? "z.array(z.any())"
: Array.isArray(schema.items)
? `z.tuple([${schema.items.map((v) => (0, parseSchema_1.parseSchema)(v, withoutDefaults))}])`
: `z.array(${(0, parseSchema_1.parseSchema)(schema.items, withoutDefaults)})`;
if (typeof schema.minItems === "number")
r += `.min(${schema.minItems})`;
if (typeof schema.maxItems === "number")
r += `.max(${schema.maxItems})`;
return r;
let r = !schema.items
? "z.array(z.any())"
: Array.isArray(schema.items)
? `z.tuple([${schema.items.map((v) =>
(0, parseSchema_1.parseSchema)(v, withoutDefaults)
)}])`
: `z.array(${(0, parseSchema_1.parseSchema)(
schema.items,
withoutDefaults
)})`;
if (typeof schema.minItems === "number") r += `.min(${schema.minItems})`;
if (typeof schema.maxItems === "number") r += `.max(${schema.maxItems})`;
return r;
};
exports.parseArray = parseArray;
import { JSONSchema7 } from "json-schema";
export declare const parseBoolean: (schema: JSONSchema7 & {
export declare const parseBoolean: (
schema: JSONSchema7 & {
type: "boolean";
}) => string;
}
) => string;

@@ -5,4 +5,4 @@ "use strict";

const parseBoolean = (schema) => {
return "z.boolean()";
return "z.boolean()";
};
exports.parseBoolean = parseBoolean;
import { JSONSchema7, JSONSchema7Type } from "json-schema";
export declare const parseConst: (schema: JSONSchema7 & {
export declare const parseConst: (
schema: JSONSchema7 & {
const: JSONSchema7Type;
}) => string;
}
) => string;

@@ -5,4 +5,4 @@ "use strict";

const parseConst = (schema) => {
return `z.literal(${JSON.stringify(schema.const)})`;
return `z.literal(${JSON.stringify(schema.const)})`;
};
exports.parseConst = parseConst;
import { JSONSchema7 } from "json-schema";
export declare const parseDefault: (schema: JSONSchema7) => string;

@@ -5,4 +5,4 @@ "use strict";

const parseDefault = (schema) => {
return "z.any()";
return "z.any()";
};
exports.parseDefault = parseDefault;
import { JSONSchema7, JSONSchema7Type } from "json-schema";
export declare const parseEnum: (schema: JSONSchema7 & {
export declare const parseEnum: (
schema: JSONSchema7 & {
enum: JSONSchema7Type[] | JSONSchema7Type;
}) => string;
}
) => string;

@@ -5,18 +5,17 @@ "use strict";

const parseEnum = (schema) => {
if (Array.isArray(schema.enum)) {
if (schema.enum.every((x) => typeof x === "string")) {
return `z.enum([${schema.enum.map((x) => JSON.stringify(x))}])`;
}
else if (schema.enum.length === 1) {
// union does not work when there is only one element
return `z.literal(${JSON.stringify(schema.enum[0])})`;
}
else {
return `z.union([${schema.enum.map((x) => `z.literal(${JSON.stringify(x)})`)}])`;
}
if (Array.isArray(schema.enum)) {
if (schema.enum.every((x) => typeof x === "string")) {
return `z.enum([${schema.enum.map((x) => JSON.stringify(x))}])`;
} else if (schema.enum.length === 1) {
// union does not work when there is only one element
return `z.literal(${JSON.stringify(schema.enum[0])})`;
} else {
return `z.union([${schema.enum.map(
(x) => `z.literal(${JSON.stringify(x)})`
)}])`;
}
else {
return `z.literal(${JSON.stringify(schema.enum)})`;
}
} else {
return `z.literal(${JSON.stringify(schema.enum)})`;
}
};
exports.parseEnum = parseEnum;
import { JSONSchema7, JSONSchema7Definition } from "json-schema";
export declare const parseIfThenElse: (schema: JSONSchema7 & {
export declare const parseIfThenElse: (
schema: JSONSchema7 & {
if: JSONSchema7Definition;
then: JSONSchema7Definition;
else: JSONSchema7Definition;
}, withoutDefaults?: boolean | undefined) => string;
},
withoutDefaults?: boolean | undefined
) => string;

@@ -6,6 +6,6 @@ "use strict";

const parseIfThenElse = (schema, withoutDefaults) => {
const $if = (0, parseSchema_1.parseSchema)(schema.if, withoutDefaults);
const $then = (0, parseSchema_1.parseSchema)(schema.then, withoutDefaults);
const $else = (0, parseSchema_1.parseSchema)(schema.else, withoutDefaults);
return `z.union([${$then},${$else}]).superRefine((value,ctx) => {
const $if = (0, parseSchema_1.parseSchema)(schema.if, withoutDefaults);
const $then = (0, parseSchema_1.parseSchema)(schema.then, withoutDefaults);
const $else = (0, parseSchema_1.parseSchema)(schema.else, withoutDefaults);
return `z.union([${$then},${$else}]).superRefine((value,ctx) => {
const result = ${$if}.safeParse(value).success

@@ -12,0 +12,0 @@ ? ${$then}.safeParse(value)

import { JSONSchema7, JSONSchema7TypeName } from "json-schema";
export declare const parseMultipleType: (schema: JSONSchema7 & {
export declare const parseMultipleType: (
schema: JSONSchema7 & {
type: JSONSchema7TypeName[];
}, withoutDefaults?: boolean | undefined) => string;
},
withoutDefaults?: boolean | undefined
) => string;

@@ -6,4 +6,9 @@ "use strict";

const parseMultipleType = (schema, withoutDefaults) => {
return `z.union([${schema.type.map((type) => (0, parseSchema_1.parseSchema)(Object.assign(Object.assign({}, schema), { type }), withoutDefaults))}])`;
return `z.union([${schema.type.map((type) =>
(0, parseSchema_1.parseSchema)(
Object.assign(Object.assign({}, schema), { type }),
withoutDefaults
)
)}])`;
};
exports.parseMultipleType = parseMultipleType;
import { JSONSchema7, JSONSchema7Definition } from "json-schema";
export declare const parseNot: (schema: JSONSchema7 & {
export declare const parseNot: (
schema: JSONSchema7 & {
not: JSONSchema7Definition;
}, withoutDefaults?: boolean | undefined) => string;
},
withoutDefaults?: boolean | undefined
) => string;

@@ -6,4 +6,7 @@ "use strict";

const parseNot = (schema, withoutDefaults) => {
return `z.any().refine((value) => !${(0, parseSchema_1.parseSchema)(schema.not, withoutDefaults)}.safeParse(value).success, "Invalid input: Should NOT be valid against schema")`;
return `z.any().refine((value) => !${(0, parseSchema_1.parseSchema)(
schema.not,
withoutDefaults
)}.safeParse(value).success, "Invalid input: Should NOT be valid against schema")`;
};
exports.parseNot = parseNot;
import { JSONSchema7 } from "json-schema";
export declare const parseNull: (schema: JSONSchema7 & {
export declare const parseNull: (
schema: JSONSchema7 & {
type: "null";
}) => string;
}
) => string;

@@ -5,4 +5,4 @@ "use strict";

const parseNull = (schema) => {
return "z.null()";
return "z.null()";
};
exports.parseNull = parseNull;

@@ -5,4 +5,7 @@ import { JSONSchema7 } from "json-schema";

*/
export declare const parseNullable: (schema: JSONSchema7 & {
export declare const parseNullable: (
schema: JSONSchema7 & {
nullable: true;
}, includeDefaults?: boolean | undefined) => string;
},
includeDefaults?: boolean | undefined
) => string;

@@ -10,4 +10,7 @@ "use strict";

const parseNullable = (schema, includeDefaults) => {
return `${(0, parseSchema_1.parseSchema)((0, omit_1.omit)(schema, "nullable"), includeDefaults)}.nullable()`;
return `${(0, parseSchema_1.parseSchema)(
(0, omit_1.omit)(schema, "nullable"),
includeDefaults
)}.nullable()`;
};
exports.parseNullable = parseNullable;
import { JSONSchema7 } from "json-schema";
export declare const parseNumber: (schema: JSONSchema7 & {
export declare const parseNumber: (
schema: JSONSchema7 & {
type: "number" | "integer";
}) => string;
}
) => string;

@@ -5,35 +5,33 @@ "use strict";

const parseNumber = (schema) => {
let r = "z.number()";
if (schema.format === "int64" ||
schema.multipleOf === 1 ||
schema.type === "integer") {
r += ".int()";
let r = "z.number()";
if (
schema.format === "int64" ||
schema.multipleOf === 1 ||
schema.type === "integer"
) {
r += ".int()";
}
if (typeof schema.multipleOf === "number" && schema.multipleOf !== 1) {
r += `.multipleOf(${schema.multipleOf})`;
}
if (typeof schema.minimum === "number") {
if (schema.exclusiveMinimum === true) {
r += `.gt({${schema.minimum}})`;
} else {
r += `.gte(${schema.minimum})`;
}
if (typeof schema.multipleOf === "number" && schema.multipleOf !== 1) {
r += `.multipleOf(${schema.multipleOf})`;
} else if (typeof schema.exclusiveMinimum === "number") {
r += `.gt(${schema.exclusiveMinimum})`;
}
if (typeof schema.maximum === "number") {
if (schema.exclusiveMaximum === true) {
r += `.lt({${schema.maximum}})`;
} else {
r += `.lte(${schema.maximum})`;
}
if (typeof schema.minimum === "number") {
if (schema.exclusiveMinimum === true) {
r += `.gt({${schema.minimum}})`;
}
else {
r += `.gte(${schema.minimum})`;
}
}
else if (typeof schema.exclusiveMinimum === "number") {
r += `.gt(${schema.exclusiveMinimum})`;
}
if (typeof schema.maximum === "number") {
if (schema.exclusiveMaximum === true) {
r += `.lt({${schema.maximum}})`;
}
else {
r += `.lte(${schema.maximum})`;
}
}
else if (typeof schema.exclusiveMaximum === "number") {
r += `.lt(${schema.exclusiveMaximum})`;
}
return r;
} else if (typeof schema.exclusiveMaximum === "number") {
r += `.lt(${schema.exclusiveMaximum})`;
}
return r;
};
exports.parseNumber = parseNumber;
import { JSONSchema7 } from "json-schema";
export declare const parseObject: (schema: JSONSchema7 & {
export declare const parseObject: (
schema: JSONSchema7 & {
type: "object";
}, withoutDefaults?: boolean | undefined) => string;
},
withoutDefaults?: boolean | undefined
) => string;

@@ -10,36 +10,73 @@ "use strict";

const parseObject = (schema, withoutDefaults) => {
var _a;
let result = !schema.properties
? typeof schema.additionalProperties === "object"
? `z.record(${(0, parseSchema_1.parseSchema)(schema.additionalProperties, withoutDefaults)})`
: schema.additionalProperties === false
? "z.object({}).strict()"
: "z.record(z.any())"
: `z.object({${Object.entries((_a = schema === null || schema === void 0 ? void 0 : schema.properties) !== null && _a !== void 0 ? _a : {}).map(([k, v]) => {
var _a;
return `${JSON.stringify(k)}:${(0, parseSchema_1.parseSchema)(v, withoutDefaults)}${((_a = schema.required) === null || _a === void 0 ? void 0 : _a.includes(k)) ||
(!withoutDefaults && v.hasOwnProperty("default"))
? requiredFlag
: ".optional()"}`;
})}})${schema.additionalProperties === true
? ".catchall(z.any())"
: schema.additionalProperties === false
? ".strict()"
: typeof schema.additionalProperties === "object"
? `.catchall(${(0, parseSchema_1.parseSchema)(schema.additionalProperties, withoutDefaults)})`
: defaultAdditionalFlag}`;
if (parseSchema_1.its.an.anyOf(schema)) {
result += `.and(${(0, parseAnyOf_1.parseAnyOf)(Object.assign(Object.assign({}, schema), { anyOf: schema.anyOf.map((x) => typeof x === "object" &&
!x.type &&
(x.properties || x.additionalProperties)
? Object.assign(Object.assign({}, x), { type: "object" }) : x) }), withoutDefaults)})`;
}
if (parseSchema_1.its.a.oneOf(schema)) {
result += `.and(${(0, parseOneOf_1.parseOneOf)(Object.assign(Object.assign({}, schema), { oneOf: schema.oneOf.map((x) => typeof x === "object" &&
!x.type &&
(x.properties || x.additionalProperties)
? Object.assign(Object.assign({}, x), { type: "object" }) : x) }), withoutDefaults)})`;
}
return result;
var _a;
let result = !schema.properties
? typeof schema.additionalProperties === "object"
? `z.record(${(0, parseSchema_1.parseSchema)(
schema.additionalProperties,
withoutDefaults
)})`
: schema.additionalProperties === false
? "z.object({}).strict()"
: "z.record(z.any())"
: `z.object({${Object.entries(
(_a =
schema === null || schema === void 0 ? void 0 : schema.properties) !==
null && _a !== void 0
? _a
: {}
).map(([k, v]) => {
var _a;
return `${JSON.stringify(k)}:${(0, parseSchema_1.parseSchema)(
v,
withoutDefaults
)}${
((_a = schema.required) === null || _a === void 0
? void 0
: _a.includes(k)) ||
(!withoutDefaults && v.hasOwnProperty("default"))
? requiredFlag
: ".optional()"
}`;
})}})${
schema.additionalProperties === true
? ".catchall(z.any())"
: schema.additionalProperties === false
? ".strict()"
: typeof schema.additionalProperties === "object"
? `.catchall(${(0, parseSchema_1.parseSchema)(
schema.additionalProperties,
withoutDefaults
)})`
: defaultAdditionalFlag
}`;
if (parseSchema_1.its.an.anyOf(schema)) {
result += `.and(${(0, parseAnyOf_1.parseAnyOf)(
Object.assign(Object.assign({}, schema), {
anyOf: schema.anyOf.map((x) =>
typeof x === "object" &&
!x.type &&
(x.properties || x.additionalProperties)
? Object.assign(Object.assign({}, x), { type: "object" })
: x
),
}),
withoutDefaults
)})`;
}
if (parseSchema_1.its.a.oneOf(schema)) {
result += `.and(${(0, parseOneOf_1.parseOneOf)(
Object.assign(Object.assign({}, schema), {
oneOf: schema.oneOf.map((x) =>
typeof x === "object" &&
!x.type &&
(x.properties || x.additionalProperties)
? Object.assign(Object.assign({}, x), { type: "object" })
: x
),
}),
withoutDefaults
)})`;
}
return result;
};
exports.parseObject = parseObject;
import { JSONSchema7, JSONSchema7Definition } from "json-schema";
export declare const parseOneOf: (schema: JSONSchema7 & {
export declare const parseOneOf: (
schema: JSONSchema7 & {
oneOf: JSONSchema7Definition[];
}, withoutDefaults?: boolean | undefined) => string;
},
withoutDefaults?: boolean | undefined
) => string;

@@ -6,7 +6,9 @@ "use strict";

const parseOneOf = (schema, withoutDefaults) => {
return schema.oneOf.length
? schema.oneOf.length === 1
? (0, parseSchema_1.parseSchema)(schema.oneOf[0], withoutDefaults)
: `z.any().superRefine((x, ctx) => {
const schemas = [${schema.oneOf.map((schema) => (0, parseSchema_1.parseSchema)(schema, withoutDefaults))}];
return schema.oneOf.length
? schema.oneOf.length === 1
? (0, parseSchema_1.parseSchema)(schema.oneOf[0], withoutDefaults)
: `z.any().superRefine((x, ctx) => {
const schemas = [${schema.oneOf.map((schema) =>
(0, parseSchema_1.parseSchema)(schema, withoutDefaults)
)}];
const errors = schemas.reduce(

@@ -28,4 +30,4 @@ (errors: z.ZodError[], schema) =>

})`
: "z.any()";
: "z.any()";
};
exports.parseOneOf = parseOneOf;

@@ -1,46 +0,57 @@

import { JSONSchema7, JSONSchema7Definition, JSONSchema7Type, JSONSchema7TypeName } from "json-schema";
export declare const parseSchema: (schema: JSONSchema7 | boolean, withoutDefaults?: boolean | undefined) => string;
import {
JSONSchema7,
JSONSchema7Definition,
JSONSchema7Type,
JSONSchema7TypeName,
} from "json-schema";
export declare const parseSchema: (
schema: JSONSchema7 | boolean,
withoutDefaults?: boolean | undefined
) => string;
export declare const its: {
an: {
object: (x: JSONSchema7) => x is JSONSchema7 & {
type: "object";
};
array: (x: JSONSchema7) => x is JSONSchema7 & {
type: "array";
};
anyOf: (x: JSONSchema7) => x is JSONSchema7 & {
anyOf: JSONSchema7Definition[];
};
allOf: (x: JSONSchema7) => x is JSONSchema7 & {
allOf: JSONSchema7Definition[];
};
enum: (x: JSONSchema7) => x is JSONSchema7 & {
enum: JSONSchema7Type | JSONSchema7Type[];
};
an: {
object: (x: JSONSchema7) => x is JSONSchema7 & {
type: "object";
};
a: {
nullable: (x: JSONSchema7) => x is JSONSchema7 & {
nullable: true;
};
multipleType: (x: JSONSchema7) => x is JSONSchema7 & {
type: JSONSchema7TypeName[];
};
not: (x: JSONSchema7) => x is JSONSchema7 & {
not: JSONSchema7Definition;
};
const: (x: JSONSchema7) => x is JSONSchema7 & {
const: JSONSchema7Type;
};
primitive: <T extends "string" | "number" | "boolean" | "integer" | "null">(x: JSONSchema7, p: T) => x is JSONSchema7 & {
type: T;
};
conditional: (x: JSONSchema7) => x is JSONSchema7 & {
if: JSONSchema7Definition;
then: JSONSchema7Definition;
else: JSONSchema7Definition;
};
oneOf: (x: JSONSchema7) => x is JSONSchema7 & {
oneOf: JSONSchema7Definition[];
};
array: (x: JSONSchema7) => x is JSONSchema7 & {
type: "array";
};
anyOf: (x: JSONSchema7) => x is JSONSchema7 & {
anyOf: JSONSchema7Definition[];
};
allOf: (x: JSONSchema7) => x is JSONSchema7 & {
allOf: JSONSchema7Definition[];
};
enum: (x: JSONSchema7) => x is JSONSchema7 & {
enum: JSONSchema7Type | JSONSchema7Type[];
};
};
a: {
nullable: (x: JSONSchema7) => x is JSONSchema7 & {
nullable: true;
};
multipleType: (x: JSONSchema7) => x is JSONSchema7 & {
type: JSONSchema7TypeName[];
};
not: (x: JSONSchema7) => x is JSONSchema7 & {
not: JSONSchema7Definition;
};
const: (x: JSONSchema7) => x is JSONSchema7 & {
const: JSONSchema7Type;
};
primitive: <T extends "string" | "number" | "boolean" | "integer" | "null">(
x: JSONSchema7,
p: T
) => x is JSONSchema7 & {
type: T;
};
conditional: (x: JSONSchema7) => x is JSONSchema7 & {
if: JSONSchema7Definition;
then: JSONSchema7Definition;
else: JSONSchema7Definition;
};
oneOf: (x: JSONSchema7) => x is JSONSchema7 & {
oneOf: JSONSchema7Definition[];
};
};
};

@@ -21,91 +21,77 @@ "use strict";

const parseSchema = (schema, withoutDefaults) => {
if (typeof schema !== "object")
return "z.unknown()";
let parsed = selectParser(schema, withoutDefaults);
parsed = addMeta(schema, parsed);
if (!withoutDefaults) {
parsed = addDefaults(schema, parsed);
}
return parsed;
if (typeof schema !== "object") return "z.unknown()";
let parsed = selectParser(schema, withoutDefaults);
parsed = addMeta(schema, parsed);
if (!withoutDefaults) {
parsed = addDefaults(schema, parsed);
}
return parsed;
};
exports.parseSchema = parseSchema;
const addMeta = (schema, parsed) => {
if (schema.description)
parsed += `.describe(${JSON.stringify(schema.description)})`;
return parsed;
if (schema.description)
parsed += `.describe(${JSON.stringify(schema.description)})`;
return parsed;
};
const addDefaults = (schema, parsed) => {
if (schema.default !== undefined) {
parsed += `.default(${JSON.stringify(schema.default)})`;
}
return parsed;
if (schema.default !== undefined) {
parsed += `.default(${JSON.stringify(schema.default)})`;
}
return parsed;
};
const selectParser = (schema, withoutDefaults) => {
if (exports.its.a.nullable(schema)) {
return (0, parseNullable_1.parseNullable)(schema, withoutDefaults);
}
else if (exports.its.an.object(schema)) {
return (0, parseObject_1.parseObject)(schema, withoutDefaults);
}
else if (exports.its.an.array(schema)) {
return (0, parseArray_1.parseArray)(schema, withoutDefaults);
}
else if (exports.its.an.anyOf(schema)) {
return (0, parseAnyOf_1.parseAnyOf)(schema, withoutDefaults);
}
else if (exports.its.an.allOf(schema)) {
return (0, parseAllOf_1.parseAllOf)(schema, withoutDefaults);
}
else if (exports.its.a.oneOf(schema)) {
return (0, parseOneOf_1.parseOneOf)(schema, withoutDefaults);
}
else if (exports.its.a.not(schema)) {
return (0, parseNot_1.parseNot)(schema, withoutDefaults);
}
else if (exports.its.an.enum(schema)) {
return (0, parseEnum_1.parseEnum)(schema); //<-- needs to come before primitives
}
else if (exports.its.a.const(schema)) {
return (0, parseConst_1.parseConst)(schema);
}
else if (exports.its.a.multipleType(schema)) {
return (0, parseMultipleType_1.parseMultipleType)(schema, withoutDefaults);
}
else if (exports.its.a.primitive(schema, "string")) {
return (0, parseString_1.parseString)(schema);
}
else if (exports.its.a.primitive(schema, "number") ||
exports.its.a.primitive(schema, "integer")) {
return (0, parseNumber_1.parseNumber)(schema);
}
else if (exports.its.a.primitive(schema, "boolean")) {
return (0, parseBoolean_1.parseBoolean)(schema);
}
else if (exports.its.a.primitive(schema, "null")) {
return (0, parseNull_1.parseNull)(schema);
}
else if (exports.its.a.conditional(schema)) {
return (0, parseIfThenElse_1.parseIfThenElse)(schema, withoutDefaults);
}
else {
return (0, parseDefault_1.parseDefault)(schema);
}
if (exports.its.a.nullable(schema)) {
return (0, parseNullable_1.parseNullable)(schema, withoutDefaults);
} else if (exports.its.an.object(schema)) {
return (0, parseObject_1.parseObject)(schema, withoutDefaults);
} else if (exports.its.an.array(schema)) {
return (0, parseArray_1.parseArray)(schema, withoutDefaults);
} else if (exports.its.an.anyOf(schema)) {
return (0, parseAnyOf_1.parseAnyOf)(schema, withoutDefaults);
} else if (exports.its.an.allOf(schema)) {
return (0, parseAllOf_1.parseAllOf)(schema, withoutDefaults);
} else if (exports.its.a.oneOf(schema)) {
return (0, parseOneOf_1.parseOneOf)(schema, withoutDefaults);
} else if (exports.its.a.not(schema)) {
return (0, parseNot_1.parseNot)(schema, withoutDefaults);
} else if (exports.its.an.enum(schema)) {
return (0, parseEnum_1.parseEnum)(schema); //<-- needs to come before primitives
} else if (exports.its.a.const(schema)) {
return (0, parseConst_1.parseConst)(schema);
} else if (exports.its.a.multipleType(schema)) {
return (0, parseMultipleType_1.parseMultipleType)(schema, withoutDefaults);
} else if (exports.its.a.primitive(schema, "string")) {
return (0, parseString_1.parseString)(schema);
} else if (
exports.its.a.primitive(schema, "number") ||
exports.its.a.primitive(schema, "integer")
) {
return (0, parseNumber_1.parseNumber)(schema);
} else if (exports.its.a.primitive(schema, "boolean")) {
return (0, parseBoolean_1.parseBoolean)(schema);
} else if (exports.its.a.primitive(schema, "null")) {
return (0, parseNull_1.parseNull)(schema);
} else if (exports.its.a.conditional(schema)) {
return (0, parseIfThenElse_1.parseIfThenElse)(schema, withoutDefaults);
} else {
return (0, parseDefault_1.parseDefault)(schema);
}
};
exports.its = {
an: {
object: (x) => x.type === "object",
array: (x) => x.type === "array",
anyOf: (x) => x.anyOf !== undefined,
allOf: (x) => x.allOf !== undefined,
enum: (x) => x.enum !== undefined,
},
a: {
nullable: (x) => x.nullable === true,
multipleType: (x) => Array.isArray(x.type),
not: (x) => x.not !== undefined,
const: (x) => x.const !== undefined,
primitive: (x, p) => x.type === p,
conditional: (x) => Boolean(x.if && x.then && x.else),
oneOf: (x) => x.oneOf !== undefined,
},
an: {
object: (x) => x.type === "object",
array: (x) => x.type === "array",
anyOf: (x) => x.anyOf !== undefined,
allOf: (x) => x.allOf !== undefined,
enum: (x) => x.enum !== undefined,
},
a: {
nullable: (x) => x.nullable === true,
multipleType: (x) => Array.isArray(x.type),
not: (x) => x.not !== undefined,
const: (x) => x.const !== undefined,
primitive: (x, p) => x.type === p,
conditional: (x) => Boolean(x.if && x.then && x.else),
oneOf: (x) => x.oneOf !== undefined,
},
};
import { JSONSchema7 } from "json-schema";
export declare const parseString: (schema: JSONSchema7 & {
export declare const parseString: (
schema: JSONSchema7 & {
type: "string";
}) => string;
}
) => string;

@@ -5,17 +5,12 @@ "use strict";

const parseString = (schema) => {
let r = "z.string()";
if (schema.pattern)
r += `.regex(new RegExp(${JSON.stringify(schema.pattern)}))`;
if (schema.format === "email")
r += ".email()";
else if (schema.format === "uri")
r += ".url()";
else if (schema.format === "uuid")
r += ".uuid()";
if (typeof schema.minLength === "number")
r += `.min(${schema.minLength})`;
if (typeof schema.maxLength === "number")
r += `.max(${schema.maxLength})`;
return r;
let r = "z.string()";
if (schema.pattern)
r += `.regex(new RegExp(${JSON.stringify(schema.pattern)}))`;
if (schema.format === "email") r += ".email()";
else if (schema.format === "uri") r += ".url()";
else if (schema.format === "uuid") r += ".uuid()";
if (typeof schema.minLength === "number") r += `.min(${schema.minLength})`;
if (typeof schema.maxLength === "number") r += `.max(${schema.maxLength})`;
return r;
};
exports.parseString = parseString;

@@ -22,3 +22,3 @@ # Json-Schema-to-Zod

> `npm i -G json-schema-to-zod`
> `npm i -g json-schema-to-zod`

@@ -25,0 +25,0 @@ Example:

export declare const format: (source: string) => string;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var __importDefault =
(this && this.__importDefault) ||
function (mod) {
return mod && mod.__esModule ? mod : { default: mod };
};
Object.defineProperty(exports, "__esModule", { value: true });

@@ -9,6 +11,7 @@ exports.format = void 0;

const parser_babel_1 = __importDefault(require("prettier/parser-babel"));
const format = (source) => prettier_1.default.format(source, {
const format = (source) =>
prettier_1.default.format(source, {
parser: "babel",
plugins: [parser_babel_1.default],
});
});
exports.format = format;
export declare const half: <T>(arr: T[]) => [T[], T[]];

@@ -5,4 +5,4 @@ "use strict";

const half = (arr) => {
return arr.length ? [arr.slice(0, Math.floor(arr.length / 2)), arr.slice(Math.floor(arr.length / 2))] : [[], []];
return [arr.slice(0, arr.length / 2), arr.slice(arr.length / 2)];
};
exports.half = half;

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

export declare const omit: <T extends object, K extends keyof T>(obj: T, ...keys: K[]) => Omit<T, K>;
export declare const omit: <T extends object, K extends keyof T>(
obj: T,
...keys: K[]
) => Omit<T, K>;
"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)));
const omit = (obj, ...keys) =>
Object.fromEntries(
Object.entries(obj).filter(([key]) => !keys.includes(key))
);
exports.omit = omit;
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