{"_id":"@crunchymonkies/zod-to-openapi","name":"@crunchymonkies/zod-to-openapi","dist-tags":{"latest":"9.2.0"},"versions":{"9.2.0":{"name":"@crunchymonkies/zod-to-openapi","version":"9.2.0","description":"Builds OpenAPI schemas from Zod schemas","main":"dist/index.cjs","module":"dist/index.mjs","types":"dist/index.d.ts","keywords":["typescript","schema","type","openapi","zod"],"repository":{"type":"git","url":"git+https://github.com/CrunchyMonkies/zod-to-openapi.git"},"homepage":"https://github.com/CrunchyMonkies/zod-to-openapi","scripts":{"build":"rollup -c","prepare":"npm run build","test":"npm run test:jest && npm run test:types","test:jest":"jest","test:types":"npx tsd --files spec/type-definitions/zod-extensions.test-d.ts --typings dist/index.d.ts","prettier":"prettier --write .","lint":"prettier --check .","prepublishOnly":"npm run build"},"dependencies":{"openapi3-ts":"^4.6.0"},"peerDependencies":{"zod":"^4.0.0"},"devDependencies":{"@rollup/plugin-commonjs":"^25.0.7","@rollup/plugin-node-resolve":"^15.2.3","@types/jest":"^29.2.5","jest":"^29.3.1","prettier":"^2.7.1","rollup":"^4.13.2","rollup-plugin-typescript2":"^0.36.0","ts-jest":"^29.0.3","tsd":"^0.32.0","typescript":"^5.5.4","yaml":"^2.2.2","zod":"^4.0.5"},"author":{"name":"Astea Solutions","email":"info@asteasolutions.com"},"license":"MIT","gitHead":"b30202b2e63bfd146b73500156d4831487786154","_id":"@crunchymonkies/zod-to-openapi@9.2.0","bugs":{"url":"https://github.com/CrunchyMonkies/zod-to-openapi/issues"},"_nodeVersion":"24.18.0","_npmVersion":"11.16.0","dist":{"integrity":"sha512-2MKyBezsEKmyvtOMw93lhSA+WakYYlwnhH+yvRRSB/07kRFnE0sjT0pPKiF/GSaNFTGzlOtlkCcCqKhTnt3eKA==","shasum":"a42cc12c7c2b539cc86ee328b6512e3abf0f0fe8","tarball":"https://registry.npmjs.org/@crunchymonkies/zod-to-openapi/-/zod-to-openapi-9.2.0.tgz","fileCount":39,"unpackedSize":249305,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIQDWY54kKaHnKLxI8rfmIan6OkkcPyXz2/99FovsbvDRHgIgOAV9lJBwfV91PKlJGjkGD5UbpeuH3oBVASvne+l7Bpk="}]},"_npmUser":{"name":"matthew.m.mckenzie","email":"matthew.m.mckenzie@gmail.com"},"directories":{},"maintainers":[{"name":"matthew.m.mckenzie","email":"matthew.m.mckenzie@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/zod-to-openapi_9.2.0_1785808112150_0.6569083256573953"},"_hasShrinkwrap":false}},"time":{"created":"2026-08-04T01:48:32.019Z","9.2.0":"2026-08-04T01:48:32.324Z","modified":"2026-08-04T01:48:32.539Z"},"maintainers":[{"name":"matthew.m.mckenzie","email":"matthew.m.mckenzie@gmail.com"}],"description":"Builds OpenAPI schemas from Zod schemas","homepage":"https://github.com/CrunchyMonkies/zod-to-openapi","keywords":["typescript","schema","type","openapi","zod"],"repository":{"type":"git","url":"git+https://github.com/CrunchyMonkies/zod-to-openapi.git"},"author":{"name":"Astea Solutions","email":"info@asteasolutions.com"},"bugs":{"url":"https://github.com/CrunchyMonkies/zod-to-openapi/issues"},"license":"MIT","readme":"# Zod to OpenAPI\n\n[![npm version](https://img.shields.io/npm/v/@asteasolutions/zod-to-openapi)](https://www.npmjs.com/package/@asteasolutions/zod-to-openapi)\n[![npm downloads](https://img.shields.io/npm/dm/@asteasolutions/zod-to-openapi)](https://www.npmjs.com/package/@asteasolutions/zod-to-openapi)\n\n> [!IMPORTANT]\n> **For Zod v3 support, please use the v7.3.4 version. However keep in mind that we do not intend to actively support that version going forward** Install with: `npm install @asteasolutions/zod-to-openapi@7.3.4`\n\nA library that uses [zod schemas](https://github.com/colinhacks/zod) to generate an Open API Swagger documentation.\n\n1. [Purpose and quick example](#purpose-and-quick-example)\n2. [Usage](#usage)\n   1. [Installation](#installation)\n   2. [The `openapi` method](#the-openapi-method)\n   3. [The Registry](#the-registry)\n   4. [The Generator](#the-generator)\n   5. [Defining schemas](#defining-schemas)\n   6. [Defining routes & webhooks](#defining-routes--webhooks)\n   7. [Defining custom components](#defining-custom-components)\n   8. [A full example](#a-full-example)\n   9. [Adding it as part of your build](#adding-it-as-part-of-your-build)\n   10. [Using schemas vs a registry](#using-schemas-vs-a-registry)\n   11. [Generation options](#generation-options)\n3. [Zod schema types](#zod-schema-types)\n   1. [Supported types](#supported-types)\n   2. [Unsupported types](#unsupported-types)\n4. [Technologies](#technologies)\n\nWe keep a changelog as part of the [GitHub releases](https://github.com/asteasolutions/zod-to-openapi/releases).\n\n## Purpose and quick example\n\nWe at [Astea Solutions](https://asteasolutions.com/) made this library because we use [zod](https://github.com/colinhacks/zod) for validation in our APIs and are tired of the duplication to also support a separate OpenAPI definition that must be kept in sync. Using `zod-to-openapi`, we generate OpenAPI definitions directly from our zod schemas, thus having a single source of truth.\n\nSimply put, it turns this:\n\n```ts\nconst UserSchema = z\n  .object({\n    id: z.string().openapi({ example: '1212121' }),\n    name: z.string().openapi({ example: 'John Doe' }),\n    age: z.number().openapi({ example: 42 }),\n  })\n  .openapi('User');\n\nregistry.registerPath({\n  method: 'get',\n  path: '/users/{id}',\n  summary: 'Get a single user',\n  request: {\n    params: z.object({ id: z.string() }),\n  },\n\n  responses: {\n    200: {\n      description: 'Object with user data.',\n      content: {\n        'application/json': {\n          schema: UserSchema,\n        },\n      },\n    },\n  },\n});\n```\n\ninto this:\n\n```yaml\ncomponents:\n  schemas:\n    User:\n      type: object\n      properties:\n        id:\n          type: string\n          example: '1212121'\n        name:\n          type: string\n          example: John Doe\n        age:\n          type: number\n          example: 42\n      required:\n        - id\n        - name\n        - age\n\n/users/{id}:\n  get:\n    summary: Get a single user\n    parameters:\n      - in: path\n        name: id\n        schema:\n          type: string\n        required: true\n    responses:\n      '200':\n        description: Object with user data\n        content:\n          application/json:\n            schema:\n              $ref: '#/components/schemas/User'\n```\n\nand you can still use `UserSchema` and the `request.params` object to validate the input of your API.\n\n## Usage\n\n### Installation\n\nThis fork is published to [GitHub Packages](https://github.com/CrunchyMonkies/zod-to-openapi/packages), not to npmjs.org. Point the `@crunchymonkies` scope at the GitHub registry in an `.npmrc` next to your `package.json`:\n\n```\n@crunchymonkies:registry=https://npm.pkg.github.com\n```\n\n```shell\nnpm install @crunchymonkies/zod-to-openapi\n# or\nyarn add @crunchymonkies/zod-to-openapi\n```\n\n> Note: GitHub Packages requires authentication even for public packages. Add a personal access token with the `read:packages` scope to your user-level `~/.npmrc`:\n>\n> ```\n> //npm.pkg.github.com/:_authToken=YOUR_TOKEN\n> ```\n>\n> In GitHub Actions, `secrets.GITHUB_TOKEN` works without any extra setup.\n\n### The `openapi` method\n\nTo keep openapi definitions natural, we add an `openapi` method to all Zod objects. Its idea is to provide a convenient way to provide OpenApi specific data.\nIt has three overloads:\n\n1. `.openapi({ [key]: value })` - this way we can specify any OpenApi fields. For example `z.number().openapi({ example: 3 })` would add `example: 3` to the generated schema.\n2. `.openapi(\"<schema-name>\")` - this way we specify that the underlying zod schema should be \"registered\" i.e added into `components/schemas` with the provided `<schema-name>`\n3. `.openapi(\"<schema-name>\", { [key]: value })` - this unites the two use cases above so that we can specify both a registration `<schema-name>` and additional metadata\n\nFor this to work, you need to call `extendZodWithOpenApi` once in your project.\n\nThis should be done only once in a common-entrypoint file of your project (for example an `index.ts`/`app.ts`). If you're using tree-shaking with Webpack, mark that file as having side-effects.\n\nIt can be bit tricky to achieve this in your codebase, because *require* is synchronous and *import* is a async.\n\n#### Using zod's .meta\nStarting from v8 (and zod v4) you can also use zod's .meta to provide metadata and we will read it accordingly.\n\nWith zod's new option for generating JSON schemas and maintaining registries we've added a pretty much seamless support for all metadata information coming from `.meta` calls as if that was metadata passed into `.openapi`.\n\nSo the following 2 schemas produce exactly the same results:\n```ts\nconst schema = z\n  .string()\n  .openapi('Schema', { description: 'Name of the user', example: 'Test' });\n\nconst schema2 = z\n  .string()\n  .meta({ id: 'Schema2', description: 'Name of the user', example: 'Test' });\n```\n\n> Note: This also means that you unless you are using some of our more complicated scenarios you could even generate a schema without using `extendZodWithOpenApi` in your codebase and only rely on `.meta` to provide additional metadata information and schema names (using the `id` property).\n\n#### Scenarios that require using `extendZodWithOpenApi` and `.openapi`\n1. When extending registered schemas that are both registered and want the extended one to use `anyOf` i.e:\n\n```ts\nconst schema = z.object({ name: z.string() }).openapi('Schema');\n\nconst schema2 = schema.extend({ age: z.number() }).openapi('Schema2'); // this one would have anyOf and a reference to the first one\n```\n2. Defining parameter metadata. So for example when doing:\n```ts\nregistry.registerPath({\n  // ...\n  request: {\n    query: z.object({\n      name: z.string().openapi({\n        description: 'Schema level description',\n        param: { description: 'Param level description' },\n      }),\n    }),\n  },\n});\n```\n\nthe result would be:\n```ts\n  \"parameters\": [\n      {\n        \"schema\": {\n          \"type\": \"string\",\n          \"description\": \"Schema level description\" // comes directly from description\n        },\n        \"required\": true,\n        \"description\": \"Param level description\", // comes from param.description\n        \"name\": \"name\",\n        \"in\": \"query\"\n      }\n  ],\n```\n\n#### Hiding schemas, fields and routes\n\nMarking something with `hidden: true` leaves it out of the generated document. It works\nthe same through `.meta({ hidden: true })` and `.openapi({ hidden: true })`, and it is\nalways on - there is no generator option to disable it.\n\n```ts\nconst User = z\n  .object({\n    id: z.string(),\n    internalToken: z.string().meta({ hidden: true }),\n  })\n  .openapi('User');\n\n// components.schemas.User ->\n// { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] }\n```\n\nThe following can be hidden:\n\n- **Object properties** - the key is dropped from both `properties` and `required`.\n- **Registered schemas** - no `components.schemas` entry is generated, and nothing\n  `$ref`s it.\n- **Route parameters and response headers** - the parameter/header is dropped. Hiding\n  the whole `query`/`params`/`headers`/`cookies` object drops all of its parameters.\n- **Whole routes and webhooks** - `registry.registerPath({ hidden: true, ... })` and\n  `registry.registerWebhook({ hidden: true, ... })`. If it was the only operation on\n  its path, the path itself is omitted too.\n- **Members of `z.union`, `z.discriminatedUnion` and `z.intersection`** - the member is\n  dropped from `anyOf`/`oneOf`/`allOf`, and from `discriminator.mapping`.\n\nThe `hidden` key itself is never emitted into the document.\n\nHiding works through `.optional()`, `.nullable()`, `.default()`, `.readonly()` and pipes,\nso it does not matter where in the chain you set it. It is deliberately **not** inherited\nthrough `.extend()` - hiding an internal base object while still publishing the objects\nextending it is the main reason to reach for this, so the child has to opt in itself.\n\n##### Where a hidden schema is inlined instead\n\nSome positions cannot simply lose their schema without producing an invalid document -\nan array element, a tuple item, a record value, a request body, a response `content`, or\na union that would otherwise be left with no members. In those, a hidden schema is\n**inlined** at the use site. It still never becomes a `components.schemas` entry, so no\n`$ref` points at it, but the document stays valid.\n\n```ts\nconst Secret = z.string().openapi('Secret', { hidden: true });\n\nz.object({ secrets: z.array(Secret) }).openapi('User');\n// -> properties.secrets = { type: 'array', items: { type: 'string' } }\n```\n\nTo drop it entirely, hide the property rather than the schema:\n\n```ts\nz.object({ secrets: z.array(Secret).meta({ hidden: true }) }).openapi('User');\n```\n\nBecause a hidden schema is inlined rather than referenced, a **recursive** schema cannot\nbe hidden - it has no finite inline form. Doing so throws a `RecursiveHiddenSchemaError`\nnaming the schema.\n\n### The basic idea\n\n```ts\nimport { extendZodWithOpenApi } from '@asteasolutions/zod-to-openapi';\nimport { z } from 'zod';\n\nextendZodWithOpenApi(z);\n\n// We can now use `.openapi()` to specify OpenAPI metadata\nz.string().openapi({ description: 'Some string' });\n```\n\n### Example 1: Calling the openapi-extension using tsx\n\n```\n//zod-extend.ts\n\nimport { extendZodWithOpenApi } from '@asteasolutions/zod-to-openapi';\nimport { z } from 'zod';\n\nextendZodWithOpenApi(z);\n\n// package.json\n\n  \"scripts\": {\n    \"start\": \"tsx --import ./zod-extend.ts ./index.ts\",\n```\n\n### Example 2 - require-syntax\n\n```\nimport { extendZodWithOpenApi } from '@asteasolutions/zod-to-openapi';\nimport { z } from 'zod';\n\nextendZodWithOpenApi(z);\n\nconst { startServer } = require('./server/start');\nstartServer();\n```\n\n\n### The Registry\n\nThe `OpenAPIRegistry` is a utility that can be used to collect definitions which would later be passed to a `OpenApiGeneratorV3` or `OpenApiGeneratorV31` instance.\n\n```ts\nimport {\n  OpenAPIRegistry,\n  OpenApiGeneratorV3,\n} from '@asteasolutions/zod-to-openapi';\n\nconst registry = new OpenAPIRegistry();\n\n// Register definitions here\n\nconst generator = new OpenApiGeneratorV3(registry.definitions);\n\nreturn generator.generateComponents();\n```\n\n### The Generator\n\nThere are three generators that can be used - `OpenApiGeneratorV3`, `OpenApiGeneratorV31` and `OpenApiGeneratorV32`. They share the same interface but internally generate schemas that correctly follow the data format for the specific Open API version - `3.0.x`, `3.1.x` or `3.2.x`. The Open API version affects how some components are generated.\n\n`OpenApiGeneratorV32` uses the same JSON Schema dialect as 3.1 (2020-12), so schemas are generated identically. It additionally accepts the document-structure fields that were added in 3.2 - see [OpenAPI 3.2 support](#openapi-32-support).\n\nFor example: changing the generator from `OpenApiGeneratorV3` to `OpenApiGeneratorV31` would result in following differences:\n\n```ts\nz.string().nullable().openapi({refId: 'name'});\n```\n\n```yml\n# 3.1.0\n# nullable is invalid in 3.1.0 but type arrays are invalid in previous versions\nname:\n  type:\n    - 'string'\n    - 'null'\n\n# 3.0.0\nname:\n  type: 'string'\n  nullable: true\n```\n\nBoth generators take a single argument in their constructors - an array of definitions - i.e results from the registry or regular zod schemas.\n\nThe public methods of both generators are as follows:\n\n`generateComponents` will generate only the `/components` section of an OpenAPI document (e.g. only `schemas` and `parameters`), not generating actual routes.\n\n`generateDocument` will generate the whole OpenAPI document.\n\n### Defining schemas\n\nAn OpenApi schema should be registered by using the `.openapi` method and providing a name:\n\n```ts\nconst UserSchema = z\n  .object({\n    id: z.string().openapi({ example: '1212121' }),\n    name: z.string().openapi({ example: 'John Doe' }),\n    age: z.number().openapi({ example: 42 }),\n  })\n  .openapi('User');\n\nconst generator = new OpenApiGeneratorV3([UserSchema]);\n```\n\nThe same can be achieved by using the `register` method of an `OpenAPIRegistry` instance. For more check the [\"Using schemas vs a registry\"](#using-schemas-vs-a-registry) section\n\n```ts\nconst UserSchema = registry.register(\n  'User',\n  z.object({\n    id: z.string().openapi({ example: '1212121' }),\n    name: z.string().openapi({ example: 'John Doe' }),\n    age: z.number().openapi({ example: 42 }),\n  })\n);\n\nconst generator = new OpenApiGeneratorV3(registry.definitions);\n```\n\nIf run now, `generator.generateComponents()` will generate the following structure:\n\n```yaml\ncomponents:\n  schemas:\n    User:\n      type: object\n      properties:\n        id:\n          type: string\n          example: '1212121'\n        name:\n          type: string\n          example: John Doe\n        age:\n          type: number\n          example: 42\n      required:\n        - id\n        - name\n        - age\n```\n\nThe key for the schema in the output is the first argument passed to `.openapi` method (or the `.register`) - in this case: `User`.\n\nNote that `generateComponents` does not return YAML but a JS object - you can then serialize that object into YAML or JSON depending on your use-case.\n\nThe resulting schema can then be referenced by using `$ref: #/components/schemas/User` in an existing OpenAPI JSON. This will be done automatically for Routes defined through the registry.\n\nNote by default a Zod object will result in `\"additionalProperties\": true` as per the Open API spec unless using `strict` or `catchall`, this is in contrast to normal Zod object usage where `zod.parse` is used.\n\n### Defining routes & webhooks\n\n#### Registering a path or webhook\n\nAn OpenAPI path is registered using the `registerPath` method of an `OpenAPIRegistry` instance. An OpenAPI webhook is registered using the `registerWebhook` method and takes the same parameters as `registerPath`.\n\n```ts\nregistry.registerPath({\n  method: 'get',\n  path: '/users/{id}',\n  description: 'Get user data by its id',\n  summary: 'Get a single user',\n  request: {\n    params: z.object({\n      id: z.string().openapi({ example: '1212121' }),\n    }),\n  },\n  responses: {\n    200: {\n      description: 'Object with user data.',\n      content: {\n        'application/json': {\n          schema: UserSchema,\n        },\n      },\n    },\n    204: {\n      description: 'No content - successful operation',\n    },\n  },\n});\n```\n\nThe YAML equivalent of the schema above would be:\n\n```yaml\n'/users/{id}':\n  get:\n    description: Get user data by its id\n    summary: Get a single user\n    parameters:\n      - in: path\n        name: id\n        schema:\n          type: string\n          example: '1212121'\n        required: true\n    responses:\n      '200':\n        description: Object with user data.\n        content:\n          application/json:\n            schema:\n              $ref: '#/components/schemas/User'\n      '204':\n        description: No content - successful operation\n```\n\nThe library specific properties for `registerPath` are `method`, `path`, `hidden`, `request` and `responses`. Everything else gets directly appended to the path definition.\n\n- `method` - One of `get`, `post`, `put`, `delete` and `patch`;\n- `path` - a string - being the path of the endpoint;\n- `hidden` - an optional boolean. When `true` the operation is left out of the generated document entirely - see [Hiding schemas, fields and routes](#hiding-schemas-fields-and-routes). The same applies to `registerWebhook`;\n- `request` - an optional object with optional `body`, `params`, `query` and `headers` keys,\n  - `query`, `params` - being instances of `ZodObject`\n  - `body` - an object with a `description` and a `content` record where:\n    - the key is a `mediaType` string like `application/json`\n    - and the value is an object with a `schema` of any `zod` type\n  - `headers` - instances of `ZodObject` or an array of any `zod` instances\n- `responses` - an object where the key is the status code or `default` and the value is an object with a `description` and a `content` record where:\n  - the key is a `mediaType` string like `application/json`\n  - and the value is an object with a `schema` of any `zod` type\n\n#### Defining route parameters\n\nIf you don't want to inline all parameter definitions, you can define them separately with `registerParameter` and then reference them:\n\n```ts\nconst UserIdParam = registry.registerParameter(\n  'UserId',\n  z.string().openapi({\n    param: {\n      name: 'id',\n      in: 'path',\n    },\n    example: '1212121',\n  })\n);\n\nregistry.registerPath({\n  ...\n  request: {\n    params: z.object({\n      id: UserIdParam\n    }),\n  },\n  responses: ...\n});\n```\n\nThe YAML equivalent would be:\n\n```yaml\ncomponents:\n  parameters:\n    UserId:\n      in: path\n      name: id\n      schema:\n        type: string\n        example: '1212121'\n      required: true\n\n'/users/{id}':\n  get:\n    ...\n    parameters:\n      - $ref: '#/components/parameters/UserId'\n    responses: ...\n```\n\nNote: In order to define properties that apply to the parameter itself, use the `param` property of `.openapi`. Any properties provided outside of `param` would be applied to the schema for this parameter.\n\n#### Generating the full document\n\nA full OpenAPI document can be generated using the `generateDocument` method of an `OpenApiGeneratorV3` or `OpenApiGeneratorV31` instance. It takes one argument - the document config. It may look something like this:\n\n```ts\nreturn generator.generateDocument({\n  openapi: '3.0.0',\n  info: {\n    version: '1.0.0',\n    title: 'My API',\n    description: 'This is the API',\n  },\n  servers: [{ url: 'v1' }],\n});\n```\n\n### OpenAPI 3.2 support\n\n`OpenApiGeneratorV32` generates `3.2.x` documents. The JSON Schema dialect is unchanged from 3.1, so schema generation is identical - the generator only adds the document-structure fields introduced in 3.2.\n\nThe main addition is `itemSchema` on a media type, used to describe each item of a sequential stream such as `text/event-stream`, `application/jsonl` or `application/json-seq`. A Zod schema is converted and registered exactly like `schema` (so it `$ref`s a component); a raw `SchemaObject`/`ReferenceObject` is passed through untouched.\n\n```ts\nconst Event = registry.register('Event', z.object({ message: z.string() }));\n\nregistry.registerPath({\n  method: 'get',\n  path: '/events',\n  responses: {\n    200: {\n      description: 'Event stream',\n      content: {\n        'text/event-stream': {\n          itemSchema: Event,\n        },\n      },\n    },\n  },\n});\n```\n\n```yml\n/events:\n  get:\n    responses:\n      '200':\n        description: Event stream\n        content:\n          text/event-stream:\n            itemSchema:\n              $ref: '#/components/schemas/Event'\n```\n\nOther 3.2 fields are accepted on the relevant configs: `summary` and an optional `description` on responses, the `query` HTTP method on routes, and `itemEncoding`/`prefixEncoding` on media types.\n\n### Defining custom components\n\nYou can define components that are not OpenAPI schemas, including security schemes, response headers and others. See [this test file](spec/custom-components.spec.ts) for examples.\n\n### A full example\n\nA full example code can be found [here](./example/index.ts). And the YAML representation of its result - [here](./example/openapi-docs.yml)\n\n### Using schemas vs a registry\n\nSchemas are automatically being registered when referenced. That means that if you have a schema like:\n\n```ts\nconst schema = z.object({ key: z.string().openapi('Test') }).openapi('Object');\n```\n\nyou'd have the following resulting structure:\n\n```yaml\ncomponents:\n  schemas:\n    Test:\n      type: 'string',\n    Object:\n      type: 'object',\n      properties:\n        key:\n          $ref: '#/components/schemas/Test'\n      required: ['key']\n```\n\nThis does not require any usages of an `OpenAPIRegistry` instance.\n\nHowever the same output can be achieved with the following code:\n\n```ts\nconst registry = new OpenAPIRegistry();\nconst schema = registry.register(\n  'Object',\n  z.object({ key: z.string().openapi('Test') })\n);\n```\n\nThe main benefit of the `.registry` method is that you can use the registry as a \"collection\" where you would put all such schemas.\n\nWith `.openapi`:\n\n```ts\n// file1.ts\nexport const Schema1 = ...\n\n// file2.ts\nexport const Schema2 = ...\n\nnew OpenApiGeneratorV3([Schema1, Schema2])\n```\n\nAdding a `NewSchema` into `file3.ts` would require you to pass that schema manually into the array of the generator constructor.\nNote: If a `NewSchema` is referenced by any other schemas or a route/webhook definition it would still appear in the resulting document.\n\nWith `registry.register`:\n\n```ts\n// registry.ts\nexport const registry = new OpenAPIRegistry()\n\n// file1.ts\nexport const Schema1 = registry.register(...)\n\n// file2.ts\nexport const Schema2 = registry.register(...)\n\nnew OpenApiGeneratorV3(registry.definitions)\n```\n\nAdding a `NewSchema` into `file3.ts` and using `registry.register` would NOT require you to do any changes to the generator constructor.\n\n#### Conclusion\n\nUsing an `OpenAPIRegistry` instance is mostly useful if you would want your resulting document to contain unreferenced schemas.\nThat can sometimes be useful - for example when you are slowly integrating an already existing documentation with `@asteasolutions/zod-to-openapi` and you are migrating small pieces at a time. Those pieces can then be referenced directly from an existing documentation.\n\n#### Adding it as part of your build\n\nIn a file inside your project you can have a file like so:\n\n```ts\nexport const registry = new OpenAPIRegistry();\n\nexport function generateOpenAPI() {\n  const config = {...}; // your config comes here\n\n  return new OpenApiGeneratorV3(registry.definitions).generateDocument(config);\n}\n```\n\nYou then use the exported `registry` object to register all schemas, parameters and routes where appropriate.\n\nThen you can create a script that executes the exported `generateOpenAPI` function. This script can be executed as a part of your build step so that it can write the result to some file like `openapi-docs.json`.\n\n### Generation options\n\nSchema generation can be altered in certain scenarios. This can be done by either:\n\n#### Passing a global configuration as second argument for the generator:\n\n```ts\nconst generator = new OpenApiGeneratorV3(registry.definitions, options);\n```\n\n\nThere list of currently supported global options is:\n```ts\nconst options = {\n  unionPreferredType: 'oneOf' | 'anyOf' // configures whether oneOf or anyOf is used when generating a schema for a zod union\n  sortComponents?: 'alphabetically'; // if sortComponents is passed with the value 'alphabetically' it would sort all schemas and parameters.\n                                     // If not - they would appear in the order they were defined\n}\n```\n\n\n#### Passing options for a one-off usage for a single schema:\n\n```ts\n// Note it is valid for metadata to be undefined in both of the below cases:\n\nschema.openapi('Schema', metadata, options); // when registering a schema or\nschema.openapi(metadata, options) // when simply adding some metadata to it\n```\n\nThere list of currently supported one-off options is:\n```ts\nconst options = {\n  unionPreferredType: 'oneOf' | 'anyOf' // configures whether oneOf or anyOf is used when generating a schema for a zod union\n}\n```\n\n> Note: `hidden` is deliberately not a generator option. It is set on the schema, parameter\n> or route itself and is always applied - see [Hiding schemas, fields and routes](#hiding-schemas-fields-and-routes).\n\n## Zod schema types\n\n### Supported types\n\nThe list of all supported types as of now is:\n\n- `ZodAny`\n- `ZodArray`\n- `ZodBigInt`\n- `ZodBoolean`\n- `ZodDate`\n- `ZodDefault`\n- `ZodPrefault`\n- `ZodDiscriminatedUnion`\n  - including `discriminator` mapping when all Zod objects in the union are registered with `.register()` or contain a `refId`.\n- `ZodEffects`\n- `ZodEnum`\n- `ZodIntersection`\n- `ZodLiteral`\n- `ZodNativeEnum`\n- `ZodNullable`\n- `ZodNumber`\n  - including `z.number().int()` being inferred as `type: 'integer'`\n- `ZodObject`\n  - including `.catchall` resulting in the respective `additionalProperties` schema\n  - also including `strict` resulting in the respective `additionalProperties` schema\n- `ZodOptional`\n- `ZodPipeline`\n- `ZodReadonly`\n- `ZodRecord`\n- `ZodString`\n  - adding `format` for:\n    - `.emoji()`\n    - `.cuid()`\n    - `.cuid2()`\n    - `.ulid()`\n    - `.ip()`\n    - `.cidrv4()` / `.cidrv6()`\n    - `.base64url()`\n    - `.date()`\n    - `.datetime()`\n    - `.time()`\n    - `.duration()`\n    - `.uuid()` / `.guid()`\n    - `.email()`\n    - `.url()`\n  - adding `pattern` for `.regex()` is also supported\n\n- `ZodTuple`\n- `ZodUnion`\n- `ZodUnknown`\n\nExtending an instance of `ZodObject` is also supported and results in an OpenApi definition with `allOf`\n\n### Unsupported types\n\nIn case you try to create an OpenAPI schema from a zod schema that is not one of the aforementioned types then you'd receive an `UnknownZodTypeError`.\n\nYou can still register such schemas on your own by providing a `type` via the `.openapi` method. In case you think that the desired behavior can be achieved automatically do not hesitate to reach out to us by describing your case via Github Issues.\n\n#### Known issues\n\n1. `z.nullable(schema)` [does not generate a $ref for underlying registered schemas](https://github.com/asteasolutions/zod-to-openapi/issues/141).\n  - This is an implementation limitation.\n  - However you can simply use `schema.nullable()` which has the exact same effect `zod` wise but it is also fully supported on our end.\n\n## Technologies\n\n- [Typescript](https://www.typescriptlang.org/)\n- [Zod 4.x](https://github.com/colinhacks/zod)\n- [OpenAPI 3.x TS](https://github.com/metadevpro/openapi3-ts)\n","readmeFilename":"README.md","_rev":"1-5ab8ca5251f4f7224db98541b035ee15"}