{"_id":"@alcyone-labs/zod-to-json-schema","_rev":"2-08e3eb21df56f7154c0c9f0bbbbd9a2f","name":"@alcyone-labs/zod-to-json-schema","dist-tags":{"latest":"4.0.10"},"versions":{"4.0.5":{"name":"@alcyone-labs/zod-to-json-schema","version":"4.0.5","keywords":["zod","json","schema","open","api","conversion"],"author":{"name":"Stefan Terdell"},"license":"ISC","_id":"@alcyone-labs/zod-to-json-schema@4.0.5","maintainers":[{"name":"nembleton","email":"nicolas.embleton@gmail.com"}],"contributors":[{"url":"https://github.com/nicolasembleton","name":"Nicolas Embleton"},{"url":"https://github.com/mrhammadasif","name":"Hammad Asif"},{"url":"https://github.com/Noah2610","name":"Noah Rosenzweig"},{"url":"https://github.com/johngeorgewright","name":"John Wright"},{"url":"https://github.com/krzysztofciombor","name":"Krzysztof Ciombor"},{"url":"https://github.com/mokocm","name":"Yuta Mombetsu"},{"url":"https://github.com/tomarad","name":"Tom Arad"},{"url":"https://github.com/iway1","name":"Isaac Way"},{"url":"https://github.com/Andy2003","name":"Andreas Berger"},{"url":"https://github.com/Janpot","name":"Jan Potoms"},{"url":"https://github.com/scammi","name":"Santiago Cammi"},{"url":"https://github.com/Planeshifter","name":"Philipp Burckhardt"},{"url":"https://github.com/Bram-dc","name":"Bram del Canho"},{"url":"https://github.com/gthecht","name":"Gilad Hecht"},{"url":"https://github.com/colinhacks","name":"Colin McDonnell"},{"url":"https://github.com/Spappz","name":"Spappz"},{"url":"https://github.com/jacoblee93","name":"Jacob Lee"},{"url":"https://github.com/brettz9","name":"Brett Zamir"},{"url":"https://github.com/imsanchez","name":"Isaiah Marc Sanchez"},{"url":"https://github.com/mitchell-merry","name":"Mitchell Merry"},{"url":"https://github.com/enzomonjardin","name":"Enzo Monjardín"},{"url":"https://github.com/NanezX","name":"Víctor Hernández"}],"homepage":"https://github.com/alcyone-labs/zod-to-json-schema#readme","bugs":{"url":"https://github.com/alcyone-labs/zod-to-json-schema/issues"},"c8":{"exclude":["createIndex.ts","postcjs.ts","postesm.ts","test"]},"dist":{"shasum":"58fe0509eae830187d80619842d730380ea6e3c6","tarball":"https://registry.npmjs.org/@alcyone-labs/zod-to-json-schema/-/zod-to-json-schema-4.0.5.tgz","fileCount":138,"integrity":"sha512-++DftPPnO7TQ7hpZvQVMO7tUGgnejRUGU7PkHQ+biMx6HtnwexPnneBPAIiTvXEZU7+kVw2rhPC6TR5JlefBUg==","signatures":[{"sig":"MEUCIQCh3Ee/ioIOBymouhgBshjw4B4rgtg8imlXkP3vaUiqYgIgDPho/iC+7smqOiPmt5flgit6p0o5h2H+aj7f+PbfAhI=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":368988},"main":"./dist/cjs/index.js","_from":"file:alcyone-labs-zod-to-json-schema-4.0.5.tgz","types":"./dist/types/index.d.ts","module":"./dist/esm/index.js","exports":{"import":{"types":"./dist/types/index.d.ts","default":"./dist/esm/index.js"},"require":{"types":"./dist/types/index.d.ts","default":"./dist/cjs/index.js"}},"scripts":{"dry":"npm run build && npm pub --dry-run","gen":"tsx createIndex.ts","test":"tsx test/index.ts","build":"npm i && npm run gen && npm test && rimraf ./dist && npm run build:types && npm run build:cjs && npm run build:esm && npm run build:test","test:gen":"tsx test/createIndex.ts","build:cjs":"tsc -p tsconfig.cjs.json && tsx postcjs.ts","build:esm":"tsc -p tsconfig.esm.json && tsx postesm.ts","build:test":"npm --prefix ./dist-test test","test:watch":"tsx watch test/index.ts","build:types":"tsc -p tsconfig.types.json"},"_npmUser":{"name":"nembleton","email":"nicolas.embleton@gmail.com"},"_resolved":"/private/var/folders/27/xlh5p6rd54vgnqk_t2kq551c0000gn/T/5855af87d2c1948fa346e8ca71c2bf1b/alcyone-labs-zod-to-json-schema-4.0.5.tgz","_integrity":"sha512-++DftPPnO7TQ7hpZvQVMO7tUGgnejRUGU7PkHQ+biMx6HtnwexPnneBPAIiTvXEZU7+kVw2rhPC6TR5JlefBUg==","repository":{"url":"git+https://github.com/alcyone-labs/zod-to-json-schema.git","type":"git"},"_npmVersion":"10.9.2","description":"Converts Zod schemas to Json Schemas (Fork upgraded to Zod V4)","directories":{},"_nodeVersion":"22.15.1","_hasShrinkwrap":false,"devDependencies":{"ajv":"^8.17.1","tsx":"^4.20.3","zod":"^4.0.5","rimraf":"^6.0.1","fast-diff":"^1.3.0","ajv-errors":"^3.0.0","typescript":"^5.8.3","@types/node":"^20.19.9","ajv-formats":"^2.1.1","@types/json-schema":"^7.0.15","local-ref-resolver":"^0.2.0"},"peerDependencies":{"zod":"^4.0.5"},"_npmOperationalInternal":{"tmp":"tmp/zod-to-json-schema_4.0.5_1753450368320_0.4218686572767518","host":"s3://npm-registry-packages-npm-production"}},"4.0.10":{"name":"@alcyone-labs/zod-to-json-schema","version":"4.0.10","description":"Converts Zod schemas to Json Schemas (Fork upgraded to Zod V4)","types":"./dist/types/index.d.ts","main":"./dist/cjs/index.js","module":"./dist/esm/index.js","exports":{"import":{"types":"./dist/types/index.d.ts","default":"./dist/esm/index.js"},"require":{"types":"./dist/types/index.d.ts","default":"./dist/cjs/index.js"}},"c8":{"exclude":["createIndex.ts","postcjs.ts","postesm.ts","test"]},"keywords":["zod","json","schema","open","api","conversion"],"author":{"name":"Stefan Terdell"},"contributors":[{"name":"Nicolas Embleton","url":"https://github.com/nicolasembleton"},{"name":"Hammad Asif","url":"https://github.com/mrhammadasif"},{"name":"Noah Rosenzweig","url":"https://github.com/Noah2610"},{"name":"John Wright","url":"https://github.com/johngeorgewright"},{"name":"Krzysztof Ciombor","url":"https://github.com/krzysztofciombor"},{"name":"Yuta Mombetsu","url":"https://github.com/mokocm"},{"name":"Tom Arad","url":"https://github.com/tomarad"},{"name":"Isaac Way","url":"https://github.com/iway1"},{"name":"Andreas Berger","url":"https://github.com/Andy2003"},{"name":"Jan Potoms","url":"https://github.com/Janpot"},{"name":"Santiago Cammi","url":"https://github.com/scammi"},{"name":"Philipp Burckhardt","url":"https://github.com/Planeshifter"},{"name":"Bram del Canho","url":"https://github.com/Bram-dc"},{"name":"Gilad Hecht","url":"https://github.com/gthecht"},{"name":"Colin McDonnell","url":"https://github.com/colinhacks"},{"name":"Spappz","url":"https://github.com/Spappz"},{"name":"Jacob Lee","url":"https://github.com/jacoblee93"},{"name":"Brett Zamir","url":"https://github.com/brettz9"},{"name":"Isaiah Marc Sanchez","url":"https://github.com/imsanchez"},{"name":"Mitchell Merry","url":"https://github.com/mitchell-merry"},{"name":"Enzo Monjardín","url":"https://github.com/enzomonjardin"},{"name":"Víctor Hernández","url":"https://github.com/NanezX"}],"repository":{"type":"git","url":"git+https://github.com/alcyone-labs/zod-to-json-schema.git"},"license":"ISC","peerDependencies":{"zod":"^4.0.5"},"devDependencies":{"@types/json-schema":"^7.0.15","@types/node":"^20.19.9","ajv":"^8.17.1","ajv-errors":"^3.0.0","ajv-formats":"^2.1.1","fast-diff":"^1.3.0","local-ref-resolver":"^0.2.0","rimraf":"^6.0.1","tsx":"^4.20.3","typescript":"^5.8.3","zod":"^4.0.10"},"scripts":{"build:test":"npm --prefix ./dist-test test","build:types":"tsc -p tsconfig.types.json","build:cjs":"tsc -p tsconfig.cjs.json && tsx postcjs.ts","build:esm":"tsc -p tsconfig.esm.json && tsx postesm.ts","build":"npm i && npm run gen && npm test && rimraf ./dist && npm run build:types && npm run build:cjs && npm run build:esm && npm run build:test","dry":"npm run build && npm pub --dry-run","test:watch":"tsx watch test/index.ts","test:gen":"tsx test/createIndex.ts","test":"tsx test/index.ts","gen":"tsx createIndex.ts"},"_id":"@alcyone-labs/zod-to-json-schema@4.0.10","bugs":{"url":"https://github.com/alcyone-labs/zod-to-json-schema/issues"},"homepage":"https://github.com/alcyone-labs/zod-to-json-schema#readme","_integrity":"sha512-TFsSpAPToqmqmT85SGHXuxoCwEeK9zUDvn512O9aBVvWRhSuy+VvAXZkifzsdllD3ncF0ZjUrf4MpBwIEixdWQ==","_resolved":"/private/var/folders/27/xlh5p6rd54vgnqk_t2kq551c0000gn/T/2ea0e4fe52fb6855ce2fa5a1e09e8859/alcyone-labs-zod-to-json-schema-4.0.10.tgz","_from":"file:alcyone-labs-zod-to-json-schema-4.0.10.tgz","_nodeVersion":"22.15.1","_npmVersion":"10.9.2","dist":{"integrity":"sha512-TFsSpAPToqmqmT85SGHXuxoCwEeK9zUDvn512O9aBVvWRhSuy+VvAXZkifzsdllD3ncF0ZjUrf4MpBwIEixdWQ==","shasum":"e8b6808799610702aec07ebb87a6125c64294a09","tarball":"https://registry.npmjs.org/@alcyone-labs/zod-to-json-schema/-/zod-to-json-schema-4.0.10.tgz","fileCount":138,"unpackedSize":369256,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEYCIQDrJO6NjmGOfDSS+tCAr3KeJPtlfvi7YgRE/wq03ZN2PwIhAKWhluWpJu0ol/SMMevh1G1M+LutH3AD/SmwwrgzqgRu"}]},"_npmUser":{"name":"nembleton","email":"nicolas.embleton@gmail.com"},"directories":{},"maintainers":[{"name":"nembleton","email":"nicolas.embleton@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/zod-to-json-schema_4.0.10_1753451623013_0.15458231435842706"},"_hasShrinkwrap":false}},"time":{"created":"2025-07-25T13:32:48.199Z","modified":"2025-07-25T13:53:43.376Z","4.0.5":"2025-07-25T13:32:48.495Z","4.0.10":"2025-07-25T13:53:43.196Z"},"bugs":{"url":"https://github.com/alcyone-labs/zod-to-json-schema/issues"},"author":{"name":"Stefan Terdell"},"license":"ISC","homepage":"https://github.com/alcyone-labs/zod-to-json-schema#readme","keywords":["zod","json","schema","open","api","conversion"],"repository":{"type":"git","url":"git+https://github.com/alcyone-labs/zod-to-json-schema.git"},"description":"Converts Zod schemas to Json Schemas (Fork upgraded to Zod V4)","contributors":[{"name":"Nicolas Embleton","url":"https://github.com/nicolasembleton"},{"name":"Hammad Asif","url":"https://github.com/mrhammadasif"},{"name":"Noah Rosenzweig","url":"https://github.com/Noah2610"},{"name":"John Wright","url":"https://github.com/johngeorgewright"},{"name":"Krzysztof Ciombor","url":"https://github.com/krzysztofciombor"},{"name":"Yuta Mombetsu","url":"https://github.com/mokocm"},{"name":"Tom Arad","url":"https://github.com/tomarad"},{"name":"Isaac Way","url":"https://github.com/iway1"},{"name":"Andreas Berger","url":"https://github.com/Andy2003"},{"name":"Jan Potoms","url":"https://github.com/Janpot"},{"name":"Santiago Cammi","url":"https://github.com/scammi"},{"name":"Philipp Burckhardt","url":"https://github.com/Planeshifter"},{"name":"Bram del Canho","url":"https://github.com/Bram-dc"},{"name":"Gilad Hecht","url":"https://github.com/gthecht"},{"name":"Colin McDonnell","url":"https://github.com/colinhacks"},{"name":"Spappz","url":"https://github.com/Spappz"},{"name":"Jacob Lee","url":"https://github.com/jacoblee93"},{"name":"Brett Zamir","url":"https://github.com/brettz9"},{"name":"Isaiah Marc Sanchez","url":"https://github.com/imsanchez"},{"name":"Mitchell Merry","url":"https://github.com/mitchell-merry"},{"name":"Enzo Monjardín","url":"https://github.com/enzomonjardin"},{"name":"Víctor Hernández","url":"https://github.com/NanezX"}],"maintainers":[{"name":"nembleton","email":"nicolas.embleton@gmail.com"}],"readme":"# Zod to Json Schema\n\n[![NPM Version](https://img.shields.io/npm/v/@alcyone-labs/zod-to-json-schema.svg)](https://npmjs.org/package/@alcyone-labs/zod-to-json-schema)\n[![NPM Downloads](https://img.shields.io/npm/dw/zod-to-json-schema.svg)](https://npmjs.org/package/zod-to-json-schema)\n\n_Looking for the exact opposite (for Zod V3)? Check out [json-schema-to-zod](https://npmjs.org/package/json-schema-to-zod)_\n\n## Summary\n\nNote: This is a fork upgraded to Zod V4\n\nDoes what it says on the tin; converts [Zod schemas](https://github.com/colinhacks/zod) V4 into [JSON schemas](https://json-schema.org/)! Even though Zod [now supports JSON Schemas natively](https://zod.dev/json-schema), some people still need an upgraded version of this library, so here it is.\n\n- Supports all relevant schema types, basic string, number and array length validations and string patterns.\n- Resolves recursive and recurring schemas with internal `$ref`s.\n- Supports targeting legacy Open API 3.0 specification (3.1 supports regular Json Schema).\n- Supports Open AI strict mode schemas (Optional object properties are replaced with required but nullable ones).\n\n## Zod Version Compatibility\n\nThis library is **fully compatible with Zod V4** and maintains backward compatibility with most Zod V3 patterns.\n\n### Zod V4 Support ✅\n\n- **Full compatibility** with Zod V4's new internal structure\n- **Error messages** fully supported with V4's new error system\n- **All validation types** working (string, number, object, array, union, etc.)\n- **Metadata and descriptions** fully supported\n- **Reference handling** optimized for V4's schema structure\n\n### Backward Compatibility\n\n**Most Zod V3 code will work unchanged** with this library and Zod V4. The main exceptions are:\n\n#### Breaking Changes from Zod V3 → V4\n\nSome Zod V3 APIs were removed in V4. Here's what changed and how to migrate:\n\n#### Removed String Methods (Breaking)\n\n- ❌ `z.string().ip()` → ✅ Use `z.string().ipv4()` or `z.string().ipv6()` or `z.union([z.string().ipv4(), z.string().ipv6()])`\n- ❌ `z.string().cidr()` → ✅ Use `z.string().cidrv4()` or `z.string().cidrv6()`\n\n#### Deprecated but Still Supported (Non-breaking)\n\n- `z.string().email()` → Prefer `z.email()` (top-level API)\n- `z.object().strict()` → Prefer `z.strictObject()`\n- `z.object().passthrough()` → Prefer `z.looseObject()`\n- `z.string().min(5, { message: \"...\" })` → Prefer `z.string().min(5, { error: \"...\" })`\n\nAll deprecated methods still work but may be removed in future Zod versions.\n\n## Sponsors\n\nA great big thank you to our amazing sponsors! Please consider joining them through my [GitHub Sponsors page](https://github.com/sponsors/StefanTerdell). Every cent helps, but these fellas have really gone above and beyond 💚:\n\n<table align=\"center\" style=\"justify-content: center;align-items: center;display: flex;\">\n  <tr>\n    <td align=\"center\">\n      <p></p>\n      <p>\n      <div style=\"background-color: white; padding: 4px; padding-bottom: 8px;\" alt=\"stainless\">\n        <a href=\"https://www.coderabbit.ai/\">\n          <picture height=\"45px\">\n             <source media=\"(prefers-color-scheme: dark)\" srcset=\"https://github.com/user-attachments/assets/eea24edb-ff20-4532-b57c-e8719f455d6d\">\n          <img alt=\"CodeRabbit logo\" height=\"45px\" src=\"https://github.com/user-attachments/assets/d791bc7d-dc60-4d55-9c31-97779839cb74\">\n          </picture>\n        </a>\n      </div>\n      <br  />\n      Cut code review time & bugs in half\n      <br/>\n      <a href=\"https://www.coderabbit.ai/\" style=\"text-decoration:none;\">coderabbit.ai</a>\n      </p>\n      <p></p>\n    </td>\n  </tr>\n  <tr>\n    <td align=\"center\">\n      <p></p>\n      <p>\n      <a href=\"https://retool.com/?ref=stefanterdell&utm_source=github&utm_medium=referral&utm_campaign=stefanterdell\">\n        <picture height=\"45px\">\n          <source media=\"(prefers-color-scheme: dark)\" srcset=\"https://github.com/colinhacks/zod/assets/3084745/ac65013f-aeb4-48dd-a2ee-41040b69cbe6\">\n          <img alt=\"stainless\" height=\"45px\" src=\"https://github.com/colinhacks/zod/assets/3084745/5ef4c11b-efeb-4495-90a8-41b83f798600\">\n        </picture>\n      </a>\n      <br  />\n      Build AI apps and workflows with <a href=\"https://retool.com/products/ai?ref=stefanterdell&utm_source=github&utm_medium=referral&utm_campaign=stefanterdell\">Retool AI</a>\n      <br/>\n      <a href=\"https://retool.com/?ref=stefanterdell&utm_source=github&utm_medium=referral&utm_campaign=stefanterdell\" style=\"text-decoration:none;\">retool.com</a>\n      </p>\n      <p></p>\n    </td>\n  </tr>\n</table>\n\n## Usage\n\n### Basic example\n\n```typescript\nimport { z } from \"zod\";\nimport { zodToJsonSchema } from \"zod-to-json-schema\";\n\nconst mySchema = z\n  .object({\n    myString: z.string().min(5),\n    myUnion: z.union([z.number(), z.boolean()]),\n  })\n  .describe(\"My neat object schema\");\n\nconst jsonSchema = zodToJsonSchema(mySchema, \"mySchema\");\n```\n\n#### Expected output\n\n```json\n{\n  \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n  \"$ref\": \"#/definitions/mySchema\",\n  \"definitions\": {\n    \"mySchema\": {\n      \"description\": \"My neat object schema\",\n      \"type\": \"object\",\n      \"properties\": {\n        \"myString\": {\n          \"type\": \"string\",\n          \"minLength\": 5\n        },\n        \"myUnion\": {\n          \"type\": [\"number\", \"boolean\"]\n        }\n      },\n      \"additionalProperties\": false,\n      \"required\": [\"myString\", \"myUnion\"]\n    }\n  }\n}\n```\n\n## Options\n\n### Schema name\n\nYou can pass a string as the second parameter of the main zodToJsonSchema function. If you do, your schema will end up inside a definitions object property on the root and referenced from there. Alternatively, you can pass the name as the `name` property of the options object (see below).\n\n### Options object\n\nInstead of the schema name (or nothing), you can pass an options object as the second parameter. The following options are available:\n\n| Option                                                                             | Effect                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |\n| ---------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| **name**?: _string_                                                                | As described above.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |\n| **nameStrategy**?: \"ref\" \\| \"title\"                                                | Adds name as \"title\" meta instead of as a ref as described above                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |\n| **basePath**?: string[]                                                            | The base path of the root reference builder. Defaults to [\"#\"].                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |\n| **$refStrategy**?: \"root\" \\| \"relative\" \\| \"seen\" \\| \"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>**\"seen\"** reuses the output of any \"seen\" Zod schema. In theory it's a more performant version of \"none\", but in practice this behaviour can cause issues with nested schemas and has now gotten its own option.</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\". |\n| **effectStrategy**?: \"input\" \\| \"any\"                                              | The effects output strategy. Defaults to \"input\". _See known issues!_                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |\n| **dateStrategy**?: \"format:date\" \\| \"format:date-time\" \\| \"string\" \\| \"integer\"    | Date strategy, integer allow to specify in unix-time min and max values. \"format:date\" creates a string schema with format: \"date\". \"format:date-time\" creates a string schema with format: \"date-time\". \"string\" is intepreted as \"format:date-time\". \"integer\" creates an integer schema with format \"unix-time\" (unless target \"openApi3\" is used min max checks are also respected)                                                                                                                                                                                                                                                                                                 |\n|                                                                                    |\n| **emailStrategy**?: \"format:email\" \\| \"format:idn-email\" \\| \"pattern:zod\"          | Choose how to handle the email string check. Defaults to \"format:email\".                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |\n| **base64Strategy**?: \"format:binary\" \\| \"contentEnconding:base64\" \\| \"pattern:zod\" | Choose how to handle the base64 string check. Defaults to \"contentEncoding:base64\" as described [here](https://json-schema.org/understanding-json-schema/reference/non_json_data#contentencoding). Note that \"format:binary\" is not represented in the output type as it's not part of the JSON Schema spec and only intended to be used when targeting OpenAPI 3.0. Later versions of OpenAPI support contentEncoding.                                                                                                                                                                                                                                                                 |\n| **definitionPath**?: \"definitions\" \\| \"$defs\"                                      | The name of the definitions property when name is passed. Defaults to \"definitions\".                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |\n| **target**?: \"jsonSchema7\" \\| \"jsonSchema2019-09\" \\| \"openApi3\" \\| \"openAi\"        | Which spec to target. Defaults to \"jsonSchema7\"                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |\n| **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()                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |\n| **definitions**?: Record<string, ZodSchema>                                        | See separate section below                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |\n| **errorMessages**?: boolean                                                        | Include custom error messages created via chained function checks for supported zod types. See section below                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |\n| **markdownDescription**?: boolean                                                  | Copies the `description` meta to `markdownDescription`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |\n| **patternStrategy**?: \"escape\" \\| \"preserve\"                                       | The Zod string validations `.includes()`, `.startsWith()`, and `.endsWith()` must be converted to regex to be compatible with JSON Schema's `pattern`. For safety, all non-alphanumeric characters are `escape`d by default (consider `z.string().includes(\".\")`), but this can occasionally cause problems with Unicode-flagged regex parsers. Use `preserve` to prevent this escaping behaviour and preserve the exact string written, even if it results in an inaccurate regex.                                                                                                                                                                                                     |\n| **applyRegexFlags**?: boolean                                                      | JSON Schema's `pattern` doesn't support RegExp flags, but Zod's `z.string().regex()` does. When this option is true (default false), a best-effort is made to transform regexes into a flag-independent form (e.g. `/x/i => /[xX]/` ). Supported flags: `i` (basic Latin only), `m`, `s`.                                                                                                                                                                                                                                                                                                                                                                                               |\n| **pipeStrategy**?: \"all\" \\| \"input\" \\| \"output\"                                    | Decide which types should be included when using `z.pipe`, for example `z.string().pipe(z.number())` would return both `string` and `number` by default, only `string` for \"input\" and only `number` for \"output\".                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |\n| **removeAdditionalStrategy**?: \"passthrough\" \\| \"strict\"                           | Decide when `additionalProperties` should be allowed. See the section on additional properties for details.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |\n| **allowedAdditionalProperties**?: `true` \\| `undefined`                            | What value to give `additionalProperties` when allowed. See the section on additional properties for details.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |\n| **rejectedAdditionalProperties**?: `false` \\| `undefined`                          | What value to give `additionalProperties` when rejected. See the section on additional properties for details.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |\n| **override**?: callback                                                            | See section                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |\n| **postProcess**?: callback                                                         | See section                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |\n| **openAiAnyTypeName**?: string                                                     | Decides the name of a Json schema used to allow semi-arbitrary values in Open AI structured output. If any value in the Zod-schema resolves to any \"any\"-type schema it will reference a definition of this name. If no such definition is provided a default Json schema will be used. Defaults to \"OpenAiAnyType\"                                                                                                                                                                                                                                                                                                                                                                     |\n\n### Definitions\n\nThe definitions option lets you manually add recurring schemas into definitions for cleaner outputs. It's fully compatible with named schemas, changed definitions path and base path. Here's a simple example:\n\n```typescript\nconst myRecurringSchema = z.string();\nconst myObjectSchema = z.object({ a: myRecurringSchema, b: myRecurringSchema });\n\nconst myJsonSchema = zodToJsonSchema(myObjectSchema, {\n  definitions: { myRecurringSchema },\n});\n```\n\n#### Result\n\n```json\n{\n  \"type\": \"object\",\n  \"properties\": {\n    \"a\": {\n      \"$ref\": \"#/definitions/myRecurringSchema\"\n    },\n    \"b\": {\n      \"$ref\": \"#/definitions/myRecurringSchema\"\n    }\n  },\n  \"definitions\": {\n    \"myRecurringSchema\": {\n      \"type\": \"string\"\n    }\n  }\n}\n```\n\n### Error Messages\n\nThis feature allows optionally including error messages created via chained function calls for supported zod types:\n\n```ts\n// string schema with additional chained function call checks\nconst EmailSchema = z.string().email(\"Invalid email\").min(5, \"Too short\");\n\nconst jsonSchema = zodToJsonSchema(EmailSchema, { errorMessages: true });\n```\n\n#### Result\n\n```json\n{\n  \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n  \"type\": \"string\",\n  \"format\": \"email\",\n  \"minLength\": 5,\n  \"errorMessage\": {\n    \"format\": \"Invalid email\",\n    \"minLength\": \"Too short\"\n  }\n}\n```\n\nThis allows for field specific, validation step specific error messages which can be useful for building forms and such. This format is accepted by `react-hook-form`'s ajv resolver (and therefor `ajv-errors` which it uses under the hood). Note that if using AJV with this format will require [enabling `ajv-errors`](https://ajv.js.org/packages/ajv-errors.html#usage) as vanilla AJV does not accept this format by default.\n\n#### Custom Error Message Support\n\n- ZodString\n  - regex\n  - min, max\n  - email, cuid, uuid, url\n  - endsWith, startsWith\n- ZodNumber\n  - min, max, lt, lte, gt, gte,\n  - int\n  - multipleOf\n- ZodSet\n  - min, max\n- ZodArray\n  - min, max\n\n### Additional properties\n\nBy default, Zod removes undeclared properties when parsing object schemas. In order to replicate the expected output of this behaviour, the default for behaviour of zodToJsonSchema is to set `\"additionalProperties\"` to `false` (although the correctness of this can be debated). If you wish to allow undeclared properties you can either:\n\n- Set `removeAdditionalStrategy` to `\"strict\"`. This will allow additional properties for any object schema that is not declared with `.strict()`.\n- Leave `removeAdditionalStrategy` set to its default value of `\"passthrough\"`, and add `.passtrough()` to your object schema.\n\n#### Removing the `additionalProperties` keyword using the `allowedAdditionalProperties` and/or `rejectedAdditionalProperties` options.\n\nSome schema definitions (like Googles Gen AI API for instance) does not allow the `additionalProperties` keyword at all. Luckily the JSON Schema spec allows for this: leaving the keyword undefined _should_ have the same effect as setting it to true (as per usual YMMV). To enable this behaviour, set the option `allowedAdditionalProperties` to `undefined`.\n\nTo exclude the keyword even when additional properties are _not_ allowed, set the `rejectedAdditionalProperties` to `undefined` as well.\n\n_Heads up ⚠️: Both of these options will be ignored if your schema is declared with `.catchall(...)` as the provided schema will be used instead (if valid)._\n\n#### Expected outputs\n\n| `z.object({})` + option   | `\"additionalProperties\"` value                              |\n| ------------------------- | ----------------------------------------------------------- |\n| `.strip()` (default)      | `false` if strategy is `\"passtrough\"`, `true` if `\"strict\"` |\n| `.passtrough()`           | `true`                                                      |\n| `.strict()`               | `false`                                                     |\n| `.catchall(z.string())`   | `{ \"type\": \"string\" }`                                      |\n| `.catchall(z.function())` | `undefined` (function schemas are not currently parseable)  |\n\nSubstitute `true` and `false` for `undefined` according to `allowedAdditionalProperties` and/or `rejectedAdditionalProperties` respectively.\n\n### `override`\n\nThis options takes a callback receiving a Zod schema definition, the current reference object (containing the current ref path and other options), an argument containing inforation about wether or not the schema has been encountered before, and a forceResolution argument.\n\nImportant: if you don't want to override the current item you have to return the `ignoreOverride` symbol exported from the index. This is because `undefined` is a valid option to return when you want the property to be excluded from the resulting JSON schema.\n\n```typescript\nimport zodToJsonSchema, { ignoreOverride } from \"zod-to-json-schema\";\n\nzodToJsonSchema(\n  z.object({\n    ignoreThis: z.string(),\n    overrideThis: z.string(),\n    removeThis: z.string(),\n  }),\n  {\n    override: (def, refs) => {\n      const path = refs.currentPath.join(\"/\");\n\n      if (path === \"#/properties/overrideThis\") {\n        return {\n          type: \"integer\",\n        };\n      }\n\n      if (path === \"#/properties/removeThis\") {\n        return undefined;\n      }\n\n      // Important! Do not return `undefined` or void unless you want to remove the property from the resulting schema completely.\n      return ignoreOverride;\n    },\n  },\n);\n```\n\nExpected output:\n\n```json\n{\n  \"type\": \"object\",\n  \"required\": [\"ignoreThis\", \"overrideThis\"],\n  \"properties\": {\n    \"ignoreThis\": {\n      \"type\": \"string\"\n    },\n    \"overrideThis\": {\n      \"type\": \"integer\"\n    }\n  },\n  \"additionalProperties\": false\n}\n```\n\n### `postProcess`\n\nBesided receiving all arguments of the `override` callback, the `postProcess` callback also receives the generated schema. It should always return a JSON Schema, or `undefined` if you wish to filter it out. Unlike the `override` callback you do not have to return `ignoreOverride` if you are happy with the produced schema; simply return it unchanged.\n\n```typescript\nimport zodToJsonSchema, { PostProcessCallback } from \"zod-to-json-schema\";\n\n// Define the callback to be used to process the output using the PostProcessCallback type:\nconst postProcess: PostProcessCallback = (\n  // The original output produced by the package itself:\n  jsonSchema,\n  // The ZodSchema def used to produce the original schema:\n  def,\n  // The refs object containing the current path, passed options, etc.\n  refs,\n) => {\n  if (!jsonSchema) {\n    return jsonSchema;\n  }\n\n  // Try to expand description as JSON meta:\n  if (jsonSchema.description) {\n    try {\n      jsonSchema = {\n        ...jsonSchema,\n        ...JSON.parse(jsonSchema.description),\n      };\n    } catch {}\n  }\n\n  // Make all numbers nullable:\n  if (\"type\" in jsonSchema! && jsonSchema.type === \"number\") {\n    jsonSchema.type = [\"number\", \"null\"];\n  }\n\n  // Add the refs path, just because\n  (jsonSchema as any).path = refs.currentPath;\n\n  return jsonSchema;\n};\n\nconst jsonSchema = zodToJsonSchema(zodSchema, { postProcess });\n```\n\n#### Using `postProcess` for including examples and other meta\n\nAdding support for examples and other JSON Schema meta keys are among the most commonly requested features for this project. Unfortunately the current Zod major (3) has pretty anemic support for this, so some userland hacking is required. Since this is such a common usecase I've included a helper function that simply tries to parse any description as JSON and expand it into the resulting schema.\n\nSimply stringify whatever you want added to the output schema as the description, then import and use `jsonDescription` as the postProcess option:\n\n```typescript\nimport zodToJsonSchema, { jsonDescription } from \"zod-to-json-schema\";\n\nconst zodSchema = z.string().describe(\n  JSON.stringify({\n    title: \"My string\",\n    description: \"My description\",\n    examples: [\"Foo\", \"Bar\"],\n    whatever: 123,\n  }),\n);\n\nconst jsonSchema = zodToJsonSchema(zodSchema, {\n  postProcess: jsonDescription,\n});\n```\n\nExpected output:\n\n```json\n{\n  \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n  \"type\": \"string\",\n  \"title\": \"My string\",\n  \"description\": \"My description\",\n  \"examples\": [\"Foo\", \"Bar\"],\n  \"whatever\": 123\n}\n```\n\n## Migration Guide: Zod V3 → V4\n\nIf you're upgrading from Zod V3 to V4, here are the changes you need to make:\n\n### String Validation Changes\n\n#### IP Address Validation\n\n```typescript\n// ❌ Zod V3 (removed in V4)\nz.string().ip();\nz.string().ip(\"v4\");\nz.string().ip(\"v6\");\n\n// ✅ Zod V4\nz.string().ipv4();\nz.string().ipv6();\nz.union([z.string().ipv4(), z.string().ipv6()]); // for both\n```\n\n#### CIDR Validation\n\n```typescript\n// ❌ Zod V3 (removed in V4)\nz.string().cidr();\nz.string().cidr(\"v4\");\nz.string().cidr(\"v6\");\n\n// ✅ Zod V4\nz.string().cidrv4();\nz.string().cidrv6();\nz.union([z.string().cidrv4(), z.string().cidrv6()]); // for both\n```\n\n#### Recommended: Use Top-Level APIs\n\n```typescript\n// ✅ Zod V4 preferred (more tree-shakable)\nz.email();\nz.uuid();\nz.url();\nz.ipv4();\nz.ipv6();\n\n// ⚠️ Still works but deprecated\nz.string().email();\nz.string().uuid();\nz.string().url();\nz.string().ipv4();\nz.string().ipv6();\n```\n\n### Object Schema Changes\n\n```typescript\n// ⚠️ Deprecated but still works\nz.object({ name: z.string() }).strict();\nz.object({ name: z.string() }).passthrough();\n\n// ✅ Zod V4 preferred\nz.strictObject({ name: z.string() });\nz.looseObject({ name: z.string() });\n```\n\n### Error Message Changes\n\n```typescript\n// ⚠️ Deprecated but still works\nz.string().min(5, { message: \"Too short\" });\n\n// ✅ Zod V4 preferred\nz.string().min(5, { error: \"Too short\" });\n```\n\n### Workarounds for Removed APIs\n\nIf you need to support both IPv4 and IPv6 (replacing the old `.ip()` method):\n\n```typescript\n// Create a reusable IP validator\nconst ipSchema = z.union([z.string().ipv4(), z.string().ipv6()]);\n\n// Use in your schemas\nconst serverSchema = z.object({\n  host: ipSchema,\n  port: z.number(),\n});\n```\n\nFor CIDR ranges:\n\n```typescript\nconst cidrSchema = z.union([z.string().cidrv4(), z.string().cidrv6()]);\n```\n\n### Additional Changes to Be Aware Of\n\n#### UUID Validation is Stricter\n\n```typescript\n// Zod V4 is stricter about UUID format\nz.string().uuid(); // Now validates against RFC 9562/4122\n\n// For more permissive UUID-like validation:\nz.string().guid(); // Accepts any 8-4-4-4-12 hex pattern\n```\n\n#### Base64URL No Longer Allows Padding\n\n```typescript\n// Zod V4 base64url is stricter (no padding allowed)\nz.string().base64url(); // Must be unpadded\n```\n\n#### Number Validation Changes\n\n```typescript\n// Safe integers only\nz.number().int(); // Now only accepts safe integers\nz.number().safe(); // Deprecated, behaves like .int()\n\n// Recommended: Use the new top-level API\nz.int(); // Preferred for integers\n```\n\n#### Removed Object Methods\n\n```typescript\n// ❌ Removed in Zod V4\nz.object().nonstrict(); // Use z.object() (default behavior)\nz.object().deepPartial(); // No direct replacement (was anti-pattern)\n\n// ⚠️ Deprecated but still works\nz.object().strip(); // Use z.object() (default behavior)\n```\n\n### Migration Helpers\n\nFor easier migration, you can create these helper functions:\n\n```typescript\n// Helper for IP validation (replaces old .ip() method)\nexport const ipAddress = () => z.union([z.string().ipv4(), z.string().ipv6()]);\n\n// Helper for CIDR validation (replaces old .cidr() method)\nexport const cidrRange = () =>\n  z.union([z.string().cidrv4(), z.string().cidrv6()]);\n\n// Helper for flexible UUID validation\nexport const flexibleUuid = () => z.string().guid(); // More permissive than .uuid()\n\n// Usage in your schemas\nconst networkSchema = z.object({\n  serverIp: ipAddress(),\n  allowedRange: cidrRange(),\n  sessionId: flexibleUuid(),\n});\n```\n\n## Known issues\n\n- The OpenAI target should be considered experimental for now, as some combination of options may break the compatibility.\n- When using `.transform`, the return type is inferred from the supplied function. In other words, there is no schema for the return type, and there is no way to convert it in runtime. Currently the JSON schema will therefore reflect the input side of the Zod schema and not necessarily the output (the latter aka. `z.infer`). If this causes problems with your schema, consider using the effectStrategy \"any\", which will allow any type of output.\n- JSON Schemas does not support any other key type than strings for objects. When using `z.record` with any other key type, this will be ignored. An exception to this rule is `z.enum` as is supported since 3.11.3\n- Relative JSON pointers, while published alongside [JSON schema draft 2020-12](https://json-schema.org/specification.html), is not technically a part of it. Currently, most resolvers do not handle them at all.\n- Since v3, the Object parser uses `.isOptional()` to check if a property should be included in `required` or not. This has the potentially dangerous behavior of calling `.safeParse` with `undefined`. To work around this, make sure your `preprocess` and other effects callbacks are pure and not liable to throw errors. An issue has been logged in the Zod repo and can be [tracked here](https://github.com/colinhacks/zod/issues/1460).\n- JSON Schema version 2020-12 is not yet officially supported. However, you should be able to use this library to obtain a compatible schema for the 2020-12 format just by changing the returned schema's `$schema` field to: \"https://json-schema.org/draft/2020-12/schema#\"\n\n## Versioning\n\nThis package _does not_ follow semantic versioning. The major and minor versions of this package instead reflects feature parity with the [Zod package](http://npmjs.com/package/zod).\n\nI will do my best to keep API-breaking changes to an absolute minimum, but new features may appear as \"patches\", such as introducing the options pattern in 3.9.1.\n\n## Changelog\n\nhttps://github.com/StefanTerdell/zod-to-json-schema/blob/master/changelog.md\n","readmeFilename":"README.md"}