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

zod-to-json-schema

Package Overview
Dependencies
Maintainers
1
Versions
81
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

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

Comparing version 3.21.0 to 3.21.1

2

changelog.md

@@ -5,2 +5,4 @@ # Changelog

| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 3.21.0 | Added new string validations (ip, emoji, etc) and BigInt checks to support Zod 3.21 |
| 3.20.5 | Added uniqueItems to Set and an option to disregard pipe schemas |
| 3.20.4 | Bugfixes and improved record parsing for openApi3 |

@@ -7,0 +9,0 @@ | 3.20.3 | Added Cuid2 support introduced in Zod 3.20.3 |

8

package.json
{
"name": "zod-to-json-schema",
"version": "3.21.0",
"version": "3.21.1",
"description": "Converts Zod schemas to Json Schemas",

@@ -28,3 +28,5 @@ "main": "index.js",

"Tom Arad (https://github.com/tomarad)",
"Isaac Way (https://github.com/iway1)"
"Isaac Way (https://github.com/iway1)",
"Andreas Berger (https://github.com/Andy2003)",
"Jan Potoms (https://github.com/Janpot)"
],

@@ -52,2 +54,2 @@ "repository": {

"types": "index.d.ts"
}
}

@@ -69,13 +69,13 @@ # Zod to Json Schema

| Option | Effect |
| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **name**?: _string_ | As described above. |
| **basePath**?: string[] | The base path of the root reference builder. Defaults to ["#"]. |
| **$refStrategy**?: "root" \| "relative" \| "none" | The reference builder strategy; <ul><li>**"root"** resolves $refs from the root up, ie: "#/definitions/mySchema".</li><li>**"relative"** uses [relative JSON pointers](https://tools.ietf.org/id/draft-handrews-relative-json-pointer-00.html). _See known issues!_</li><li>**"none"** ignores referencing all together, creating a new schema branch even on "seen" schemas. Recursive references defaults to "any", ie `{}`.</li></ul> Defaults to "root". |
| **effectStrategy**?: "input" \| "any" | The effects output strategy. Defaults to "input". _See known issues!_ |
| **definitionPath**?: "definitions" \| "$defs" | The name of the definitions property when name is passed. Defaults to "definitions". |
| **target**?: "jsonSchema7" \| "openApi3" | Which spec to target. Defaults to "jsonSchema7" |
| **strictUnions**?: boolean | Scrubs unions of any-like json schemas, like `{}` or `true`. Multiple zod types may result in these out of necessity, such as z.instanceof() |
| **definitions**?: Record<string, ZodSchema> | See separate section below |
| **errorMessages**?: boolean | Include custom error messages created via chained function checks for supported zod types. See section below |
| Option | Effect |
|-----------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **name**?: _string_ | As described above. |
| **basePath**?: string[] | The base path of the root reference builder. Defaults to ["#"]. |
| **$refStrategy**?: "root" \| "relative" \| "none" | The reference builder strategy; <ul><li>**"root"** resolves $refs from the root up, ie: "#/definitions/mySchema".</li><li>**"relative"** uses [relative JSON pointers](https://tools.ietf.org/id/draft-handrews-relative-json-pointer-00.html). _See known issues!_</li><li>**"none"** ignores referencing all together, creating a new schema branch even on "seen" schemas. Recursive references defaults to "any", ie `{}`.</li></ul> Defaults to "root". |
| **effectStrategy**?: "input" \| "any" | The effects output strategy. Defaults to "input". _See known issues!_ |
| **definitionPath**?: "definitions" \| "$defs" | The name of the definitions property when name is passed. Defaults to "definitions". |
| **target**?: "jsonSchema7" \| "jsonSchema2019-09" \| "openApi3" | Which spec to target. Defaults to "jsonSchema7" |
| **strictUnions**?: boolean | Scrubs unions of any-like json schemas, like `{}` or `true`. Multiple zod types may result in these out of necessity, such as z.instanceof() |
| **definitions**?: Record<string, ZodSchema> | See separate section below |
| **errorMessages**?: boolean | Include custom error messages created via chained function checks for supported zod types. See section below |

@@ -82,0 +82,0 @@ ### Definitions

import { ZodSchema } from "zod";
export type Options<Target extends "jsonSchema7" | "openApi3" = "jsonSchema7"> = {
export type Targets = "jsonSchema7" | "jsonSchema2019-09" | "openApi3";
export type Options<Target extends Targets = "jsonSchema7"> = {
name: string | undefined;

@@ -15,2 +16,2 @@ $refStrategy: "root" | "relative" | "none";

export declare const defaultOptions: Options;
export declare const getDefaultOptions: <Target extends "jsonSchema7" | "openApi3">(options: string | Partial<Options<Target>> | undefined) => Options<Target>;
export declare const getDefaultOptions: <Target extends Targets>(options: string | Partial<Options<Target>> | undefined) => Options<Target>;

@@ -34,3 +34,3 @@ import { ZodTypeDef } from "zod";

export type JsonSchema7Type = JsonSchema7TypeUnion & JsonSchema7Meta;
export declare function parseDef(def: ZodTypeDef, refs: Refs): JsonSchema7Type | undefined;
export declare function parseDef(def: ZodTypeDef, refs: Refs, forceResolution?: boolean): JsonSchema7Type | undefined;
export {};

@@ -34,9 +34,10 @@ "use strict";

const unknown_1 = require("./parsers/unknown");
function parseDef(def, refs) {
const seenItem = refs.seen.find((x) => Object.is(x.def, def));
if (seenItem) {
function parseDef(def, refs, forceResolution = false // Forces a new schema to be instantiated even though its def has been seen. Used for improving refs in definitions. See https://github.com/StefanTerdell/zod-to-json-schema/pull/61.
) {
const seenItem = refs.seen.get(def);
if (seenItem && !forceResolution) {
return get$ref(seenItem, refs);
}
const newItem = { def, path: refs.currentPath, jsonSchema: undefined };
refs.seen.push(newItem);
refs.seen.set(def, newItem);
const jsonSchema = selectParser(def, def.typeName, refs);

@@ -43,0 +44,0 @@ if (jsonSchema) {

@@ -6,3 +6,4 @@ import { ZodIntersectionDef } from "zod";

allOf: JsonSchema7Type[];
unevaluatedProperties?: boolean;
};
export declare function parseIntersectionDef(def: ZodIntersectionDef, refs: Refs): JsonSchema7AllOfType | JsonSchema7Type | undefined;
"use strict";
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseIntersectionDef = void 0;
const parseDef_1 = require("../parseDef");
const isJsonSchema7AllOfType = (type) => {
if ("type" in type && type.type === "string")
return false;
return 'allOf' in type;
};
function parseIntersectionDef(def, refs) {

@@ -10,4 +26,29 @@ const allOf = [

].filter((x) => !!x);
return allOf.length ? { allOf } : undefined;
let unevaluatedProperties = refs.target === 'jsonSchema2019-09' ? { unevaluatedProperties: false } : undefined;
const mergedAllOf = [];
// If either of the schemas is an allOf, merge them into a single allOf
allOf.forEach((schema) => {
if (isJsonSchema7AllOfType(schema)) {
mergedAllOf.push(...schema.allOf);
if (schema.unevaluatedProperties === undefined) {
// If one of the schemas has no unevaluatedProperties set,
// the merged schema should also have no unevaluatedProperties set
unevaluatedProperties = undefined;
}
}
else {
let nestedSchema = schema;
if ('additionalProperties' in schema && schema.additionalProperties === false) {
const { additionalProperties } = schema, rest = __rest(schema, ["additionalProperties"]);
nestedSchema = rest;
}
else {
// As soon as one of the schemas has additionalProperties set not to false, we allow unevaluatedProperties
unevaluatedProperties = undefined;
}
mergedAllOf.push(nestedSchema);
}
});
return mergedAllOf.length ? Object.assign({ allOf: mergedAllOf }, unevaluatedProperties) : undefined;
}
exports.parseIntersectionDef = parseIntersectionDef;

@@ -28,3 +28,3 @@ "use strict";

}
else if (options.every((x) => x._def.typeName === "ZodLiteral")) {
else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
// all options literals

@@ -31,0 +31,0 @@ const types = options.reduce((acc, x) => {

import { ZodTypeDef } from "zod";
import { Options } from "./Options";
import { Options, Targets } from "./Options";
import { JsonSchema7Type } from "./parseDef";
export type Refs = {
seen: Seen[];
seen: Map<ZodTypeDef, Seen>;
currentPath: string[];
propertyPath: string[] | undefined;
} & Options<"jsonSchema7" | "openApi3">;
} & Options<Targets>;
export type Seen = {

@@ -14,2 +14,2 @@ def: ZodTypeDef;

};
export declare const getRefs: (options?: string | Partial<Options<"jsonSchema7" | "openApi3">>) => Refs;
export declare const getRefs: (options?: string | Partial<Options<Targets>>) => Refs;

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

: _options.basePath;
return Object.assign(Object.assign({}, _options), { currentPath: currentPath, propertyPath: undefined, seen: [] });
return Object.assign(Object.assign({}, _options), { currentPath: currentPath, propertyPath: undefined, seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [
def._def,
{
def: def._def,
path: [..._options.basePath, _options.definitionPath, name],
// Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
jsonSchema: undefined,
},
])) });
};
exports.getRefs = getRefs;
import { ZodSchema } from "zod";
import { Options } from "./Options";
import { Options, Targets } from "./Options";
import { JsonSchema7Type } from "./parseDef";
declare const zodToJsonSchema: <Target extends "jsonSchema7" | "openApi3" = "jsonSchema7">(schema: ZodSchema<any>, options?: string | Partial<Options<Target>> | undefined) => (Target extends "jsonSchema7" ? JsonSchema7Type : object) & {
declare const zodToJsonSchema: <Target extends Targets = "jsonSchema7">(schema: ZodSchema<any>, options?: string | Partial<Options<Target>> | undefined) => (Target extends "jsonSchema7" ? JsonSchema7Type : object) & {
$schema?: string | undefined;
definitions?: {
[key: string]: Target extends "jsonSchema7" ? JsonSchema7Type : object;
[key: string]: Target extends "jsonSchema7" ? JsonSchema7Type : Target extends "jsonSchema2019-09" ? JsonSchema7Type : object;
} | undefined;
};
export { zodToJsonSchema };

@@ -12,3 +12,3 @@ "use strict";

var _a;
return (Object.assign(Object.assign({}, acc), { [name]: (_a = (0, parseDef_1.parseDef)(schema._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.basePath, refs.definitionPath, name] }))) !== null && _a !== void 0 ? _a : {} }));
return (Object.assign(Object.assign({}, acc), { [name]: (_a = (0, parseDef_1.parseDef)(schema._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.basePath, refs.definitionPath, name] }), true)) !== null && _a !== void 0 ? _a : {} }));
}, {})

@@ -19,3 +19,3 @@ : undefined;

? refs
: Object.assign(Object.assign({}, refs), { currentPath: [...refs.basePath, refs.definitionPath, name] }))) !== null && _a !== void 0 ? _a : {};
: Object.assign(Object.assign({}, refs), { currentPath: [...refs.basePath, refs.definitionPath, name] }), false)) !== null && _a !== void 0 ? _a : {};
const combined = name === undefined

@@ -35,4 +35,7 @@ ? definitions

}
else if (refs.target === "jsonSchema2019-09") {
combined.$schema = "https://json-schema.org/draft/2019-09/schema#";
}
return combined;
};
exports.zodToJsonSchema = zodToJsonSchema;
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