zod-nest 3.4.0 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -42,7 +42,7 @@ A short list of behavioural differences you'll hit on day one. Full migration ta
42
42
  - **Multi-status `@ZodResponse`** — stack the decorator per status code. In `nestjs-zod`, multi-status required mixing `@ZodSerializerDto` with hand-rolled `@ApiResponse({ status: ... })` calls.
43
43
  - **No internal `@HttpCode`** — `@ZodResponse` does **not** call `@HttpCode` under the hood. Status resolution precedence: `@ZodResponse({ status })` → `@HttpCode(...)` on the handler → method default (`POST → 201`, others → `200`). The caller controls `201` vs `200` vs `204` via standard NestJS decorators. `status` accepts numeric codes plus the OpenAPI 3.1 range keys (`'1XX'`…`'5XX'`) and `'default'` (sugar for the resolved method default).
44
44
  - **I/O suffix only when needed** — `<Id>Output` is only emitted when the input and output JSON Schemas actually differ. `nestjs-zod` always emitted `_Output`.
45
- - **OpenAPI 3.1 and 3.2** — no `3.0` fallback. Pick with `DocumentBuilder.setOpenAPIVersion('3.2.0')`; 3.2 is what makes `QUERY` routes conformant. `$ref`s emit to the final location; `cleanupOpenApiDoc` is unnecessary.
45
+ - **OpenAPI 3.1 and 3.2** — no `3.0` fallback. Pick with `DocumentBuilder.setOpenAPIVersion('3.2.0')`; 3.2 is what makes `QUERY` and WebDAV routes conformant, and what lets a streamed response say `itemSchema` instead of overstating the whole body. `$ref`s emit to the final location; `cleanupOpenApiDoc` is unnecessary.
46
46
  - **Validation-failure logging out of the box** — `nestjs-zod` has none.
47
47
  - **Customizable serialization exception** — both `ZodValidationPipe` and `ZodSerializerInterceptor` accept a factory. `nestjs-zod` only customized the input side.
48
48
  - **DTO discriminator** — `Symbol.for('zod-nest.dto')` (cross-realm safe), not `MyDto.isZodDto`.
@@ -484,7 +484,7 @@ A compact, link-out index. Type signatures and detailed semantics live in the co
484
484
 
485
485
  **Module** — [`docs/module-options.md`](docs/module-options.md) / [`docs/logging.md`](docs/logging.md)
486
486
 
487
- - `ZodNestModule.forRoot(options?)`, `ZodNestModuleOptions`, `DEFAULT_REDACT_KEYS`, `DEFAULT_MAX_LOGGED_VALUE_BYTES`, `ZOD_NEST_OPTIONS`
487
+ - `ZodNestModule.forRoot(options?)`, `ZodNestModuleOptions`, `DEFAULT_REDACT_KEYS`, `DEFAULT_MAX_LOGGED_VALUE_BYTES`, `DEFAULT_STREAM_CONTENT_TYPES`, `SEQUENTIAL_MEDIA_TYPES`, `ZOD_NEST_OPTIONS`
488
488
 
489
489
  **Schema engine** — single-schema mode and extension points
490
490
 
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkQ3SWJZBB_js = require('./chunk-Q3SWJZBB.js');
3
+ var chunkJ2MGUXBB_js = require('./chunk-J2MGUXBB.js');
4
4
  var chunk4LOFWANL_js = require('./chunk-4LOFWANL.js');
5
5
  var chunkEV5I5HGT_js = require('./chunk-EV5I5HGT.js');
6
6
  var zod = require('zod');
@@ -148,7 +148,7 @@ var ZOD_MULTIPART_METADATA_KEY = /* @__PURE__ */ Symbol.for("zod-nest.multipart"
148
148
  var MULTIPART_CONTENT_TYPE = "multipart/form-data";
149
149
  var schemaByShape = chunkEV5I5HGT_js.singleton("multipart-shape-schemas", () => /* @__PURE__ */ new WeakMap());
150
150
  var toSchema = /* @__PURE__ */ chunkEV5I5HGT_js.__name((body) => {
151
- if (chunkQ3SWJZBB_js.isZodSchema(body)) {
151
+ if (chunkJ2MGUXBB_js.isZodSchema(body)) {
152
152
  return body;
153
153
  }
154
154
  const cached = schemaByShape.get(body);
@@ -162,10 +162,10 @@ var toSchema = /* @__PURE__ */ chunkEV5I5HGT_js.__name((body) => {
162
162
  return schema;
163
163
  }, "toSchema");
164
164
  var toShape = /* @__PURE__ */ chunkEV5I5HGT_js.__name((body) => {
165
- if (!chunkQ3SWJZBB_js.isZodSchema(body)) {
165
+ if (!chunkJ2MGUXBB_js.isZodSchema(body)) {
166
166
  return body;
167
167
  }
168
- return chunkQ3SWJZBB_js.isZodObject(body) ? body.shape : void 0;
168
+ return chunkJ2MGUXBB_js.isZodObject(body) ? body.shape : void 0;
169
169
  }, "toShape");
170
170
  var partitionKeys = /* @__PURE__ */ chunkEV5I5HGT_js.__name((shape) => {
171
171
  const fileKeys = [];
@@ -184,13 +184,13 @@ var partitionKeys = /* @__PURE__ */ chunkEV5I5HGT_js.__name((shape) => {
184
184
  }, "partitionKeys");
185
185
  var resolveBody = /* @__PURE__ */ chunkEV5I5HGT_js.__name((schema, options, registry) => {
186
186
  if (options?.flatten === true) {
187
- const merged = chunkQ3SWJZBB_js.flattenObjectIntersection(schema, registry, "@ZodMultipart");
188
- return chunkQ3SWJZBB_js.resolveSchemaRef(merged, {
187
+ const merged = chunkJ2MGUXBB_js.flattenObjectIntersection(schema, registry, "@ZodMultipart");
188
+ return chunkJ2MGUXBB_js.resolveSchemaRef(merged, {
189
189
  registry,
190
190
  deferAnonInline: true
191
191
  }).ref;
192
192
  }
193
- return chunkQ3SWJZBB_js.resolveSchemaRef(schema, {
193
+ return chunkJ2MGUXBB_js.resolveSchemaRef(schema, {
194
194
  ...options?.id !== void 0 ? {
195
195
  id: options.id
196
196
  } : {},
@@ -200,7 +200,7 @@ var resolveBody = /* @__PURE__ */ chunkEV5I5HGT_js.__name((schema, options, regi
200
200
  }, "resolveBody");
201
201
  var createZodMultipart = /* @__PURE__ */ chunkEV5I5HGT_js.__name((defaultFilesIn) => {
202
202
  return (body, options) => {
203
- const registry = options?.registry ?? chunkQ3SWJZBB_js.defaultRegistry;
203
+ const registry = options?.registry ?? chunkJ2MGUXBB_js.defaultRegistry;
204
204
  const shape = toShape(body);
205
205
  const metadata = {
206
206
  shape,
@@ -263,7 +263,7 @@ var validate = /* @__PURE__ */ chunkEV5I5HGT_js.__name(async (schema, value, arg
263
263
  if (result.success) {
264
264
  return result.data;
265
265
  }
266
- throw new chunkQ3SWJZBB_js.ZodValidationException(result.error, {
266
+ throw new chunkJ2MGUXBB_js.ZodValidationException(result.error, {
267
267
  type: argType,
268
268
  metatype: void 0,
269
269
  data: void 0
@@ -306,5 +306,5 @@ exports.ZodUploadedFile = ZodUploadedFile;
306
306
  exports.ZodUploadedFiles = ZodUploadedFiles;
307
307
  exports.buildFileSchema = buildFileSchema;
308
308
  exports.createZodMultipart = createZodMultipart;
309
- //# sourceMappingURL=chunk-BYRNJLNK.js.map
310
- //# sourceMappingURL=chunk-BYRNJLNK.js.map
309
+ //# sourceMappingURL=chunk-3D4FM53F.js.map
310
+ //# sourceMappingURL=chunk-3D4FM53F.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/multipart/file-checks.ts","../src/multipart/file-marker.ts","../src/multipart/build-file-schema.ts","../src/multipart/metadata.ts","../src/multipart/zod-multipart.decorator.ts","../src/multipart/param-decorators.ts"],"names":["normalizeExtension","__name","extension","startsWith","toLowerCase","mimeTypeCheck","accessors","options","allowed","Set","mimeTypes","map","mimeType","payload","value","has","issues","push","code","input","message","join","extensionCheck","extensions","fileName","matched","some","endsWith","sizeCheck","readSize","size","maxSize","fileSchemas","singleton","WeakSet","isZodType","innerOf","def","innerType","element","undefined","unwrapOnce","schema","inner","_zod","markFileSchema","add","isFileSchema","resolveFragment","contentMediaType","singleMimeType","binary","description","length","collectChecks","params","checks","withId","fragment","id","overrideJSONSchema","meta","buildFileSchema","base","z","custom","predicate","checked","check","MultipartFilesIn","Request","Body","ZOD_MULTIPART_METADATA_KEY","Symbol","for","MULTIPART_CONTENT_TYPE","schemaByShape","WeakMap","toSchema","body","isZodSchema","cached","get","object","set","toShape","isZodObject","shape","partitionKeys","fileKeys","textKeys","key","Object","entries","resolveBody","registry","flatten","merged","flattenObjectIntersection","resolveSchemaRef","deferAnonInline","ref","createZodMultipart","defaultFilesIn","defaultRegistry","metadata","filesIn","target","propertyKey","descriptor","handler","TypeError","Reflect","defineMetadata","swaggerDescriptor","ApiConsumes","ApiBody","required","readMetadata","ctx","decorator","getMetadata","getHandler","isMultipartMetadata","Error","requireShape","schemaFor","name","keys","pick","wanted","picked","validate","argType","result","safeParseAsync","success","data","ZodValidationException","error","type","metatype","assertFilesOnRequest","resolveUploadedFile","request","switchToHttp","getRequest","file","resolveUploadedFiles","files","resolveMultipartBody","_data","ZodUploadedFile","createParamDecorator","ZodUploadedFiles","ZodMultipartBody"],"mappings":";;;;;;;;;;AA4BA,IAAMA,kBAAAA,mBAAqBC,uBAAA,CAAA,CAACC,SAAAA,KAC1BA,SAAAA,CAAUC,WAAW,GAAA,CAAA,GAAOD,SAAAA,CAAUE,WAAAA,EAAW,GAAK,CAAA,CAAA,EAAIF,SAAAA,CAAUE,WAAAA,EAAW,CAAA,CAAA,EADtD,oBAAA,CAAA;AAGpB,IAAMC,aAAAA,mBAAgBJ,uBAAA,CAAA,CAC3BK,SAAAA,EACAC,OAAAA,KAAAA;AAEA,EAAA,MAAMC,OAAAA,GAAU,IAAIC,GAAAA,CAAIF,OAAAA,CAAQG,SAAAA,CAAUC,GAAAA,CAAI,CAACC,QAAAA,KAAaA,QAAAA,CAASR,WAAAA,EAAW,CAAA,CAAA;AAChF,EAAA,OAAO,CAACS,OAAAA,KAAAA;AACN,IAAA,MAAMD,WAAWN,SAAAA,CAAUM,QAAAA,CAASC,OAAAA,CAAQC,KAAK,EAAEV,WAAAA,EAAW;AAC9D,IAAA,IAAII,OAAAA,CAAQO,GAAAA,CAAIH,QAAAA,CAAAA,EAAW;AACzB,MAAA;AACF,IAAA;AACAC,IAAAA,OAAAA,CAAQG,OAAOC,IAAAA,CAAK;MAClBC,IAAAA,EAAM,QAAA;AACNC,MAAAA,KAAAA,EAAON,OAAAA,CAAQC,KAAAA;AACfM,MAAAA,OAAAA,EAAS,mBAAmBb,OAAAA,CAAQG,SAAAA,CAAUW,KAAK,IAAA,CAAA,cAAmBT,QAAAA,CAAAA;KACxE,CAAA;AACF,EAAA,CAAA;AACF,CAAA,EAhB6B,eAAA,CAAA;AAkBtB,IAAMU,cAAAA,mBAAiBrB,uBAAA,CA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A,EAAsBA,QAAAA,CAAShB,QAAQ,CAAA,GACnEqC,SAAAA,CAAUrB,QAAAA,EAAUsB,MAAM,mBAAA,CAAA;AAChC,EAAA,OAAOK,QAAAA,CAAS1F,MAAAA,EAAQsG,OAAAA,CAAQK,KAAAA,EAAO,QAAA,CAAA;AACzC,CAAA,EAZoC,sBAAA,CAAA;AAc7B,IAAMC,oBAAAA,mBAAuBrJ,uBAAA,CAAA,OAClCsJ,KAAAA,EACAhC,GAAAA,KAAAA;AAEA,EAAA,MAAMd,QAAAA,GAAWa,YAAAA,CAAaC,GAAAA,EAAK,mBAAA,CAAA;AACnC,EAAA,MAAMhC,KAAAA,GAAQsC,YAAAA,CAAapB,QAAAA,EAAU,mBAAA,CAAA;AACrC,EAAA,MAAMuC,OAAAA,GAA8BzB,GAAAA,CAAI0B,YAAAA,EAAY,CAAGC,UAAAA,EAAU;AACjE,EAAA,MAAMlB,IAAAA,GAAOvB,SAASC,OAAAA,KAAYrC,gBAAAA,CAAiBE,OAAOqB,MAAAA,CAAOoC,IAAAA,CAAKzC,KAAAA,CAAAA,GAASkB,QAAAA,CAASf,QAAAA;AACxF,EAAA,OAAO0C,SAASH,IAAAA,CAAK1C,KAAAA,EAAOyC,IAAAA,CAAAA,EAAOgB,OAAAA,CAAQjE,MAAM,MAAA,CAAA;AACnD,CAAA,EAToC,sBAAA,CAAA;AAgB7B,IAAMyE,eAAAA,GAAkBC,4BAAqBV,mBAAAA;AAO7C,IAAMW,gBAAAA,GAAmBD,4BAAqBL,oBAAAA;AAO9C,IAAMO,gBAAAA,GAAmBF,4BAAqBH,oBAAAA","file":"chunk-BYRNJLNK.js","sourcesContent":["import type { z } from 'zod';\n\n/**\n * Reads the fields a check needs off a platform file object. Multer names the\n * client filename `originalname`, `@fastify/multipart` names it `filename`,\n * and only multer reports a `size` — so each platform supplies its own\n * accessors instead of the library inventing a common shape.\n */\nexport interface FileAccessors<TFile> {\n readonly mimeType: (file: TFile) => string;\n readonly fileName: (file: TFile) => string;\n readonly size?: (file: TFile) => number;\n}\n\nexport interface MimeTypeCheckOptions {\n readonly mimeTypes: readonly string[];\n}\n\nexport interface ExtensionCheckOptions {\n readonly extensions: readonly string[];\n}\n\nexport interface SizeCheckOptions {\n readonly maxSize: number;\n}\n\nexport type FileCheck<TFile> = (payload: z.core.ParsePayload<TFile>) => void;\n\nconst normalizeExtension = (extension: string): string =>\n extension.startsWith('.') ? extension.toLowerCase() : `.${extension.toLowerCase()}`;\n\nexport const mimeTypeCheck = <TFile>(\n accessors: FileAccessors<TFile>,\n options: MimeTypeCheckOptions,\n): FileCheck<TFile> => {\n const allowed = new Set(options.mimeTypes.map((mimeType) => mimeType.toLowerCase()));\n return (payload) => {\n const mimeType = accessors.mimeType(payload.value).toLowerCase();\n if (allowed.has(mimeType)) {\n return;\n }\n payload.issues.push({\n code: 'custom',\n input: payload.value,\n message: `Expected one of ${options.mimeTypes.join(', ')}, received ${mimeType}`,\n });\n };\n};\n\nexport const extensionCheck = <TFile>(\n accessors: FileAccessors<TFile>,\n options: ExtensionCheckOptions,\n): FileCheck<TFile> => {\n const allowed = new Set(options.extensions.map(normalizeExtension));\n return (payload) => {\n const fileName = accessors.fileName(payload.value).toLowerCase();\n const matched = [...allowed].some((extension) => fileName.endsWith(extension));\n if (matched) {\n return;\n }\n payload.issues.push({\n code: 'custom',\n input: payload.value,\n message: `Expected a file ending in ${options.extensions.map(normalizeExtension).join(', ')}, received ${fileName}`,\n });\n };\n};\n\nexport const sizeCheck = <TFile>(\n readSize: (file: TFile) => number,\n options: SizeCheckOptions,\n): FileCheck<TFile> => {\n return (payload) => {\n const size = readSize(payload.value);\n if (size <= options.maxSize) {\n return;\n }\n payload.issues.push({\n code: 'custom',\n input: payload.value,\n message: `Expected at most ${options.maxSize} bytes, received ${size}`,\n });\n };\n};\n","import type { z } from 'zod';\n\nimport { singleton } from '../schema/singleton.js';\n\n/**\n * Per-instance tag for schemas produced by the platform file factories.\n * WeakSet rather than `z.registry` because this is transient per-instance\n * annotation, not stable id-keyed metadata (CLAUDE.md).\n */\nconst fileSchemas = singleton('file-schemas', () => new WeakSet<z.ZodType>());\n\n// Wrapper defs expose their inner schema as Zod's internal `$ZodType`, which\n// `in` narrowing widens to `unknown`. One guard converts back to the public\n// type and rejects a non-wrapper in the same step.\nconst isZodType = (value: unknown): value is z.ZodType =>\n value !== null && typeof value === 'object' && '_zod' in value;\n\nconst innerOf = (def: object): unknown => {\n if ('innerType' in def) {\n return def.innerType;\n }\n if ('element' in def) {\n return def.element;\n }\n return undefined;\n};\n\nconst unwrapOnce = (schema: z.ZodType): z.ZodType | undefined => {\n const inner = innerOf(schema._zod.def);\n return isZodType(inner) ? inner : undefined;\n};\n\nexport const markFileSchema = <T extends z.ZodType>(schema: T): T => {\n fileSchemas.add(schema);\n return schema;\n};\n\n/**\n * True for a factory-produced file schema and for `.optional()` / `.array()`\n * wrappers around one — an optional or repeated file field is still a file\n * field for the request-vs-body split.\n */\nexport const isFileSchema = (schema: z.ZodType): boolean => {\n if (fileSchemas.has(schema)) {\n return true;\n }\n const inner = unwrapOnce(schema);\n if (inner === undefined) {\n return false;\n }\n return isFileSchema(inner);\n};\n","import { z } from 'zod';\n\nimport type { SchemaObject } from '../schema/openapi.types.js';\nimport type { FileAccessors, FileCheck } from './file-checks.js';\n\nimport { binary } from '../helpers/fragments.js';\nimport { overrideJSONSchema } from '../schema/custom-override.js';\nimport { extensionCheck, mimeTypeCheck, sizeCheck } from './file-checks.js';\nimport { markFileSchema } from './file-marker.js';\n\nexport interface BaseFileOptions {\n /**\n * Registry id for the schema. Set it to get a reusable\n * `components.schemas` entry that every field `$ref`s, instead of the\n * fragment being inlined at each use site. There is no `title` counterpart\n * — `overrideJSONSchema` replaces the emitted body and does not carry\n * `title` into it, so one would have no effect.\n */\n readonly id?: string;\n /** Allowed MIME types, matched case-insensitively against the client-supplied value. */\n readonly mimeTypes?: readonly string[];\n /** Allowed filename extensions, with or without a leading dot. */\n readonly extensions?: readonly string[];\n /** OpenAPI `description` for the emitted binary property. */\n readonly description?: string;\n /** Overrides the `contentMediaType` derived from a single-entry `mimeTypes`. */\n readonly contentMediaType?: string;\n}\n\nexport interface BuildFileSchemaParams<TFile> {\n readonly predicate: (value: unknown) => boolean;\n readonly accessors: FileAccessors<TFile>;\n readonly options: BaseFileOptions | undefined;\n /** Byte-size ceiling. Only platforms that report a size pass this. */\n readonly maxSize?: number;\n}\n\nconst resolveFragment = (options: BaseFileOptions | undefined): SchemaObject => {\n const contentMediaType = options?.contentMediaType ?? singleMimeType(options?.mimeTypes);\n return binary({\n ...(options?.description !== undefined ? { description: options.description } : {}),\n ...(contentMediaType !== undefined ? { contentMediaType } : {}),\n });\n};\n\nconst singleMimeType = (mimeTypes: readonly string[] | undefined): string | undefined => {\n if (mimeTypes === undefined || mimeTypes.length !== 1) {\n return undefined;\n }\n return mimeTypes[0];\n};\n\nconst collectChecks = <TFile>(params: BuildFileSchemaParams<TFile>): Array<FileCheck<TFile>> => {\n const { accessors, options, maxSize } = params;\n const checks: Array<FileCheck<TFile>> = [];\n if (options?.mimeTypes !== undefined) {\n checks.push(mimeTypeCheck(accessors, { mimeTypes: options.mimeTypes }));\n }\n if (options?.extensions !== undefined) {\n checks.push(extensionCheck(accessors, { extensions: options.extensions }));\n }\n if (maxSize !== undefined && accessors.size !== undefined) {\n checks.push(sizeCheck(accessors.size, { maxSize }));\n }\n return checks;\n};\n\nconst withId = <TFile>(\n schema: z.ZodType<TFile, TFile>,\n options: BaseFileOptions | undefined,\n fragment: SchemaObject,\n): z.ZodType<TFile, TFile> => {\n if (options?.id === undefined) {\n return schema;\n }\n return overrideJSONSchema(schema.meta({ id: options.id }), fragment);\n};\n\n/**\n * Assemble a platform file schema: duck-typing predicate, the option checks,\n * then `.meta({ id })` — re-registering the binary fragment after every step.\n *\n * Each registration is load-bearing. `overrideJSONSchema` keys its fragment on\n * the schema *instance*, and both `.check()` and `.meta()` clone. Emission\n * visits every instance in the chain, so a step left unregistered emits `{}`\n * — as a bare `{}` property in strict mode, or as an empty `components.schemas`\n * entry when the schema is named.\n */\nexport const buildFileSchema = <TFile>(\n params: BuildFileSchemaParams<TFile>,\n): z.ZodType<TFile, TFile> => {\n const fragment = resolveFragment(params.options);\n const base = overrideJSONSchema(z.custom<TFile>(params.predicate), fragment);\n const checks = collectChecks(params);\n const checked = checks.length === 0 ? base : overrideJSONSchema(base.check(...checks), fragment);\n return markFileSchema(withId(checked, params.options, fragment));\n};\n","import type { z } from 'zod';\n\n/**\n * Where the multipart parser puts uploaded files. Multer leaves them on the\n * request (`req.file` / `req.files`) with only text fields in `req.body`;\n * `@fastify/multipart` with `attachFieldsToBody: true` puts everything in\n * `req.body`.\n */\nexport const MultipartFilesIn = {\n Request: 'request',\n Body: 'body',\n} as const;\n\nexport type MultipartFilesIn = (typeof MultipartFilesIn)[keyof typeof MultipartFilesIn];\n\n/** Shape accepted by `@ZodMultipart` — one Zod schema per form field. */\nexport type MultipartShape = Readonly<Record<string, z.ZodType>>;\n\nexport interface MultipartMetadata {\n /**\n * Flat shape the param decorators validate against. `undefined` when the\n * body is a composite (`z.intersection` / `z.union`) with no single flat\n * shape to split — the document still emits, but `@ZodUploadedFile` and\n * friends have nothing to resolve and say so.\n */\n readonly shape: MultipartShape | undefined;\n readonly fileKeys: readonly string[];\n readonly textKeys: readonly string[];\n readonly filesIn: MultipartFilesIn;\n}\n\n/**\n * Metadata key for the shape declared by `@ZodMultipart`. `Symbol.for` so\n * consumers in other realms read the same registry (CLAUDE.md).\n */\nexport const ZOD_MULTIPART_METADATA_KEY = Symbol.for('zod-nest.multipart');\n","import { ApiBody, ApiConsumes } from '@nestjs/swagger';\nimport { z } from 'zod';\n\nimport type { ZodNestRegistry } from '../schema/registry.js';\nimport type { MultipartFilesIn, MultipartMetadata, MultipartShape } from './metadata.js';\n\nimport { flattenObjectIntersection } from '../decorators/internal/flatten-intersection.js';\nimport { isZodObject } from '../decorators/internal/zod-param-expand.js';\nimport { resolveSchemaRef } from '../decorators/internal/zod-schema-ref.js';\nimport { isZodSchema } from '../dto/predicates.js';\nimport { defaultRegistry } from '../schema/registry.js';\nimport { singleton } from '../schema/singleton.js';\nimport { isFileSchema } from './file-marker.js';\nimport { ZOD_MULTIPART_METADATA_KEY } from './metadata.js';\n\nexport const MULTIPART_CONTENT_TYPE = 'multipart/form-data';\n\n/**\n * Body declaration accepted by `@ZodMultipart`: a flat shape record, or any\n * Zod schema. A record is the common case; a schema covers named bodies\n * (`.meta({ id })` → `$ref`) and composites an object literal can't express.\n */\nexport type MultipartBody = MultipartShape | z.ZodType;\n\nexport interface ZodMultipartOptions {\n /**\n * Where the parser puts uploaded files. Defaults to the platform entry\n * point's convention — `'request'` from `zod-nest/express`, `'body'` from\n * `zod-nest/fastify`.\n */\n readonly filesIn?: MultipartFilesIn;\n /**\n * Forces this id, overriding any `.meta({ id })` on the schema. A named body\n * is emitted as a `$ref` to `components.schemas`, which keeps a stable name\n * for client generators — at the cost of Swagger UI's `try-it-out` form,\n * which doesn't follow `$ref` for `multipart/form-data`.\n */\n readonly id?: string;\n /**\n * Merge an intersection / union of `z.object` arms into one flat inline\n * object. Needed for composite bodies whose `try-it-out` form must render.\n * All merged properties become optional. See `@ZodBody`'s `flatten`.\n */\n readonly flatten?: boolean;\n /** Registry to register named descendants into. Defaults to `defaultRegistry`. */\n readonly registry?: ZodNestRegistry;\n /** OpenAPI `description` for the request body. */\n readonly description?: string;\n /** Whether the body is required. Defaults to `true`. */\n readonly required?: boolean;\n}\n\n// One `z.object` per shape record, so a shape hoisted across handlers (the\n// pattern docs/recipes/multipart-uploads.md recommends) resolves to a single\n// synthetic id rather than one per route.\nconst schemaByShape = singleton(\n 'multipart-shape-schemas',\n () => new WeakMap<MultipartShape, z.ZodType>(),\n);\n\nconst toSchema = (body: MultipartBody): z.ZodType => {\n if (isZodSchema(body)) {\n return body;\n }\n const cached = schemaByShape.get(body);\n if (cached !== undefined) {\n return cached;\n }\n const schema = z.object({ ...body });\n schemaByShape.set(body, schema);\n return schema;\n};\n\n/**\n * The flat shape the param decorators split on. A record is already flat and a\n * `z.object` exposes one; a composite has none, and the decorators report that\n * rather than guessing.\n */\nconst toShape = (body: MultipartBody): MultipartShape | undefined => {\n if (!isZodSchema(body)) {\n return body;\n }\n return isZodObject(body) ? body.shape : undefined;\n};\n\nconst partitionKeys = (\n shape: MultipartShape | undefined,\n): { fileKeys: string[]; textKeys: string[] } => {\n const fileKeys: string[] = [];\n const textKeys: string[] = [];\n for (const [key, schema] of Object.entries(shape ?? {})) {\n if (isFileSchema(schema)) {\n fileKeys.push(key);\n continue;\n }\n textKeys.push(key);\n }\n return { fileKeys, textKeys };\n};\n\n/**\n * Resolves the operation's body to a `$ref`. An anonymous one targets a\n * synthetic id that `applyZodNest` emits under the document's `strict` /\n * `override` and then inlines at the operation — Swagger UI's\n * `multipart/form-data` form generator doesn't follow `$ref`, so a referenced\n * body renders one stub field instead of file pickers. Naming the body (`id`\n * or `.meta({ id })`) keeps the `$ref` in the final document and opts into\n * that trade-off.\n */\nconst resolveBody = (\n schema: z.ZodType,\n options: ZodMultipartOptions | undefined,\n registry: ZodNestRegistry,\n): { readonly $ref: string } => {\n if (options?.flatten === true) {\n const merged = flattenObjectIntersection(schema, registry, '@ZodMultipart');\n return resolveSchemaRef(merged, { registry, deferAnonInline: true }).ref;\n }\n return resolveSchemaRef(schema, {\n ...(options?.id !== undefined ? { id: options.id } : {}),\n registry,\n deferAnonInline: true,\n }).ref;\n};\n\nexport const createZodMultipart = (defaultFilesIn: MultipartFilesIn) => {\n /**\n * Declares an endpoint's whole `multipart/form-data` body — file fields and\n * text fields together — as the single source of truth for both the OpenAPI\n * document and the multipart param decorators.\n */\n return (body: MultipartBody, options?: ZodMultipartOptions): MethodDecorator => {\n const registry = options?.registry ?? defaultRegistry;\n const shape = toShape(body);\n const metadata: MultipartMetadata = {\n shape,\n ...partitionKeys(shape),\n filesIn: options?.filesIn ?? defaultFilesIn,\n };\n const schema = resolveBody(toSchema(body), options, registry);\n\n return (target, propertyKey, descriptor) => {\n const handler = descriptor.value;\n if (typeof handler !== 'function') {\n throw new TypeError('[zod-nest] @ZodMultipart can only be applied to methods.');\n }\n Reflect.defineMetadata(ZOD_MULTIPART_METADATA_KEY, metadata, handler);\n\n // `TypedPropertyDescriptor<unknown>` matches what the swagger decorators\n // expect; `MethodDecorator`'s parameter is `TypedPropertyDescriptor<T>`\n // for the inferred return type, structurally compatible at runtime.\n const swaggerDescriptor = descriptor as TypedPropertyDescriptor<unknown>;\n ApiConsumes(MULTIPART_CONTENT_TYPE)(target, propertyKey, swaggerDescriptor);\n ApiBody({\n schema,\n ...(options?.description !== undefined ? { description: options.description } : {}),\n required: options?.required ?? true,\n })(target, propertyKey, swaggerDescriptor);\n };\n };\n};\n","import { createParamDecorator } from '@nestjs/common';\nimport { z } from 'zod';\n\nimport type { ExecutionContext } from '@nestjs/common';\nimport type { MultipartMetadata, MultipartShape } from './metadata.js';\n\nimport { ZodValidationException } from '../exceptions/validation.exception.js';\nimport { MultipartFilesIn, ZOD_MULTIPART_METADATA_KEY } from './metadata.js';\n\ntype ArgType = 'body' | 'custom';\n\nconst readMetadata = (ctx: ExecutionContext, decorator: string): MultipartMetadata => {\n const metadata: unknown = Reflect.getMetadata(ZOD_MULTIPART_METADATA_KEY, ctx.getHandler());\n if (!isMultipartMetadata(metadata)) {\n throw new Error(\n `[zod-nest] ${decorator} requires @ZodMultipart on the same handler — it reads the declared shape from there.`,\n );\n }\n return metadata;\n};\n\nconst isMultipartMetadata = (value: unknown): value is MultipartMetadata =>\n value !== null && typeof value === 'object' && 'shape' in value && 'filesIn' in value;\n\n/**\n * The declared shape, or a pointed error when the body is a composite. An\n * intersection / union has no single flat shape to split, so there is nothing\n * for these decorators to resolve a field against.\n */\nconst requireShape = (metadata: MultipartMetadata, decorator: string): MultipartShape => {\n if (metadata.shape !== undefined) {\n return metadata.shape;\n }\n throw new Error(\n `[zod-nest] ${decorator} needs a flat body shape, but @ZodMultipart was given a composite schema (an intersection or union). Validate it with @Body(new ZodValidationPipe(schema)) instead.`,\n );\n};\n\nconst schemaFor = (metadata: MultipartMetadata, name: string, decorator: string): z.ZodType => {\n const shape = requireShape(metadata, decorator);\n const schema = shape[name];\n if (schema === undefined) {\n throw new Error(\n `[zod-nest] ${decorator}('${name}') has no matching property in the @ZodMultipart shape. Declared: ${Object.keys(shape).join(', ')}.`,\n );\n }\n return schema;\n};\n\nconst pick = (shape: MultipartShape, keys: readonly string[]): z.ZodType => {\n const wanted = new Set(keys);\n const picked: Record<string, z.ZodType> = {};\n for (const [key, schema] of Object.entries(shape)) {\n if (wanted.has(key)) {\n picked[key] = schema;\n }\n }\n return z.object(picked);\n};\n\nconst validate = async (schema: z.ZodType, value: unknown, argType: ArgType): Promise<unknown> => {\n const result = await schema.safeParseAsync(value);\n if (result.success) {\n return result.data;\n }\n throw new ZodValidationException(result.error, {\n type: argType,\n metatype: undefined,\n data: undefined,\n });\n};\n\nconst assertFilesOnRequest = (metadata: MultipartMetadata, decorator: string): void => {\n if (metadata.filesIn === MultipartFilesIn.Request) {\n return;\n }\n throw new Error(\n `[zod-nest] ${decorator} is unavailable under filesIn: 'body' — the parser puts files in the request body, so read them with @ZodMultipartBody().`,\n );\n};\n\nexport const resolveUploadedFile = async (\n name: string,\n ctx: ExecutionContext,\n): Promise<unknown> => {\n const metadata = readMetadata(ctx, '@ZodUploadedFile');\n assertFilesOnRequest(metadata, '@ZodUploadedFile');\n const request: { file?: unknown } = ctx.switchToHttp().getRequest();\n return validate(schemaFor(metadata, name, '@ZodUploadedFile'), request.file, 'custom');\n};\n\nexport const resolveUploadedFiles = async (\n name: string | undefined,\n ctx: ExecutionContext,\n): Promise<unknown> => {\n const metadata = readMetadata(ctx, '@ZodUploadedFiles');\n assertFilesOnRequest(metadata, '@ZodUploadedFiles');\n const request: { files?: unknown } = ctx.switchToHttp().getRequest();\n const schema =\n name === undefined\n ? pick(requireShape(metadata, '@ZodUploadedFiles'), metadata.fileKeys)\n : schemaFor(metadata, name, '@ZodUploadedFiles');\n return validate(schema, request.files, 'custom');\n};\n\nexport const resolveMultipartBody = async (\n _data: unknown,\n ctx: ExecutionContext,\n): Promise<unknown> => {\n const metadata = readMetadata(ctx, '@ZodMultipartBody');\n const shape = requireShape(metadata, '@ZodMultipartBody');\n const request: { body?: unknown } = ctx.switchToHttp().getRequest();\n const keys = metadata.filesIn === MultipartFilesIn.Body ? Object.keys(shape) : metadata.textKeys;\n return validate(pick(shape, keys), request.body, 'body');\n};\n\n/**\n * Validates `req.file` against the named property of the `@ZodMultipart`\n * shape. The name selects a schema; it never searches the request. Match it\n * to your `FileInterceptor('<name>')` field name, as with plain Nest.\n */\nexport const ZodUploadedFile = createParamDecorator(resolveUploadedFile);\n\n/**\n * Validates `req.files` against the named property of the `@ZodMultipart`\n * shape, or against an object of every declared file property when called\n * with no name — the record shape `FileFieldsInterceptor` produces.\n */\nexport const ZodUploadedFiles = createParamDecorator(resolveUploadedFiles);\n\n/**\n * Validates `req.body` against the `@ZodMultipart` shape — the text fields\n * only under `filesIn: 'request'` (multer keeps files off the body), the\n * whole shape under `filesIn: 'body'`.\n */\nexport const ZodMultipartBody = createParamDecorator(resolveMultipartBody);\n"]}
1
+ {"version":3,"sources":["../src/multipart/file-checks.ts","../src/multipart/file-marker.ts","../src/multipart/build-file-schema.ts","../src/multipart/metadata.ts","../src/multipart/zod-multipart.decorator.ts","../src/multipart/param-decorators.ts"],"names":["normalizeExtension","__name","extension","startsWith","toLowerCase","mimeTypeCheck","accessors","options","allowed","Set","mimeTypes","map","mimeType","payload","value","has","issues","push","code","input","message","join","extensionCheck","extensions","fileName","matched","some","endsWith","sizeCheck","readSize","size","maxSize","fileSchemas","singleton","WeakSet","isZodType","innerOf","def","innerType","element","undefined","unwrapOnce","schema","inner","_zod","markFileSchema","add","isFileSchema","resolveFragment","contentMediaType","singleMimeType","binary","description","length","collectChecks","params","checks","withId","fragment","id","overrideJSONSchema","meta","buildFileSchema","base","z","custom","predicate","checked","check","MultipartFilesIn","Request","Body","ZOD_MULTIPART_METADATA_KEY","Symbol","for","MULTIPART_CONTENT_TYPE","schemaByShape","WeakMap","toSchema","body","isZodSchema","cached","get","object","set","toShape","isZodObject","shape","partitionKeys","fileKeys","textKeys","key","Object","entries","resolveBody","registry","flatten","merged","flattenObjectIntersection","resolveSchemaRef","deferAnonInline","ref","createZodMultipart","defaultFilesIn","defaultRegistry","metadata","filesIn","target","propertyKey","descriptor","handler","TypeError","Reflect","defineMetadata","swaggerDescriptor","ApiConsumes","ApiBody","required","readMetadata","ctx","decorator","getMetadata","getHandler","isMultipartMetadata","Error","requireShape","schemaFor","name","keys","pick","wanted","picked","validate","argType","result","safeParseAsync","success","data","ZodValidationException","error","type","metatype","assertFilesOnRequest","resolveUploadedFile","request","switchToHttp","getRequest","file","resolveUploadedFiles","files","resolveMultipartBody","_data","ZodUploadedFile","createParamDecorator","ZodUploadedFiles","ZodMultipartBody"],"mappings":";;;;;;;;;;AA4BA,IAAMA,kBAAAA,mBAAqBC,uBAAA,CAAA,CAACC,SAAAA,KAC1BA,SAAAA,CAAUC,WAAW,GAAA,CAAA,GAAOD,SAAAA,CAAUE,WAAAA,EAAW,GAAK,CAAA,CAAA,EAAIF,SAAAA,CAAUE,WAAAA,EAAW,CAAA,CAAA,EADtD,oBAAA,CAAA;AAGpB,IAAMC,aAAAA,mBAAgBJ,uBAAA,CAAA,CAC3BK,SAAAA,EACAC,OAAAA,KAAAA;AAEA,EAAA,MAAMC,OAAAA,GAAU,IAAIC,GAAAA,CAAIF,OAAAA,CAAQG,SAAAA,CAAUC,GAAAA,CAAI,CAACC,QAAAA,KAAaA,QAAAA,CAASR,WAAAA,EAAW,CAAA,CAAA;AAChF,EAAA,OAAO,CAACS,OAAAA,KAAAA;AACN,IAAA,MAAMD,WAAWN,SAAAA,CAAUM,QAAAA,CAASC,OAAAA,CAAQC,KAAK,EAAEV,WAAAA,EAAW;AAC9D,IAAA,IAAII,OAAAA,CAAQO,GAAAA,CAAIH,QAAAA,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eAAAA,GAAkBC,4BAAqBV,mBAAAA;AAO7C,IAAMW,gBAAAA,GAAmBD,4BAAqBL,oBAAAA;AAO9C,IAAMO,gBAAAA,GAAmBF,4BAAqBH,oBAAAA","file":"chunk-3D4FM53F.js","sourcesContent":["import type { z } from 'zod';\n\n/**\n * Reads the fields a check needs off a platform file object. Multer names the\n * client filename `originalname`, `@fastify/multipart` names it `filename`,\n * and only multer reports a `size` — so each platform supplies its own\n * accessors instead of the library inventing a common shape.\n */\nexport interface FileAccessors<TFile> {\n readonly mimeType: (file: TFile) => string;\n readonly fileName: (file: TFile) => string;\n readonly size?: (file: TFile) => number;\n}\n\nexport interface MimeTypeCheckOptions {\n readonly mimeTypes: readonly string[];\n}\n\nexport interface ExtensionCheckOptions {\n readonly extensions: readonly string[];\n}\n\nexport interface SizeCheckOptions {\n readonly maxSize: number;\n}\n\nexport type FileCheck<TFile> = (payload: z.core.ParsePayload<TFile>) => void;\n\nconst normalizeExtension = (extension: string): string =>\n extension.startsWith('.') ? extension.toLowerCase() : `.${extension.toLowerCase()}`;\n\nexport const mimeTypeCheck = <TFile>(\n accessors: FileAccessors<TFile>,\n options: MimeTypeCheckOptions,\n): FileCheck<TFile> => {\n const allowed = new Set(options.mimeTypes.map((mimeType) => mimeType.toLowerCase()));\n return (payload) => {\n const mimeType = accessors.mimeType(payload.value).toLowerCase();\n if (allowed.has(mimeType)) {\n return;\n }\n payload.issues.push({\n code: 'custom',\n input: payload.value,\n message: `Expected one of ${options.mimeTypes.join(', ')}, received ${mimeType}`,\n });\n };\n};\n\nexport const extensionCheck = <TFile>(\n accessors: FileAccessors<TFile>,\n options: ExtensionCheckOptions,\n): FileCheck<TFile> => {\n const allowed = new Set(options.extensions.map(normalizeExtension));\n return (payload) => {\n const fileName = accessors.fileName(payload.value).toLowerCase();\n const matched = [...allowed].some((extension) => fileName.endsWith(extension));\n if (matched) {\n return;\n }\n payload.issues.push({\n code: 'custom',\n input: payload.value,\n message: `Expected a file ending in ${options.extensions.map(normalizeExtension).join(', ')}, received ${fileName}`,\n });\n };\n};\n\nexport const sizeCheck = <TFile>(\n readSize: (file: TFile) => number,\n options: SizeCheckOptions,\n): FileCheck<TFile> => {\n return (payload) => {\n const size = readSize(payload.value);\n if (size <= options.maxSize) {\n return;\n }\n payload.issues.push({\n code: 'custom',\n input: payload.value,\n message: `Expected at most ${options.maxSize} bytes, received ${size}`,\n });\n };\n};\n","import type { z } from 'zod';\n\nimport { singleton } from '../schema/singleton.js';\n\n/**\n * Per-instance tag for schemas produced by the platform file factories.\n * WeakSet rather than `z.registry` because this is transient per-instance\n * annotation, not stable id-keyed metadata (CLAUDE.md).\n */\nconst fileSchemas = singleton('file-schemas', () => new WeakSet<z.ZodType>());\n\n// Wrapper defs expose their inner schema as Zod's internal `$ZodType`, which\n// `in` narrowing widens to `unknown`. One guard converts back to the public\n// type and rejects a non-wrapper in the same step.\nconst isZodType = (value: unknown): value is z.ZodType =>\n value !== null && typeof value === 'object' && '_zod' in value;\n\nconst innerOf = (def: object): unknown => {\n if ('innerType' in def) {\n return def.innerType;\n }\n if ('element' in def) {\n return def.element;\n }\n return undefined;\n};\n\nconst unwrapOnce = (schema: z.ZodType): z.ZodType | undefined => {\n const inner = innerOf(schema._zod.def);\n return isZodType(inner) ? inner : undefined;\n};\n\nexport const markFileSchema = <T extends z.ZodType>(schema: T): T => {\n fileSchemas.add(schema);\n return schema;\n};\n\n/**\n * True for a factory-produced file schema and for `.optional()` / `.array()`\n * wrappers around one — an optional or repeated file field is still a file\n * field for the request-vs-body split.\n */\nexport const isFileSchema = (schema: z.ZodType): boolean => {\n if (fileSchemas.has(schema)) {\n return true;\n }\n const inner = unwrapOnce(schema);\n if (inner === undefined) {\n return false;\n }\n return isFileSchema(inner);\n};\n","import { z } from 'zod';\n\nimport type { SchemaObject } from '../schema/openapi.types.js';\nimport type { FileAccessors, FileCheck } from './file-checks.js';\n\nimport { binary } from '../helpers/fragments.js';\nimport { overrideJSONSchema } from '../schema/custom-override.js';\nimport { extensionCheck, mimeTypeCheck, sizeCheck } from './file-checks.js';\nimport { markFileSchema } from './file-marker.js';\n\nexport interface BaseFileOptions {\n /**\n * Registry id for the schema. Set it to get a reusable\n * `components.schemas` entry that every field `$ref`s, instead of the\n * fragment being inlined at each use site. There is no `title` counterpart\n * — `overrideJSONSchema` replaces the emitted body and does not carry\n * `title` into it, so one would have no effect.\n */\n readonly id?: string;\n /** Allowed MIME types, matched case-insensitively against the client-supplied value. */\n readonly mimeTypes?: readonly string[];\n /** Allowed filename extensions, with or without a leading dot. */\n readonly extensions?: readonly string[];\n /** OpenAPI `description` for the emitted binary property. */\n readonly description?: string;\n /** Overrides the `contentMediaType` derived from a single-entry `mimeTypes`. */\n readonly contentMediaType?: string;\n}\n\nexport interface BuildFileSchemaParams<TFile> {\n readonly predicate: (value: unknown) => boolean;\n readonly accessors: FileAccessors<TFile>;\n readonly options: BaseFileOptions | undefined;\n /** Byte-size ceiling. Only platforms that report a size pass this. */\n readonly maxSize?: number;\n}\n\nconst resolveFragment = (options: BaseFileOptions | undefined): SchemaObject => {\n const contentMediaType = options?.contentMediaType ?? singleMimeType(options?.mimeTypes);\n return binary({\n ...(options?.description !== undefined ? { description: options.description } : {}),\n ...(contentMediaType !== undefined ? { contentMediaType } : {}),\n });\n};\n\nconst singleMimeType = (mimeTypes: readonly string[] | undefined): string | undefined => {\n if (mimeTypes === undefined || mimeTypes.length !== 1) {\n return undefined;\n }\n return mimeTypes[0];\n};\n\nconst collectChecks = <TFile>(params: BuildFileSchemaParams<TFile>): Array<FileCheck<TFile>> => {\n const { accessors, options, maxSize } = params;\n const checks: Array<FileCheck<TFile>> = [];\n if (options?.mimeTypes !== undefined) {\n checks.push(mimeTypeCheck(accessors, { mimeTypes: options.mimeTypes }));\n }\n if (options?.extensions !== undefined) {\n checks.push(extensionCheck(accessors, { extensions: options.extensions }));\n }\n if (maxSize !== undefined && accessors.size !== undefined) {\n checks.push(sizeCheck(accessors.size, { maxSize }));\n }\n return checks;\n};\n\nconst withId = <TFile>(\n schema: z.ZodType<TFile, TFile>,\n options: BaseFileOptions | undefined,\n fragment: SchemaObject,\n): z.ZodType<TFile, TFile> => {\n if (options?.id === undefined) {\n return schema;\n }\n return overrideJSONSchema(schema.meta({ id: options.id }), fragment);\n};\n\n/**\n * Assemble a platform file schema: duck-typing predicate, the option checks,\n * then `.meta({ id })` — re-registering the binary fragment after every step.\n *\n * Each registration is load-bearing. `overrideJSONSchema` keys its fragment on\n * the schema *instance*, and both `.check()` and `.meta()` clone. Emission\n * visits every instance in the chain, so a step left unregistered emits `{}`\n * — as a bare `{}` property in strict mode, or as an empty `components.schemas`\n * entry when the schema is named.\n */\nexport const buildFileSchema = <TFile>(\n params: BuildFileSchemaParams<TFile>,\n): z.ZodType<TFile, TFile> => {\n const fragment = resolveFragment(params.options);\n const base = overrideJSONSchema(z.custom<TFile>(params.predicate), fragment);\n const checks = collectChecks(params);\n const checked = checks.length === 0 ? base : overrideJSONSchema(base.check(...checks), fragment);\n return markFileSchema(withId(checked, params.options, fragment));\n};\n","import type { z } from 'zod';\n\n/**\n * Where the multipart parser puts uploaded files. Multer leaves them on the\n * request (`req.file` / `req.files`) with only text fields in `req.body`;\n * `@fastify/multipart` with `attachFieldsToBody: true` puts everything in\n * `req.body`.\n */\nexport const MultipartFilesIn = {\n Request: 'request',\n Body: 'body',\n} as const;\n\nexport type MultipartFilesIn = (typeof MultipartFilesIn)[keyof typeof MultipartFilesIn];\n\n/** Shape accepted by `@ZodMultipart` — one Zod schema per form field. */\nexport type MultipartShape = Readonly<Record<string, z.ZodType>>;\n\nexport interface MultipartMetadata {\n /**\n * Flat shape the param decorators validate against. `undefined` when the\n * body is a composite (`z.intersection` / `z.union`) with no single flat\n * shape to split — the document still emits, but `@ZodUploadedFile` and\n * friends have nothing to resolve and say so.\n */\n readonly shape: MultipartShape | undefined;\n readonly fileKeys: readonly string[];\n readonly textKeys: readonly string[];\n readonly filesIn: MultipartFilesIn;\n}\n\n/**\n * Metadata key for the shape declared by `@ZodMultipart`. `Symbol.for` so\n * consumers in other realms read the same registry (CLAUDE.md).\n */\nexport const ZOD_MULTIPART_METADATA_KEY = Symbol.for('zod-nest.multipart');\n","import { ApiBody, ApiConsumes } from '@nestjs/swagger';\nimport { z } from 'zod';\n\nimport type { ZodNestRegistry } from '../schema/registry.js';\nimport type { MultipartFilesIn, MultipartMetadata, MultipartShape } from './metadata.js';\n\nimport { flattenObjectIntersection } from '../decorators/internal/flatten-intersection.js';\nimport { isZodObject } from '../decorators/internal/zod-param-expand.js';\nimport { resolveSchemaRef } from '../decorators/internal/zod-schema-ref.js';\nimport { isZodSchema } from '../dto/predicates.js';\nimport { defaultRegistry } from '../schema/registry.js';\nimport { singleton } from '../schema/singleton.js';\nimport { isFileSchema } from './file-marker.js';\nimport { ZOD_MULTIPART_METADATA_KEY } from './metadata.js';\n\nexport const MULTIPART_CONTENT_TYPE = 'multipart/form-data';\n\n/**\n * Body declaration accepted by `@ZodMultipart`: a flat shape record, or any\n * Zod schema. A record is the common case; a schema covers named bodies\n * (`.meta({ id })` → `$ref`) and composites an object literal can't express.\n */\nexport type MultipartBody = MultipartShape | z.ZodType;\n\nexport interface ZodMultipartOptions {\n /**\n * Where the parser puts uploaded files. Defaults to the platform entry\n * point's convention — `'request'` from `zod-nest/express`, `'body'` from\n * `zod-nest/fastify`.\n */\n readonly filesIn?: MultipartFilesIn;\n /**\n * Forces this id, overriding any `.meta({ id })` on the schema. A named body\n * is emitted as a `$ref` to `components.schemas`, which keeps a stable name\n * for client generators — at the cost of Swagger UI's `try-it-out` form,\n * which doesn't follow `$ref` for `multipart/form-data`.\n */\n readonly id?: string;\n /**\n * Merge an intersection / union of `z.object` arms into one flat inline\n * object. Needed for composite bodies whose `try-it-out` form must render.\n * All merged properties become optional. See `@ZodBody`'s `flatten`.\n */\n readonly flatten?: boolean;\n /** Registry to register named descendants into. Defaults to `defaultRegistry`. */\n readonly registry?: ZodNestRegistry;\n /** OpenAPI `description` for the request body. */\n readonly description?: string;\n /** Whether the body is required. Defaults to `true`. */\n readonly required?: boolean;\n}\n\n// One `z.object` per shape record, so a shape hoisted across handlers (the\n// pattern docs/recipes/multipart-uploads.md recommends) resolves to a single\n// synthetic id rather than one per route.\nconst schemaByShape = singleton(\n 'multipart-shape-schemas',\n () => new WeakMap<MultipartShape, z.ZodType>(),\n);\n\nconst toSchema = (body: MultipartBody): z.ZodType => {\n if (isZodSchema(body)) {\n return body;\n }\n const cached = schemaByShape.get(body);\n if (cached !== undefined) {\n return cached;\n }\n const schema = z.object({ ...body });\n schemaByShape.set(body, schema);\n return schema;\n};\n\n/**\n * The flat shape the param decorators split on. A record is already flat and a\n * `z.object` exposes one; a composite has none, and the decorators report that\n * rather than guessing.\n */\nconst toShape = (body: MultipartBody): MultipartShape | undefined => {\n if (!isZodSchema(body)) {\n return body;\n }\n return isZodObject(body) ? body.shape : undefined;\n};\n\nconst partitionKeys = (\n shape: MultipartShape | undefined,\n): { fileKeys: string[]; textKeys: string[] } => {\n const fileKeys: string[] = [];\n const textKeys: string[] = [];\n for (const [key, schema] of Object.entries(shape ?? {})) {\n if (isFileSchema(schema)) {\n fileKeys.push(key);\n continue;\n }\n textKeys.push(key);\n }\n return { fileKeys, textKeys };\n};\n\n/**\n * Resolves the operation's body to a `$ref`. An anonymous one targets a\n * synthetic id that `applyZodNest` emits under the document's `strict` /\n * `override` and then inlines at the operation — Swagger UI's\n * `multipart/form-data` form generator doesn't follow `$ref`, so a referenced\n * body renders one stub field instead of file pickers. Naming the body (`id`\n * or `.meta({ id })`) keeps the `$ref` in the final document and opts into\n * that trade-off.\n */\nconst resolveBody = (\n schema: z.ZodType,\n options: ZodMultipartOptions | undefined,\n registry: ZodNestRegistry,\n): { readonly $ref: string } => {\n if (options?.flatten === true) {\n const merged = flattenObjectIntersection(schema, registry, '@ZodMultipart');\n return resolveSchemaRef(merged, { registry, deferAnonInline: true }).ref;\n }\n return resolveSchemaRef(schema, {\n ...(options?.id !== undefined ? { id: options.id } : {}),\n registry,\n deferAnonInline: true,\n }).ref;\n};\n\nexport const createZodMultipart = (defaultFilesIn: MultipartFilesIn) => {\n /**\n * Declares an endpoint's whole `multipart/form-data` body — file fields and\n * text fields together — as the single source of truth for both the OpenAPI\n * document and the multipart param decorators.\n */\n return (body: MultipartBody, options?: ZodMultipartOptions): MethodDecorator => {\n const registry = options?.registry ?? defaultRegistry;\n const shape = toShape(body);\n const metadata: MultipartMetadata = {\n shape,\n ...partitionKeys(shape),\n filesIn: options?.filesIn ?? defaultFilesIn,\n };\n const schema = resolveBody(toSchema(body), options, registry);\n\n return (target, propertyKey, descriptor) => {\n const handler = descriptor.value;\n if (typeof handler !== 'function') {\n throw new TypeError('[zod-nest] @ZodMultipart can only be applied to methods.');\n }\n Reflect.defineMetadata(ZOD_MULTIPART_METADATA_KEY, metadata, handler);\n\n // `TypedPropertyDescriptor<unknown>` matches what the swagger decorators\n // expect; `MethodDecorator`'s parameter is `TypedPropertyDescriptor<T>`\n // for the inferred return type, structurally compatible at runtime.\n const swaggerDescriptor = descriptor as TypedPropertyDescriptor<unknown>;\n ApiConsumes(MULTIPART_CONTENT_TYPE)(target, propertyKey, swaggerDescriptor);\n ApiBody({\n schema,\n ...(options?.description !== undefined ? { description: options.description } : {}),\n required: options?.required ?? true,\n })(target, propertyKey, swaggerDescriptor);\n };\n };\n};\n","import { createParamDecorator } from '@nestjs/common';\nimport { z } from 'zod';\n\nimport type { ExecutionContext } from '@nestjs/common';\nimport type { MultipartMetadata, MultipartShape } from './metadata.js';\n\nimport { ZodValidationException } from '../exceptions/validation.exception.js';\nimport { MultipartFilesIn, ZOD_MULTIPART_METADATA_KEY } from './metadata.js';\n\ntype ArgType = 'body' | 'custom';\n\nconst readMetadata = (ctx: ExecutionContext, decorator: string): MultipartMetadata => {\n const metadata: unknown = Reflect.getMetadata(ZOD_MULTIPART_METADATA_KEY, ctx.getHandler());\n if (!isMultipartMetadata(metadata)) {\n throw new Error(\n `[zod-nest] ${decorator} requires @ZodMultipart on the same handler — it reads the declared shape from there.`,\n );\n }\n return metadata;\n};\n\nconst isMultipartMetadata = (value: unknown): value is MultipartMetadata =>\n value !== null && typeof value === 'object' && 'shape' in value && 'filesIn' in value;\n\n/**\n * The declared shape, or a pointed error when the body is a composite. An\n * intersection / union has no single flat shape to split, so there is nothing\n * for these decorators to resolve a field against.\n */\nconst requireShape = (metadata: MultipartMetadata, decorator: string): MultipartShape => {\n if (metadata.shape !== undefined) {\n return metadata.shape;\n }\n throw new Error(\n `[zod-nest] ${decorator} needs a flat body shape, but @ZodMultipart was given a composite schema (an intersection or union). Validate it with @Body(new ZodValidationPipe(schema)) instead.`,\n );\n};\n\nconst schemaFor = (metadata: MultipartMetadata, name: string, decorator: string): z.ZodType => {\n const shape = requireShape(metadata, decorator);\n const schema = shape[name];\n if (schema === undefined) {\n throw new Error(\n `[zod-nest] ${decorator}('${name}') has no matching property in the @ZodMultipart shape. Declared: ${Object.keys(shape).join(', ')}.`,\n );\n }\n return schema;\n};\n\nconst pick = (shape: MultipartShape, keys: readonly string[]): z.ZodType => {\n const wanted = new Set(keys);\n const picked: Record<string, z.ZodType> = {};\n for (const [key, schema] of Object.entries(shape)) {\n if (wanted.has(key)) {\n picked[key] = schema;\n }\n }\n return z.object(picked);\n};\n\nconst validate = async (schema: z.ZodType, value: unknown, argType: ArgType): Promise<unknown> => {\n const result = await schema.safeParseAsync(value);\n if (result.success) {\n return result.data;\n }\n throw new ZodValidationException(result.error, {\n type: argType,\n metatype: undefined,\n data: undefined,\n });\n};\n\nconst assertFilesOnRequest = (metadata: MultipartMetadata, decorator: string): void => {\n if (metadata.filesIn === MultipartFilesIn.Request) {\n return;\n }\n throw new Error(\n `[zod-nest] ${decorator} is unavailable under filesIn: 'body' — the parser puts files in the request body, so read them with @ZodMultipartBody().`,\n );\n};\n\nexport const resolveUploadedFile = async (\n name: string,\n ctx: ExecutionContext,\n): Promise<unknown> => {\n const metadata = readMetadata(ctx, '@ZodUploadedFile');\n assertFilesOnRequest(metadata, '@ZodUploadedFile');\n const request: { file?: unknown } = ctx.switchToHttp().getRequest();\n return validate(schemaFor(metadata, name, '@ZodUploadedFile'), request.file, 'custom');\n};\n\nexport const resolveUploadedFiles = async (\n name: string | undefined,\n ctx: ExecutionContext,\n): Promise<unknown> => {\n const metadata = readMetadata(ctx, '@ZodUploadedFiles');\n assertFilesOnRequest(metadata, '@ZodUploadedFiles');\n const request: { files?: unknown } = ctx.switchToHttp().getRequest();\n const schema =\n name === undefined\n ? pick(requireShape(metadata, '@ZodUploadedFiles'), metadata.fileKeys)\n : schemaFor(metadata, name, '@ZodUploadedFiles');\n return validate(schema, request.files, 'custom');\n};\n\nexport const resolveMultipartBody = async (\n _data: unknown,\n ctx: ExecutionContext,\n): Promise<unknown> => {\n const metadata = readMetadata(ctx, '@ZodMultipartBody');\n const shape = requireShape(metadata, '@ZodMultipartBody');\n const request: { body?: unknown } = ctx.switchToHttp().getRequest();\n const keys = metadata.filesIn === MultipartFilesIn.Body ? Object.keys(shape) : metadata.textKeys;\n return validate(pick(shape, keys), request.body, 'body');\n};\n\n/**\n * Validates `req.file` against the named property of the `@ZodMultipart`\n * shape. The name selects a schema; it never searches the request. Match it\n * to your `FileInterceptor('<name>')` field name, as with plain Nest.\n */\nexport const ZodUploadedFile = createParamDecorator(resolveUploadedFile);\n\n/**\n * Validates `req.files` against the named property of the `@ZodMultipart`\n * shape, or against an object of every declared file property when called\n * with no name — the record shape `FileFieldsInterceptor` produces.\n */\nexport const ZodUploadedFiles = createParamDecorator(resolveUploadedFiles);\n\n/**\n * Validates `req.body` against the `@ZodMultipart` shape — the text fields\n * only under `filesIn: 'request'` (multer keeps files off the body), the\n * whole shape under `filesIn: 'body'`.\n */\nexport const ZodMultipartBody = createParamDecorator(resolveMultipartBody);\n"]}
@@ -8,6 +8,7 @@ var DEFS_PREFIX = "#/$defs/";
8
8
  var ZOD_NEST_ERROR_EXTENSION = "x-zod-nest-error";
9
9
  var ZOD_NEST_ERROR_DUPLICATE_ID = "duplicate-id";
10
10
  var ZOD_NEST_DTO_EXTENSION = "x-zod-nest-dto";
11
+ var ZOD_NEST_ITEM_STREAM_EXTENSION = "x-zod-nest-item-stream";
11
12
 
12
13
  // src/schema/discover-dependents.ts
13
14
  var INNER_TYPE_WRAPPERS = /* @__PURE__ */ new Set([
@@ -817,6 +818,6 @@ var flattenObjectIntersection = /* @__PURE__ */ __name((schema, registry, decora
817
818
  return z.object(mergedShape);
818
819
  }, "flattenObjectIntersection");
819
820
 
820
- export { ANON_RESPONSE_PREFIX, COMPONENTS_SCHEMAS_PREFIX, ZOD_DTO_SYMBOL, ZOD_NEST_DTO_EXTENSION, ZOD_NEST_ERROR_DUPLICATE_ID, ZOD_NEST_ERROR_EXTENSION, ZodNestError, ZodNestUnrepresentableError, ZodValidationException, buildToJsonSchemaOptions, createRegistry, defaultRegistry, expandObjectSchema, extend, flattenObjectIntersection, getLineage, isZodDto, isZodObject, isZodSchema, paramSchemaBody, registerSchema, resolveAnonId, resolveSchemaRef, toOpenApi };
821
- //# sourceMappingURL=chunk-YRTGPVSJ.mjs.map
822
- //# sourceMappingURL=chunk-YRTGPVSJ.mjs.map
821
+ export { ANON_RESPONSE_PREFIX, COMPONENTS_SCHEMAS_PREFIX, ZOD_DTO_SYMBOL, ZOD_NEST_DTO_EXTENSION, ZOD_NEST_ERROR_DUPLICATE_ID, ZOD_NEST_ERROR_EXTENSION, ZOD_NEST_ITEM_STREAM_EXTENSION, ZodNestError, ZodNestUnrepresentableError, ZodValidationException, buildToJsonSchemaOptions, createRegistry, defaultRegistry, expandObjectSchema, extend, flattenObjectIntersection, getLineage, isZodDto, isZodObject, isZodSchema, paramSchemaBody, registerSchema, resolveAnonId, resolveSchemaRef, toOpenApi };
822
+ //# sourceMappingURL=chunk-6HU5TMFO.mjs.map
823
+ //# sourceMappingURL=chunk-6HU5TMFO.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/schema/constants.ts","../src/schema/discover-dependents.ts","../src/schema/registry.ts","../src/schema/composition.ts","../src/schema/errors.ts","../src/schema/override.ts","../src/schema/post-process.ts","../src/schema/engine.ts","../src/dto/symbols.ts","../src/dto/predicates.ts","../src/exceptions/validation.exception.ts","../src/schema/anon-id.ts","../src/decorators/internal/zod-schema-ref.ts","../src/decorators/internal/zod-param-expand.ts","../src/decorators/internal/flatten-intersection.ts"],"names":["COMPONENTS_SCHEMAS_PREFIX","DEFS_PREFIX","ZOD_NEST_ERROR_EXTENSION","ZOD_NEST_ERROR_DUPLICATE_ID","ZOD_NEST_DTO_EXTENSION","ZOD_NEST_ITEM_STREAM_EXTENSION","INNER_TYPE_WRAPPERS","Set","resolveLazyTarget","getter","error","ReferenceError","collectChildren","schema","def","_zod","type","shape","out","Object","values","catchall","undefined","push","element","options","map","opt","left","right","items","it","rest","keyType","valueType","in","has","innerType","discoverDependents","visited","WeakSet","stack","length","current","pop","add","child","named","findRefTarget","owner","id","createRegistry","seen","Map","forceExposed","anonymous","pendingRoots","recordOnce","set","get","flushPendingDiscovery","root","splice","childId","zodRegistry","z","globalRegistry","register","flags","expose","existing","hasCollision","size","getCollisions","ids","keys","forceExposedIds","anonymousIds","defaultRegistry","singleton","registerSchema","registry","explicit","findIdOwner","lineageMap","WeakMap","OPTIONAL_WRAPPER_TYPES","isOptionalProp","propSchema","computeShapeKeys","entries","properties","key","required","filter","computeOverriddenKeys","parent","overriddenKeys","parentProp","extend","build","result","op","getLineage","DEFAULT_BUILD_REF","createCompositionOverride","opts","buildRef","ctx","jsonSchema","zodSchema","entry","parentCache","parentId","childProps","childRequired","parentPropSet","parentReqSet","deltaProps","value","deltaRequired","delta","additionalProperties","allOf","$ref","unevaluatedProperties","ZodNestError","Error","message","name","ZodNestUnrepresentableError","path","zodType","formatPath","String","join","primitiveOverride","format","combine","overrides","list","candidate","o","rewriteRefs","node","rootRef","Array","isArray","item","obj","ref","startsWith","slice","refsIn","rootDefId","raw","isReferenced","defs","ownRef","referencesRoot","stripEnvelope","$schema","$defs","resolveRoot","refs","liftedId","body","delete","rootId","strict","postProcess","rawDefs","STRICT_REQUIRES_OVERRIDE","ANNOTATION_ONLY_KEYS","isStrictlyUnrepresentable","every","descentTarget","$in","io","traits","markPipeCoverage","covered","target","buildToJsonSchemaOptions","params","compositionOverride","uri","customOverride","createCustomOverride","merged","override","unrepresentableHits","coveredByPipe","wrapped","record","peekRegistration","unrepresentable","metadata","cycles","reused","consumeUnrepresentable","firstHit","find","hit","resolveRootId","toOpenApi","built","toJSONSchema","description","ZOD_DTO_SYMBOL","Symbol","for","isZodDto","isZodSchema","ZodType","ZodValidationException","BadRequestException","zodError","argMetadata","statusCode","HttpStatus","BAD_REQUEST","errors","treeifyError","cause","ANON_RESPONSE_PREFIX","ANON_BODY_PREFIX","anonIdCache","counterRef","resolveAnonId","prefix","cached","resolveSchemaRef","kind","deferAnonInline","anonId","isZodObject","expandObjectSchema","decoratorName","resolution","forceRequired","paramSchemaBody","intersectionArms","unionOptions","collectObjectShapes","shapes","unionCrossed","allShapes","variant","variantResult","arms","flattenObjectIntersection","collected","mergedShape","assign","optional","object"],"mappings":";;;;;AACO,IAAMA,yBAAAA,GAA4B;AAGlC,IAAMC,WAAAA,GAAc,UAAA;AAGpB,IAAMC,wBAAAA,GAA2B;AAGjC,IAAMC,2BAAAA,GAA8B;AAQpC,IAAMC,sBAAAA,GAAyB;AAI/B,IAAMC,8BAAAA,GAAiC;;;AChB9C,IAAMC,mBAAAA,uBAA0BC,GAAAA,CAAI;AAClC,EAAA,UAAA;AACA,EAAA,UAAA;AACA,EAAA,SAAA;AACA,EAAA,UAAA;AACA,EAAA,OAAA;AACA,EAAA,aAAA;AACA,EAAA,SAAA;AACA,EAAA,UAAA;AACA,EAAA;AACD,CAAA,CAAA;AAKD,IAAMC,iBAAAA,2BAAqBC,MAAAA,KAAAA;AACzB,EAAA,IAAI;AACF,IAAA,OAAO;MAACA,MAAAA;;AACV,EAAA,CAAA,CAAA,OAASC,KAAAA,EAAO;AACd,IAAA,IAAIA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AA,MAAW5O,KAAAA,IAAS2O,UAAUP,MAAAA,EAAQ;AACpClO,IAAAA,MAAAA,CAAO2O,MAAAA,CAAOD,aAAa5O,KAAAA,CAAAA;AAC7B,EAAA;AACA,EAAA,IAAI2O,UAAUN,YAAAA,EAAc;AAK1B,IAAA,KAAA,MAAW,CAAC1J,GAAAA,EAAK2B,KAAAA,KAAUpG,MAAAA,CAAOuE,OAAAA,CAAQmK,WAAAA,CAAAA,EAAc;AACtDA,MAAAA,WAAAA,CAAYjK,GAAAA,CAAAA,GAAO2B,KAAAA,CAAMwI,QAAAA,EAAQ;AACnC,IAAA;AACF,EAAA;AAIA/K,EAAAA,cAAAA,CAAenE,QAAQoE,QAAAA,CAAAA;AAIvB,EAAA,KAAA,MAAW,CAACnC,KAAAA,EAAOiB,OAAAA,CAAAA,IAAYzB,kBAAAA,CAAmBzB,MAAAA,CAAAA,EAAS;AACzDoE,IAAAA,QAAAA,CAASd,QAAAA,CAASrB,OAAOiB,OAAAA,CAAAA;AAC3B,EAAA;AACA,EAAA,OAAOE,CAAAA,CAAE+L,OAAOH,WAAAA,CAAAA;AAClB,CAAA,EAtCyC,2BAAA","file":"chunk-6HU5TMFO.mjs","sourcesContent":["/** OpenAPI 3.1 `$ref` prefix for entries in `components.schemas`. */\nexport const COMPONENTS_SCHEMAS_PREFIX = '#/components/schemas/';\n\n/** JSON Schema `$ref` prefix for entries in `$defs` (single-schema emission). */\nexport const DEFS_PREFIX = '#/$defs/';\n\n/** OpenAPI extension key zod-nest uses to surface engine errors inside emitted schemas. */\nexport const ZOD_NEST_ERROR_EXTENSION = 'x-zod-nest-error';\n\n/** Value of `x-zod-nest-error` when a registry id is claimed by more than one schema. */\nexport const ZOD_NEST_ERROR_DUPLICATE_ID = 'duplicate-id';\n\n/**\n * OpenAPI extension key used by `createZodDto` to mark a class for `applyZodNest`.\n * The marker carries `{ __zodNestDto: true, dtoId, io }` so `applyZodNest` can\n * locate every zod-nest DTO in the @nestjs/swagger document and inject the\n * real Zod-derived schema.\n */\nexport const ZOD_NEST_DTO_EXTENSION = 'x-zod-nest-dto';\n\n/** Transient marker on a Media Type Object: this custom stream carries discrete\n * items, so the 3.2 pass rewrites its `schema` to `itemSchema`. Always stripped. */\nexport const ZOD_NEST_ITEM_STREAM_EXTENSION = 'x-zod-nest-item-stream';\n","import { z } from 'zod';\n\nimport type { $ZodType, $ZodTypes } from 'zod/v4/core';\n\nimport { findRefTarget } from './clone-chain.js';\n\nconst INNER_TYPE_WRAPPERS = new Set([\n 'optional',\n 'nullable',\n 'default',\n 'prefault',\n 'catch',\n 'nonoptional',\n 'success',\n 'readonly',\n 'promise',\n]);\n\n// A `z.lazy` getter can close over a `const` still in its temporal dead zone\n// (mutual recursion under ESM). Treat that as \"no child yet\" — `toOpenApi`\n// calls the getter again and reports a genuinely broken reference then.\nconst resolveLazyTarget = (getter: () => $ZodType): z.ZodType[] => {\n try {\n return [getter() as unknown as z.ZodType];\n } catch (error) {\n if (error instanceof ReferenceError) {\n return [];\n }\n throw error;\n }\n};\n\nconst collectChildren = (schema: z.ZodType): z.ZodType[] => {\n const def = (schema as unknown as $ZodTypes)._zod.def;\n if (def.type === 'object') {\n const shape = def.shape as Record<string, z.ZodType>;\n const out: z.ZodType[] = [...Object.values(shape)];\n if (def.catchall !== undefined) {\n out.push(def.catchall as unknown as z.ZodType);\n }\n return out;\n }\n if (def.type === 'array') {\n return [def.element as unknown as z.ZodType];\n }\n if (def.type === 'union') {\n return (def.options as readonly $ZodType[]).map((opt) => opt as unknown as z.ZodType);\n }\n if (def.type === 'intersection') {\n return [def.left as unknown as z.ZodType, def.right as unknown as z.ZodType];\n }\n if (def.type === 'tuple') {\n const out: z.ZodType[] = (def.items as readonly $ZodType[]).map(\n (it) => it as unknown as z.ZodType,\n );\n if (def.rest !== null) {\n out.push(def.rest as unknown as z.ZodType);\n }\n return out;\n }\n if (def.type === 'record' || def.type === 'map') {\n return [def.keyType as unknown as z.ZodType, def.valueType as unknown as z.ZodType];\n }\n if (def.type === 'set') {\n return [def.valueType as unknown as z.ZodType];\n }\n if (def.type === 'pipe') {\n return [def.in as unknown as z.ZodType, def.out as unknown as z.ZodType];\n }\n if (def.type === 'lazy') {\n return resolveLazyTarget(() => def.getter());\n }\n if (INNER_TYPE_WRAPPERS.has(def.type)) {\n return [(def as { innerType: $ZodType }).innerType as unknown as z.ZodType];\n }\n return [];\n};\n\n/**\n * Returns every named descendant of `schema` — sub-schemas carrying\n * `.meta({ id })` reachable through the Zod composition tree, at any depth.\n *\n * Cycle-safe via a visited `WeakSet` keyed by Zod schema identity; safe for\n * `z.lazy` schemas that close over themselves. Leaf types (string, number,\n * enum, literal, custom, transform, …) have no children and are skipped.\n */\nexport const discoverDependents = (schema: z.ZodType): ReadonlyArray<[z.ZodType, string]> => {\n const visited = new WeakSet<z.ZodType>();\n const out: [z.ZodType, string][] = [];\n const stack: z.ZodType[] = [schema];\n while (stack.length > 0) {\n const current = stack.pop() as z.ZodType;\n if (visited.has(current)) {\n continue;\n }\n visited.add(current);\n for (const child of collectChildren(current)) {\n // Defensive: a malformed/in-progress schema can yield an undefined slot\n // (sparse object shape, undefined tuple item, etc.). The walker treats\n // such slots as \"no child here\" rather than crashing — the user's\n // schema may still emit fine through `toJSONSchema`.\n if (child === undefined || visited.has(child)) {\n continue;\n }\n // Zod emits `$ref` to a named *ancestor* of a `.describe()` / `.refine()`\n // / `z.compile()` clone, so the ancestor is the document dependency.\n const named = findRefTarget(child);\n if (named !== undefined) {\n out.push([named.owner, named.id]);\n }\n stack.push(child);\n }\n }\n return out;\n};\n","import { z } from 'zod';\n\nimport { findIdOwner } from './clone-chain.js';\nimport { discoverDependents } from './discover-dependents.js';\nimport { singleton } from './singleton.js';\n\n/**\n * Per-registration flags carried alongside the id.\n *\n * - `expose` — force the id into the emitted document even when no endpoint\n * references it. The author deliberately wants it in `components.schemas`\n * (e.g. for out-of-band client codegen). Default exposure is otherwise\n * reachability-scoped, so an unreferenced schema is pruned unless flagged.\n * - `anonymous` — the id is a synthetic placeholder for a schema with no\n * resolvable id (passed inline to `@ZodResponse` / `@ZodBody`). It exists\n * only to carry the body through bulk emission under the document's\n * `strict` / `override` options; `inlineAnonymousBodies` later inlines the\n * body at each `$ref` site and prunes the component, so the synthetic id\n * never reaches the final document.\n *\n * Both flags are sticky — once set for an id they stay set, so a later plain\n * `register` of the same id (e.g. the idempotent re-register inside\n * `createZodDto`) doesn't clear them.\n */\nexport interface RegisterFlags {\n readonly expose?: boolean;\n readonly anonymous?: boolean;\n}\n\nexport interface ZodNestRegistry {\n readonly zodRegistry: typeof z.globalRegistry;\n register(schema: z.ZodType, id: string, flags?: RegisterFlags): void;\n hasCollision(id: string): boolean;\n getCollisions(): ReadonlyMap<string, ReadonlySet<z.ZodType>>;\n /**\n * Snapshot of every id registered through this `ZodNestRegistry`. The\n * underlying Zod registry is `z.globalRegistry`, which may hold third-party\n * entries — bulk emission scopes both its input registry and its output to\n * this snapshot, so third-party entries are neither emitted nor\n * strict-checked.\n *\n * Includes ids discovered transitively via `.meta({ id })` on descendants\n * of explicitly-registered schemas.\n */\n ids(): readonly string[];\n /** Ids registered with `{ expose: true }` — exposed regardless of usage. */\n forceExposedIds(): readonly string[];\n /** Ids registered with `{ anonymous: true }` — inlined + pruned by `applyZodNest`. */\n anonymousIds(): readonly string[];\n}\n\nexport const createRegistry = (): ZodNestRegistry => {\n const seen = new Map<string, Set<z.ZodType>>();\n const forceExposed = new Set<string>();\n const anonymous = new Set<string>();\n const pendingRoots: z.ZodType[] = [];\n\n const recordOnce = (schema: z.ZodType, id: string): boolean => {\n let set = seen.get(id);\n if (set === undefined) {\n set = new Set<z.ZodType>();\n seen.set(id, set);\n }\n if (set.has(schema)) {\n return false;\n }\n set.add(schema);\n return true;\n };\n\n const flushPendingDiscovery = (): void => {\n for (const root of pendingRoots.splice(0)) {\n for (const [child, childId] of discoverDependents(root)) {\n recordOnce(child, childId);\n }\n }\n };\n\n return {\n zodRegistry: z.globalRegistry,\n register: (schema, id, flags) => {\n // Flags are sticky: a later plain re-register of the same id (e.g. the\n // idempotent call inside `createZodDto`) must not clear an earlier\n // `expose` / `anonymous`.\n if (flags?.expose === true) {\n forceExposed.add(id);\n }\n if (flags?.anonymous === true) {\n anonymous.add(id);\n }\n // `globalRegistry.add` overwrites the schema's entire meta entry; we\n // must merge so user-supplied fields (`title`, `description`,\n // anything else in `.meta({...})`) survive registration. The `has`\n // gate avoids promoting parent-inherited meta into a local entry\n // — `get()` returns parent-merged metadata when the schema has no\n // local entry, and writing that back here would freeze the\n // inherited fields against the schema.\n if (z.globalRegistry.has(schema)) {\n // `?? {}` is unreachable — the `has` gate guarantees a local entry —\n // but the return type is optional, so the fallback satisfies it.\n const existing = z.globalRegistry.get(schema) ?? {};\n if (existing.id !== id) {\n z.globalRegistry.add(schema, { ...existing, id });\n }\n } else {\n z.globalRegistry.add(schema, { id });\n }\n if (!recordOnce(schema, id)) {\n return;\n }\n // Queue, don't walk: forcing `z.lazy` getters here reads forward\n // references still in their temporal dead zone (throws under ESM,\n // yields `undefined` under CJS). Draining on first read is always safe.\n pendingRoots.push(schema);\n },\n hasCollision: (id) => {\n flushPendingDiscovery();\n const set = seen.get(id);\n return set !== undefined && set.size > 1;\n },\n getCollisions: () => {\n flushPendingDiscovery();\n const out = new Map<string, Set<z.ZodType>>();\n for (const [id, set] of seen) {\n if (set.size <= 1) {\n continue;\n }\n out.set(id, set);\n }\n return out;\n },\n ids: () => {\n flushPendingDiscovery();\n return [...seen.keys()];\n },\n forceExposedIds: () => [...forceExposed],\n anonymousIds: () => [...anonymous],\n };\n};\n\n/** Process-wide default registry. Shared so subpath ids reach `applyZodNest`. */\nexport const defaultRegistry: ZodNestRegistry = singleton('default-registry', createRegistry);\n\nexport interface RegisterSchemaOptions {\n /** Forces this id, overriding any `.meta({ id })` already on the schema. */\n readonly id?: string;\n /**\n * Force the schema into the emitted document even when no endpoint\n * references it. Default exposure is reachability-scoped — see\n * {@link RegisterFlags.expose}.\n */\n readonly expose?: boolean;\n /**\n * Mark the resolved id as a synthetic anonymous placeholder — inlined and\n * pruned by `applyZodNest`. See {@link RegisterFlags.anonymous}.\n */\n readonly anonymous?: boolean;\n}\n\n/**\n * Register a schema with the given registry, resolving its id from (in order):\n * an explicit `options.id`, then `.meta({ id })` on the schema. Returns the\n * resolved id, or `undefined` when neither source yields one (the call is then\n * a no-op — callers with their own fallback path handle that case).\n *\n * Shared by `createZodDto` and `extend` so a schema named via `.meta({ id })`\n * gets its body emitted into `components.schemas` even when it never flows\n * through `createZodDto` (e.g. used only as an `extend()` parent — Zod's\n * `.extend()` produces a flat object, so the parent isn't a transitive\n * descendant of the child and would otherwise be missed by `discoverDependents`).\n *\n * Idempotent — `registry.register` already deduplicates repeat calls.\n */\nexport const registerSchema = (\n schema: z.ZodType,\n registry: ZodNestRegistry = defaultRegistry,\n options?: RegisterSchemaOptions,\n): string | undefined => {\n const flags: RegisterFlags = { expose: options?.expose, anonymous: options?.anonymous };\n const explicit = options?.id;\n if (typeof explicit === 'string' && explicit !== '') {\n registry.register(schema, explicit, flags);\n return explicit;\n }\n // Registers the *owner*, never the clone: two instances under one id read as\n // a collision (`recordOnce`), and the clone already emits `$ref` to the owner.\n const named = findIdOwner(schema, registry.zodRegistry);\n if (named === undefined) {\n return undefined;\n }\n registry.register(named.owner, named.id, flags);\n return named.id;\n};\n","/**\n * Composition layer — emits OpenAPI `allOf` for schemas derived via `extend`.\n *\n * **EXPERIMENTAL**: output shape may change as edge cases surface.\n */\n\nimport { z } from 'zod';\n\nimport type { $ZodType } from 'zod/v4/core';\nimport type { SchemaObject } from './openapi.types.js';\nimport type { Override } from './override.js';\nimport type { ZodNestRegistry } from './registry.js';\n\nimport { DEFS_PREFIX } from './constants.js';\nimport { registerSchema } from './registry.js';\nimport { singleton } from './singleton.js';\n\n/**\n * Lineage record for a composition-derived schema. Read by the override to\n * emit `allOf` instead of a flat body.\n *\n * @experimental — shape may change.\n */\nexport interface LineageEntry {\n readonly op: 'extend';\n readonly parent: z.ZodObject;\n /**\n * Keys the child redeclared with a *different* schema than the parent's\n * (e.g. narrowing `type: SomeEnum` to `type: z.literal('A')`). Computed by\n * reference comparison at `extend()` time — Zod's `.extend()` keeps the same\n * shape reference for untouched keys and assigns a fresh one for overrides.\n * The composition override keeps these in the delta instead of dropping them\n * as parent-owned, so the narrowing survives in the emitted `allOf`.\n */\n readonly overriddenKeys: ReadonlySet<string>;\n}\n\n// `WeakMap` (not `z.registry`) so transient derived schemas can GC — Zod's\n// own docs warn against long-running registries pinning short-lived schemas.\nconst lineageMap = singleton('lineage-map', () => new WeakMap<$ZodType, LineageEntry>());\n\n/** Zod's wrapper types that make a property optional in JSON Schema's `required` sense. */\nexport const OPTIONAL_WRAPPER_TYPES: ReadonlySet<string> = new Set(['optional', 'default']);\n\nexport const isOptionalProp = (propSchema: z.ZodType): boolean =>\n OPTIONAL_WRAPPER_TYPES.has(propSchema._zod.def.type);\n\nconst computeShapeKeys = (\n schema: z.ZodObject,\n): { properties: readonly string[]; required: readonly string[] } => {\n const entries = Object.entries(schema.shape);\n return {\n properties: entries.map(([key]) => key),\n required: entries.filter(([, propSchema]) => !isOptionalProp(propSchema)).map(([key]) => key),\n };\n};\n\n/**\n * Keys the child shares with the parent by name but redeclares with a\n * different schema. Relies on Zod's `.extend()` reference semantics: untouched\n * keys keep the parent's shape reference, overridden keys get a fresh one.\n */\nconst computeOverriddenKeys = (parent: z.ZodObject, child: z.ZodObject): ReadonlySet<string> => {\n const overriddenKeys = new Set<string>();\n for (const key of Object.keys(child.shape)) {\n const parentProp = parent.shape[key];\n if (parentProp !== undefined && parentProp !== child.shape[key]) {\n overriddenKeys.add(key);\n }\n }\n return overriddenKeys;\n};\n\n/**\n * Wraps a derived `z.ZodObject` and records the parent → child link so\n * emission rewrites the body to `allOf: [{ $ref: <parent> }, <delta>]`.\n *\n * @experimental — output shape may change as the surface stabilizes.\n *\n * @example\n * const Base = z.object({ id: z.string() }).meta({ id: 'Base' });\n * const Child = extend(Base, (s) => s.extend({ role: z.string() }).meta({ id: 'Child' }));\n */\nexport const extend = <P extends z.ZodObject, S extends z.ZodObject>(\n parent: P,\n build: (p: P) => S,\n): S => {\n const result = build(parent);\n lineageMap.set(result, {\n op: 'extend',\n parent,\n overriddenKeys: computeOverriddenKeys(parent, result),\n });\n // Auto-register named parent/result so their bodies land in\n // `components.schemas`. Zod's `.extend()` produces a flat object, so the\n // parent isn't a transitive descendant of the result — without this, a\n // parent named only via `.meta({ id })` would be referenced by `$ref` but\n // never emitted, yielding `DANGLING_REF`. No-op when the schema is\n // anonymous. The composition override (below) re-registers against the\n // active registry at emit time as a backstop for custom-registry users.\n registerSchema(parent);\n registerSchema(result);\n return result;\n};\n\n/**\n * Read the lineage entry for a composition-derived schema, or `undefined`.\n *\n * @experimental — `LineageEntry` shape may change.\n */\nexport const getLineage = (schema: z.ZodType): LineageEntry | undefined => lineageMap.get(schema);\n\n/**\n * Default ref builder for single-schema mode (`toOpenApi`) — refs land in\n * `#/$defs/<id>` and `post-process` rewrites them to `#/components/schemas/<id>`.\n * Bulk mode passes its own `uri` callback so refs land at the final location.\n */\nexport const DEFAULT_BUILD_REF = (id: string): string => `${DEFS_PREFIX}${id}`;\n\nexport interface CreateCompositionOverrideOptions {\n /** Shape the `$ref` string for a parent id. Defaults to `#/$defs/<id>`. */\n buildRef: (id: string) => string;\n /** Registry to resolve parent ids against. Use the same instance the engine emits with. */\n registry: ZodNestRegistry;\n}\n\n/**\n * Factory for the composition override. Returns an `Override` that rewrites\n * composition-derived schemas to `allOf` form, falling back to Zod's flat\n * emission when no lineage entry exists or the parent has no registered id.\n *\n * Mutation happens in-place — Zod's override doesn't propagate\n * `ctx.jsonSchema = newBody` reassignments; only mutations on the existing\n * object reference reach the caller.\n */\nexport const createCompositionOverride = (opts: CreateCompositionOverrideOptions): Override => {\n const { buildRef, registry } = opts;\n return (ctx) => {\n const { jsonSchema, zodSchema } = ctx;\n const entry = lineageMap.get(zodSchema);\n if (entry === undefined) {\n return;\n }\n\n const parentCache = computeShapeKeys(entry.parent);\n\n // Backstop the eager `extend()` registration above: that only writes to\n // `defaultRegistry`, so custom-registry users need the parent surfaced\n // here too. Idempotent against the eager call.\n const parentId = registerSchema(entry.parent, registry);\n if (parentId === undefined) {\n // Anonymous parent — fall back to Zod's flat emission.\n return;\n }\n\n const childProps = jsonSchema.properties ?? {};\n const childRequired = jsonSchema.required ?? [];\n const parentPropSet = new Set(parentCache.properties);\n const parentReqSet = new Set(parentCache.required);\n\n const deltaProps: NonNullable<SchemaObject['properties']> = {};\n for (const [key, value] of Object.entries(childProps)) {\n // Drop parent-owned keys, but keep any the child overrode with a\n // different schema — otherwise the narrowing (e.g. enum → literal) is\n // lost and `allOf` would only carry the parent's wider constraint.\n if (parentPropSet.has(key) && !entry.overriddenKeys.has(key)) {\n continue;\n }\n deltaProps[key] = value;\n }\n // Mirror the properties logic: drop parent-required keys, but keep any the\n // child overrode and still requires — its narrowed body now lives in the\n // delta, so the `required` marker must travel with it (otherwise the\n // overridden field reads as optional in the delta arm, e.g. breaking a\n // discriminated union whose discriminator must be required on each arm).\n const deltaRequired = childRequired.filter(\n (key) => !parentReqSet.has(key) || entry.overriddenKeys.has(key),\n );\n\n const delta: SchemaObject = { type: 'object', properties: deltaProps };\n if (deltaRequired.length > 0) {\n delta.required = deltaRequired;\n }\n\n delete jsonSchema.properties;\n delete jsonSchema.required;\n delete jsonSchema.additionalProperties;\n // Keep `type: 'object'` on the wrapper rather than deleting it: every arm of\n // the `allOf` is an object, so the wrapper is unambiguously an object, and\n // the explicit `type` is the more correct / tool-friendly emission.\n // `type: 'object'` + `allOf` is valid (the instance must be an object AND\n // satisfy every arm); `unevaluatedProperties: false` still closes the shape.\n jsonSchema.type = 'object';\n jsonSchema.allOf = [{ $ref: buildRef(parentId) }, delta];\n jsonSchema.unevaluatedProperties = false;\n };\n};\n","export class ZodNestError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ZodNestError';\n }\n}\n\nexport class ZodNestUnrepresentableError extends ZodNestError {\n readonly path: ReadonlyArray<string | number>;\n readonly zodType: string;\n\n constructor(path: ReadonlyArray<string | number>, zodType: string) {\n super(\n `Unrepresentable Zod schema \\`${zodType}\\` at ${formatPath(path)}: no override produced ` +\n `a JSON Schema body. Set strict: false to emit \\`{}\\` instead, or supply an \\`override\\` ` +\n `that handles this Zod type.`,\n );\n this.name = 'ZodNestUnrepresentableError';\n this.path = path;\n this.zodType = zodType;\n }\n}\n\nconst formatPath = (path: ReadonlyArray<string | number>): string => {\n if (path.length === 0) {\n return '<root>';\n }\n return '/' + path.map(String).join('/');\n};\n","import type { $ZodTypes } from 'zod/v4/core';\nimport type { SchemaObject } from './openapi.types.js';\n\nexport interface OverrideContext {\n zodSchema: $ZodTypes;\n jsonSchema: SchemaObject;\n path: (string | number)[];\n}\n\nexport type Override = (ctx: OverrideContext) => void;\n\n/**\n * Type-driven override for primitive Zod constructs that JSON Schema can't\n * represent directly (bigint → integer, date → string + date-time format).\n * Composition's `allOf`-form emission lives in `composition.ts`; the engine\n * combines both into the full override chain per call site (since composition\n * needs a uri-aware `buildRef` that differs between single-schema and bulk\n * emission).\n */\nexport const primitiveOverride: Override = ({ zodSchema, jsonSchema }) => {\n const type = zodSchema._zod.def.type;\n if (type === 'bigint') {\n jsonSchema.type = 'integer';\n return;\n }\n if (type === 'date') {\n jsonSchema.type = 'string';\n jsonSchema.format = 'date-time';\n return;\n }\n};\n\nexport const combine = (...overrides: ReadonlyArray<Override | undefined>): Override => {\n const list: Override[] = [];\n for (const candidate of overrides) {\n if (typeof candidate !== 'function') {\n continue;\n }\n list.push(candidate);\n }\n return (ctx) => {\n for (const o of list) {\n o(ctx);\n }\n };\n};\n","import type { SchemaObject } from './openapi.types.js';\n\nimport { COMPONENTS_SCHEMAS_PREFIX, DEFS_PREFIX } from './constants.js';\nimport { ZodNestError } from './errors.js';\n\nexport interface PostProcessResult {\n schema: SchemaObject;\n refs: Map<string, SchemaObject>;\n}\n\nexport interface PostProcessOptions {\n /** Component id of the emitted root, when it has one. Resolves `'#'` refs. */\n rootId?: string;\n strict?: boolean;\n}\n\n// Zod emits '#' for a cycle back to the document root, so it resolves to the\n// root's own component — never to whichever def happens to contain it.\nconst rewriteRefs = (node: unknown, rootRef: string | undefined): void => {\n if (Array.isArray(node)) {\n for (const item of node) {\n rewriteRefs(item, rootRef);\n }\n return;\n }\n if (node === null || typeof node !== 'object') {\n return;\n }\n const obj = node as Record<string, unknown>;\n const ref = obj.$ref;\n if (typeof ref === 'string' && ref.startsWith(DEFS_PREFIX)) {\n obj.$ref = COMPONENTS_SCHEMAS_PREFIX + ref.slice(DEFS_PREFIX.length);\n } else if (ref === '#' && rootRef !== undefined) {\n obj.$ref = rootRef;\n }\n for (const value of Object.values(obj)) {\n rewriteRefs(value, rootRef);\n }\n};\n\nconst refsIn = function* (node: unknown): Generator<string> {\n if (Array.isArray(node)) {\n for (const item of node) {\n yield* refsIn(item);\n }\n return;\n }\n if (node === null || typeof node !== 'object') {\n return;\n }\n const obj = node as Record<string, unknown>;\n if (typeof obj.$ref === 'string') {\n yield obj.$ref;\n }\n for (const value of Object.values(obj)) {\n yield* refsIn(value);\n }\n};\n\nconst rootDefId = (raw: SchemaObject): string | undefined => {\n const ref = raw.$ref;\n if (typeof ref !== 'string' || !ref.startsWith(DEFS_PREFIX)) {\n return undefined;\n }\n return ref.slice(DEFS_PREFIX.length);\n};\n\nconst isReferenced = (defs: SchemaObject['$defs'], id: string): boolean => {\n const ownRef = `${DEFS_PREFIX}${id}`;\n for (const ref of refsIn(defs)) {\n if (ref === '#' || ref === ownRef) {\n return true;\n }\n }\n return false;\n};\n\nconst referencesRoot = (raw: SchemaObject): boolean => {\n for (const ref of refsIn(raw)) {\n if (ref === '#') {\n return true;\n }\n }\n return false;\n};\n\nconst stripEnvelope = (raw: SchemaObject): SchemaObject => {\n const root: SchemaObject = { ...raw };\n delete root.$schema;\n delete root.$defs;\n return root;\n};\n\ninterface ResolvedRoot {\n schema: SchemaObject;\n rootRef: string | undefined;\n}\n\n// A referenced root has to be addressable, so it keeps (or gains) a component\n// entry and the caller gets a `$ref`. Inlining an unreferenced one keeps zod\n// 4.4 and 4.5 emitting the same shape.\nconst resolveRoot = (\n raw: SchemaObject,\n refs: Map<string, SchemaObject>,\n options: PostProcessOptions | undefined,\n): ResolvedRoot => {\n const liftedId = rootDefId(raw);\n if (liftedId !== undefined) {\n const body = refs.get(liftedId);\n if (body !== undefined && !isReferenced(raw.$defs, liftedId)) {\n refs.delete(liftedId);\n return { schema: body, rootRef: undefined };\n }\n return { schema: stripEnvelope(raw), rootRef: `${COMPONENTS_SCHEMAS_PREFIX}${liftedId}` };\n }\n\n const root = stripEnvelope(raw);\n if (!referencesRoot(raw)) {\n return { schema: root, rootRef: undefined };\n }\n\n const rootId = options?.rootId;\n if (rootId === undefined) {\n if (options?.strict ?? true) {\n throw new ZodNestError(\n 'A schema referenced from inside its own emission has no id, so the reference ' +\n 'cannot be resolved. Add `.meta({ id: \"…\" })` to the root schema, or set ' +\n 'strict: false to leave the reference unresolved.',\n );\n }\n return { schema: root, rootRef: undefined };\n }\n\n refs.set(rootId, root);\n const rootRef = `${COMPONENTS_SCHEMAS_PREFIX}${rootId}`;\n return { schema: { $ref: rootRef }, rootRef };\n};\n\nexport const postProcess = (raw: SchemaObject, options?: PostProcessOptions): PostProcessResult => {\n const refs = new Map<string, SchemaObject>();\n const rawDefs = raw.$defs;\n if (rawDefs !== undefined) {\n for (const [id, body] of Object.entries(rawDefs)) {\n refs.set(id, body);\n }\n }\n\n const { schema, rootRef } = resolveRoot(raw, refs, options);\n rewriteRefs(schema, rootRef);\n\n for (const body of refs.values()) {\n rewriteRefs(body, rootRef);\n }\n\n return { schema, refs };\n};\n","import { z } from 'zod';\n\nimport type { $ZodType, $ZodTypes } from 'zod/v4/core';\nimport type { SchemaObject } from './openapi.types.js';\nimport type { Override } from './override.js';\nimport type { ZodNestRegistry } from './registry.js';\n\nimport { findIdOwner } from './clone-chain.js';\nimport { createCompositionOverride, DEFAULT_BUILD_REF } from './composition.js';\nimport { ZOD_NEST_ERROR_DUPLICATE_ID, ZOD_NEST_ERROR_EXTENSION } from './constants.js';\nimport { createCustomOverride, peekRegistration } from './custom-override.js';\nimport { ZodNestUnrepresentableError } from './errors.js';\nimport { combine, primitiveOverride } from './override.js';\nimport { postProcess } from './post-process.js';\n\n/**\n * Zod constructs that JSON Schema can't represent without an override. When\n * one of these shows up and our combined override chain didn't produce any\n * body for it, strict mode collects the hit and surfaces it as a\n * `ZodNestUnrepresentableError`. Bound to `engine.ts` since the strict-hit\n * collection lives here too.\n */\nconst STRICT_REQUIRES_OVERRIDE: ReadonlySet<string> = new Set([\n 'bigint',\n 'date',\n 'symbol',\n 'undefined',\n 'void',\n 'map',\n 'set',\n 'transform',\n 'nan',\n 'custom',\n]);\n\n/**\n * Keywords that annotate a schema without describing its shape. A body made\n * only of these has no type, so it's as unrepresentable as an empty one —\n * `.meta({ title })` on an unregistered schema emits exactly that, and\n * checking emptiness alone let it through as a valid annotation-only body.\n *\n * Deliberately an allow-list of annotations rather than a deny-list of\n * structural keywords: an unrecognised keyword counts as structural, so a\n * future JSON Schema addition can't turn into a spurious build failure.\n */\nconst ANNOTATION_ONLY_KEYS: ReadonlySet<string> = new Set([\n 'title',\n 'description',\n 'deprecated',\n 'examples',\n 'default',\n 'readOnly',\n 'writeOnly',\n '$id',\n '$schema',\n '$comment',\n 'id',\n]);\n\nconst isStrictlyUnrepresentable = (jsonSchema: SchemaObject, zodSchema: $ZodTypes): boolean => {\n if (!STRICT_REQUIRES_OVERRIDE.has(zodSchema._zod.def.type)) {\n return false;\n }\n return Object.keys(jsonSchema).every((key) => ANNOTATION_ONLY_KEYS.has(key));\n};\n\nexport interface ToOpenApiOptions {\n io: 'input' | 'output';\n registry: ZodNestRegistry;\n override?: Override;\n strict?: boolean;\n}\n\nexport interface ToOpenApiResult {\n schema: SchemaObject;\n refs: Map<string, SchemaObject>;\n}\n\ninterface UnrepresentableHit {\n path: (string | number)[];\n zodType: string;\n /**\n * Schema instance that emitted empty. Kept so `consumeUnrepresentable`\n * can drop hits whose outer pipe later marked them covered — pipes process\n * inner before outer in reverse-seen order, so the inner's hit fires\n * before the outer pipe gets to declare coverage.\n */\n zodSchema: $ZodType;\n}\n\nconst descentTarget = ($in: $ZodType, out: $ZodType, io: 'input' | 'output'): $ZodType => {\n if (io === 'output') {\n return out;\n }\n // A transform emits its output shape, so its input side is never the target.\n if ($in._zod.traits.has('$ZodTransform')) {\n return out;\n }\n return $in;\n};\n\n/**\n * Mark a pipe's descent target as covered by an outer registration when\n * the override for the outer pipe fires. Recurses for nested\n * pipe-of-pipe chains (e.g. `pipe(pipe2, transform)`) so the deep inner\n * descent target also has its strict-mode hit suppressed.\n *\n * Mirrors Zod's `pipeProcessor` descent rules (`json-schema-processors.js`):\n * - `io === 'output'` → cover `def.out`\n * - `io === 'input'` → cover `def.out` when `def.in` is a `$ZodTransform`\n * (Zod skips preprocessing on input emission), else `def.in`.\n */\nconst markPipeCoverage = (\n schema: $ZodType,\n io: 'input' | 'output',\n covered: WeakSet<$ZodType>,\n): void => {\n const def = schema._zod.def as { type: string; in?: $ZodType; out?: $ZodType };\n if (def.type !== 'pipe' || def.in === undefined || def.out === undefined) {\n return;\n }\n const target = descentTarget(def.in, def.out, io);\n if (covered.has(target)) {\n return;\n }\n covered.add(target);\n markPipeCoverage(target, io, covered);\n};\n\n/**\n * Parameters for `buildToJsonSchemaOptions` — the shared option-bag builder\n * used by both `toOpenApi` (single-schema mode) and `bulkEmit` (registry-mode).\n * Centralizes the override chain, unrepresentable detection,\n * metadata wiring, and target/cycles defaults so both paths emit equivalent\n * JSON Schema for the same input.\n */\nexport interface BuildToJsonSchemaOptionsParams {\n registry: ZodNestRegistry;\n io: 'input' | 'output';\n override?: Override;\n strict?: boolean;\n /**\n * Zod's strategy for anonymous reused sub-schemas. Both single-schema and\n * bulk modes use `'inline'` — `'ref'` extracts anonymous reused branches\n * into a virtual `__shared/$defs` table whose refs don't resolve against\n * `components.schemas`, producing dangling refs. Registered schemas\n * (`metadata.id` present) always go through the `uri` callback regardless,\n * so DTO-to-DTO `$ref`s are unaffected.\n */\n reused: 'inline' | 'ref';\n /** Bulk-mode only — shapes internal `$ref`s to `#/components/schemas/<id>`. */\n uri?: (id: string) => string;\n}\n\nexport interface BuiltJsonSchemaOptions {\n options: NonNullable<Parameters<typeof z.toJSONSchema>[1]>;\n /** Throws `ZodNestUnrepresentableError` if any strict-unrepresentable hit was collected during emission. */\n consumeUnrepresentable(): void;\n}\n\nexport const buildToJsonSchemaOptions = (\n params: BuildToJsonSchemaOptionsParams,\n): BuiltJsonSchemaOptions => {\n const strict = params.strict ?? true;\n // Composition's `buildRef` differs between single-schema and bulk modes:\n // single-schema emits `#/$defs/<id>` (post-process rewrites to\n // `#/components/schemas/<id>`); bulk emits `#/components/schemas/<id>`\n // directly via the configured `uri` callback (post-process is skipped).\n const compositionOverride = createCompositionOverride({\n buildRef: params.uri ?? DEFAULT_BUILD_REF,\n registry: params.registry,\n });\n // Chain order matches precedence (left → right, last-write-wins mutation\n // semantics). Caller's `params.override` runs last so per-call overrides\n // remain the ultimate escape hatch; `customOverride` consults the\n // `overrideJSONSchema(...)` registration map (parameterized by `io` so it\n // can pick divergent input/output fragments) and clobbers the built-in\n // primitive/composition mappings for the registered schema instance.\n const customOverride = createCustomOverride(params.io);\n const merged = combine(primitiveOverride, compositionOverride, customOverride, params.override);\n const unrepresentableHits: UnrepresentableHit[] = [];\n // Inner descent targets shadowed by an outer pipe registration. Populated\n // JIT during traversal: Zod processes inner-before-outer in reverse-seen\n // order, but `consumeUnrepresentable` runs only after traversal completes,\n // so by then the outer pipe's coverage declaration has landed.\n const coveredByPipe = new WeakSet<$ZodType>();\n\n const wrapped: Override = (ctx) => {\n merged(ctx);\n if (ctx.zodSchema._zod.def.type === 'pipe') {\n const record = peekRegistration(ctx.zodSchema);\n if (record !== undefined && record[params.io] !== undefined) {\n markPipeCoverage(ctx.zodSchema, params.io, coveredByPipe);\n }\n }\n if (!strict || !isStrictlyUnrepresentable(ctx.jsonSchema, ctx.zodSchema)) {\n return;\n }\n unrepresentableHits.push({\n path: [...ctx.path],\n zodType: ctx.zodSchema._zod.def.type,\n zodSchema: ctx.zodSchema,\n });\n };\n\n const options: NonNullable<Parameters<typeof z.toJSONSchema>[1]> = {\n target: 'draft-2020-12',\n io: params.io,\n unrepresentable: 'any',\n metadata: params.registry.zodRegistry,\n override: wrapped,\n cycles: 'ref',\n reused: params.reused,\n };\n if (params.uri !== undefined) {\n options.uri = params.uri;\n }\n\n return {\n options,\n consumeUnrepresentable: () => {\n const firstHit = unrepresentableHits.find((hit) => !coveredByPipe.has(hit.zodSchema));\n if (firstHit !== undefined) {\n throw new ZodNestUnrepresentableError(firstHit.path, firstHit.zodType);\n }\n },\n };\n};\n\n// Covers both `.meta({ id })` and `registry.register(schema, id)` — the latter\n// writes the id through to the zod registry.\nconst resolveRootId = (schema: z.ZodType, registry: ZodNestRegistry): string | undefined =>\n findIdOwner(schema, registry.zodRegistry)?.id;\n\nexport const toOpenApi = (schema: z.ZodType, opts: ToOpenApiOptions): ToOpenApiResult => {\n const built = buildToJsonSchemaOptions({\n registry: opts.registry,\n io: opts.io,\n override: opts.override,\n strict: opts.strict,\n reused: 'inline',\n });\n const raw = z.toJSONSchema(schema, built.options);\n built.consumeUnrepresentable();\n\n const result = postProcess(raw, {\n rootId: resolveRootId(schema, opts.registry),\n strict: opts.strict,\n });\n\n for (const [id] of opts.registry.getCollisions()) {\n if (!result.refs.has(id)) {\n continue;\n }\n result.refs.set(id, {\n description: `ERROR: duplicate zod-nest id <${id}>`,\n [ZOD_NEST_ERROR_EXTENSION]: ZOD_NEST_ERROR_DUPLICATE_ID,\n });\n }\n\n return result;\n};\n","/** Runtime tag placed on every class returned by `createZodDto`. */\nexport const ZOD_DTO_SYMBOL: unique symbol = Symbol.for('zod-nest.dto');\n","import { z } from 'zod';\n\nimport type { ZodDto } from './dto.types.js';\n\nimport { ZOD_DTO_SYMBOL } from './symbols.js';\n\n/**\n * Runtime guard: is `value` a class returned by `createZodDto`?\n *\n * Used by `ZodValidationPipe`, `ZodSerializerInterceptor`, and `applyZodNest`\n * to discriminate zod-nest DTOs from plain\n * constructors, class-validator DTOs, primitives, and any other metatypes\n * NestJS exposes via `ArgumentMetadata`.\n */\nexport const isZodDto = (value: unknown): value is ZodDto =>\n typeof value === 'function' &&\n (value as unknown as Record<symbol, unknown>)[ZOD_DTO_SYMBOL] === true;\n\n/**\n * Runtime guard: is `value` a Zod schema (any `z.*` type)?\n *\n * Used by `@ZodResponse` to accept a raw schema in place of a DTO — including\n * `z.discriminatedUnion` / `z.union` / `z.intersection`, which can't be wrapped\n * with `createZodDto` (their `z.infer` is a union, so `class … extends\n * createZodDto(schema)` fails to typecheck with TS2509). `instanceof z.ZodType`\n * holds for every schema built through the same `zod` module instance.\n */\nexport const isZodSchema = (value: unknown): value is z.ZodType => value instanceof z.ZodType;\n","import { BadRequestException, HttpStatus } from '@nestjs/common';\nimport { z } from 'zod';\n\nimport type { ArgumentMetadata } from '@nestjs/common';\n\n/**\n * Default exception thrown by `ZodValidationPipe` when input fails to parse.\n *\n * Body shape (returned by `getResponse()`):\n * ```\n * {\n * statusCode: 400,\n * message: 'Validation failed',\n * errors: z.treeifyError(zodError),\n * }\n * ```\n *\n * Carries `zodError` and `argMetadata` so custom exception filters can\n * introspect the original validation failure.\n */\nexport class ZodValidationException extends BadRequestException {\n readonly zodError: z.ZodError;\n readonly argMetadata?: ArgumentMetadata;\n\n constructor(zodError: z.ZodError, argMetadata?: ArgumentMetadata) {\n super(\n {\n statusCode: HttpStatus.BAD_REQUEST,\n message: 'Validation failed',\n errors: z.treeifyError(zodError),\n },\n { cause: zodError },\n );\n this.zodError = zodError;\n this.argMetadata = argMetadata;\n }\n}\n","import type { z } from 'zod';\n\nimport { singleton } from './singleton.js';\n\n/** Synthetic-id prefix for an anonymous `@ZodResponse` body. */\nexport const ANON_RESPONSE_PREFIX = '_AnonResponseSchema_';\n/** Synthetic-id prefix for an anonymous `@ZodBody` body. */\nexport const ANON_BODY_PREFIX = '_AnonBodySchema_';\n\n/**\n * One synthetic id per schema instance, cached so the same un-named schema\n * reused across routes maps to a single id (and therefore a single registry\n * entry) rather than minting a fresh one per decoration. WeakMap so the id is\n * GC'd with the schema. Mirrors the cache pattern in `output-dto.ts` /\n * `normalize-type.ts`.\n *\n * The counter is module-global so ids are unique across both prefixes; the\n * prefix is only chosen on first sight of a schema, so a schema passed to both\n * `@ZodBody` and `@ZodResponse` keeps whichever id it got first — harmless,\n * since the id is internal and inlined away.\n */\nconst anonIdCache = singleton('anon-id-cache', () => new WeakMap<z.ZodType, string>());\nconst counterRef = singleton('anon-id-counter', () => ({ value: 0 }));\n\nexport const resolveAnonId = (schema: z.ZodType, prefix: string): string => {\n const cached = anonIdCache.get(schema);\n if (cached !== undefined) {\n return cached;\n }\n counterRef.value += 1;\n const id = `${prefix}${counterRef.value}`;\n anonIdCache.set(schema, id);\n return id;\n};\n","import { z } from 'zod';\n\nimport type { ZodNestRegistry } from '../../schema/registry.js';\n\nimport { ANON_BODY_PREFIX, resolveAnonId } from '../../schema/anon-id.js';\nimport { COMPONENTS_SCHEMAS_PREFIX } from '../../schema/constants.js';\nimport { discoverDependents } from '../../schema/discover-dependents.js';\nimport { toOpenApi } from '../../schema/engine.js';\nimport { defaultRegistry, registerSchema } from '../../schema/registry.js';\n\n/**\n * Resolution of a schema used by `@ZodBody` / `@ZodQuery` / `@ZodParam` /\n * `@ZodHeaders` / `@ZodCookies`.\n *\n * - `ref` — the schema (or property's schema) has an id via `.meta({ id })`\n * or via the explicit `id` option. It's registered in the registry so\n * `applyZodNest`'s bulk-emit pass writes its body to `components.schemas`,\n * and the decorator references it as `{ $ref: '#/components/schemas/<id>' }`.\n * - `inline` — no id was resolvable; the JSON Schema body is embedded\n * directly into the operation. Named descendants are still registered so\n * any nested `$ref`s inside the inline body resolve at doc-build time.\n */\nexport interface SchemaRefResolutionRef {\n readonly kind: 'ref';\n readonly ref: { readonly $ref: string };\n}\nexport interface SchemaRefResolutionInline {\n readonly kind: 'inline';\n readonly schema: Record<string, unknown>;\n}\nexport type SchemaRefResolution = SchemaRefResolutionRef | SchemaRefResolutionInline;\n\nexport interface ResolveSchemaRefOptions {\n /** Forces this id, overriding any `.meta({ id })` already on the schema. */\n readonly id?: string;\n /** Registry to register into. Defaults to `defaultRegistry`. */\n readonly registry?: ZodNestRegistry;\n /**\n * When `true`, an anonymous (un-named) schema is registered under a synthetic\n * `anonymous` id and returned as a `$ref` instead of being rendered inline\n * here. `applyZodNest`'s `inlineAnonymousBodies` pass then inlines the body\n * (emitted by bulk-emit under the document's `strict` / `override`) and\n * prunes the component. Used by `@ZodBody`, where the body is emitted as a\n * full schema; left `false` for per-property param expansion, which inlines\n * the (usually primitive) property body directly.\n */\n readonly deferAnonInline?: boolean;\n}\n\n/**\n * Resolve a schema for embedding in an OpenAPI operation. If the schema is\n * named (has `.meta({ id })` or an explicit `options.id`), it's registered\n * and a `$ref` is returned. Otherwise:\n *\n * - with `deferAnonInline`, the schema is registered under a synthetic\n * `anonymous` id and a `$ref` to it is returned — `applyZodNest` inlines and\n * prunes it later, so the body honors the document's `strict` / `override`;\n * - without it, the schema is rendered inline here via `toOpenApi(...)`, and\n * any *named descendants* are registered so refs inside the inline body\n * resolve at doc-build time.\n */\n// With `deferAnonInline: true`, an anonymous schema is registered and returned\n// as a `$ref` too, so the result is always a `ref` — narrow the return so\n// callers (e.g. `@ZodBody`) don't carry a dead `inline` branch.\nexport function resolveSchemaRef(\n schema: z.ZodType,\n options: ResolveSchemaRefOptions & { readonly deferAnonInline: true },\n): SchemaRefResolutionRef;\nexport function resolveSchemaRef(\n schema: z.ZodType,\n options?: ResolveSchemaRefOptions,\n): SchemaRefResolution;\nexport function resolveSchemaRef(\n schema: z.ZodType,\n options?: ResolveSchemaRefOptions,\n): SchemaRefResolution {\n const registry = options?.registry ?? defaultRegistry;\n const id = registerSchema(schema, registry, { id: options?.id });\n if (id !== undefined) {\n return { kind: 'ref', ref: { $ref: `${COMPONENTS_SCHEMAS_PREFIX}${id}` } };\n }\n if (options?.deferAnonInline === true) {\n // `registerSchema` registers the schema and (via `register`) its named\n // descendants, so nested `$ref`s inside the emitted body resolve.\n const anonId = resolveAnonId(schema, ANON_BODY_PREFIX);\n registerSchema(schema, registry, { id: anonId, anonymous: true });\n return { kind: 'ref', ref: { $ref: `${COMPONENTS_SCHEMAS_PREFIX}${anonId}` } };\n }\n for (const [child, childId] of discoverDependents(schema)) {\n registry.register(child, childId);\n }\n const { schema: body } = toOpenApi(schema, { io: 'input', registry });\n return { kind: 'inline', schema: body as Record<string, unknown> };\n}\n","import { z } from 'zod';\n\nimport type { ZodNestRegistry } from '../../schema/registry.js';\nimport type { SchemaRefResolution } from './zod-schema-ref.js';\n\nimport { isOptionalProp } from '../../schema/composition.js';\nimport { ZodNestError } from '../../schema/errors.js';\nimport { defaultRegistry, registerSchema } from '../../schema/registry.js';\nimport { resolveSchemaRef } from './zod-schema-ref.js';\n\nexport const isZodObject = (schema: z.ZodType): schema is z.ZodObject =>\n schema._zod.def.type === 'object';\n\nexport interface ExpandedParam {\n readonly name: string;\n readonly required: boolean;\n readonly resolution: SchemaRefResolution;\n}\n\nexport interface ExpandObjectSchemaOptions {\n readonly id?: string;\n readonly registry?: ZodNestRegistry;\n /**\n * When `true`, every expanded property is marked `required` regardless of\n * its Zod optionality — path params can't be optional in OpenAPI.\n */\n readonly forceRequired?: boolean;\n /** Decorator name used in error messages, e.g. `@ZodQuery`. */\n readonly decoratorName: string;\n}\n\n/**\n * Expand a Zod object schema into one parameter entry per property. Used by\n * `@ZodQuery`, `@ZodParam`, `@ZodHeaders`, and `@ZodCookies` — they all\n * project an object schema onto N named OpenAPI parameters.\n *\n * Registers the root schema (when it has an id) so `components.schemas[id]`\n * holds the full object body for cross-referencing. Each property's schema\n * goes through `resolveSchemaRef` independently: named properties become\n * `$ref`s, anonymous properties inline.\n *\n * Throws `ZodNestError` when the schema is not a `z.object` — non-object\n * schemas can't be represented as a flat list of named params in OpenAPI.\n */\nexport const expandObjectSchema = (\n schema: z.ZodType,\n options: ExpandObjectSchemaOptions,\n): ExpandedParam[] => {\n if (!isZodObject(schema)) {\n throw new ZodNestError(\n `${options.decoratorName} requires a \\`z.object({...})\\` schema (got \\`${schema._zod.def.type}\\`). ` +\n `Each property of the object becomes one OpenAPI parameter. ` +\n `For non-object body shapes (intersections, unions, primitives), use \\`@ZodBody\\` instead.`,\n );\n }\n const registry = options.registry ?? defaultRegistry;\n // Register the root if it has an id — it isn't referenced by the per-property\n // expansion below, so it'll only land in `components.schemas` when something\n // else references it (`@ZodBody`, another decorator, a manual `$ref`).\n // Idempotent + harmless when the schema is anonymous.\n registerSchema(schema, registry, { id: options.id });\n const result: ExpandedParam[] = [];\n for (const [name, propSchema] of Object.entries(schema.shape)) {\n const resolution = resolveSchemaRef(propSchema, { registry });\n const required = options.forceRequired === true || !isOptionalProp(propSchema);\n result.push({ name, required, resolution });\n }\n return result;\n};\n\n/**\n * Resolve the JSON Schema body for a single expanded parameter. `$ref` for\n * named property schemas, otherwise the inline JSON Schema body.\n */\nexport const paramSchemaBody = (\n resolution: SchemaRefResolution,\n): { $ref: string } | Record<string, unknown> =>\n resolution.kind === 'ref' ? resolution.ref : resolution.schema;\n","import { z } from 'zod';\n\nimport type { ZodNestRegistry } from '../../schema/registry.js';\n\nimport { discoverDependents } from '../../schema/discover-dependents.js';\nimport { ZodNestError } from '../../schema/errors.js';\nimport { registerSchema } from '../../schema/registry.js';\nimport { isZodObject } from './zod-param-expand.js';\n\n/**\n * Runtime shape of Zod v4's `$ZodIntersectionDef`. The upstream `.left` /\n * `.right` are typed as Zod's internal `$ZodType` base, not the public\n * `z.ZodType`; the structures are runtime-equivalent. The cast at the\n * boundary keeps the rest of this module on the public type.\n */\ninterface IntersectionDef {\n readonly type: 'intersection';\n readonly left: z.ZodType;\n readonly right: z.ZodType;\n}\n\ninterface UnionDef {\n readonly type: 'union';\n readonly options: ReadonlyArray<z.ZodType>;\n}\n\nconst intersectionArms = (\n schema: z.ZodType,\n): { readonly left: z.ZodType; readonly right: z.ZodType } | null => {\n if (schema._zod.def.type !== 'intersection') {\n return null;\n }\n // Zod-internal → public-type boundary: `$ZodType` vs `z.ZodType`.\n const def = schema._zod.def as unknown as IntersectionDef;\n return { left: def.left, right: def.right };\n};\n\nconst unionOptions = (schema: z.ZodType): ReadonlyArray<z.ZodType> | null => {\n if (schema._zod.def.type !== 'union') {\n return null;\n }\n // Zod-internal → public-type boundary. `discriminatedUnion` also uses\n // `type: 'union'` and shares the `options` field shape.\n const def = schema._zod.def as unknown as UnionDef;\n return def.options;\n};\n\ninterface CollectedShapes {\n readonly shapes: ReadonlyArray<Record<string, z.ZodType>>;\n /**\n * `true` when the walk traversed a union arm at any depth — signals that\n * the merged shape should mark all properties optional, since no single\n * property is guaranteed across the original variants.\n */\n readonly unionCrossed: boolean;\n}\n\n/**\n * Walk an intersection / union tree and collect every `z.object` shape\n * reachable. Returns `null` as soon as a non-object leaf is hit (a\n * primitive, a tuple, a transform — anything that isn't an object and\n * isn't a composite of objects). Single-object input returns one shape.\n */\nconst collectObjectShapes = (schema: z.ZodType): CollectedShapes | null => {\n if (isZodObject(schema)) {\n return { shapes: [schema.shape], unionCrossed: false };\n }\n const options = unionOptions(schema);\n if (options !== null) {\n const allShapes: Array<Record<string, z.ZodType>> = [];\n for (const variant of options) {\n const variantResult = collectObjectShapes(variant);\n if (variantResult === null) {\n return null;\n }\n allShapes.push(...variantResult.shapes);\n }\n return { shapes: allShapes, unionCrossed: true };\n }\n const arms = intersectionArms(schema);\n if (arms === null) {\n return null;\n }\n const left = collectObjectShapes(arms.left);\n if (left === null) {\n return null;\n }\n const right = collectObjectShapes(arms.right);\n if (right === null) {\n return null;\n }\n return {\n shapes: [...left.shapes, ...right.shapes],\n unionCrossed: left.unionCrossed || right.unionCrossed,\n };\n};\n\n/**\n * Merge an intersection / union tree of `z.object` arms into a single\n * anonymous `z.object`. Callers register it as an anonymous body, so\n * `applyZodNest` emits it under the document's `strict` / `override` and\n * inlines it at the operation. Used by `@ZodBody({ flatten: true })` so\n * Swagger UI's `multipart/form-data` `try-it-out` form renders correctly —\n * the UI doesn't follow `$ref` or unwrap `allOf` / `oneOf`, so it needs a\n * flat object literal at the operation's `schema` site.\n *\n * Supported shapes:\n * - `z.object({...})` — single-arm case, identity merge.\n * - `z.intersection(obj, obj)` — merges both arms' properties.\n * - Nested intersections (`intersection(intersection(A, B), C)`) — all\n * reachable arms merged in source order.\n * - `z.union([obj, obj, ...])` / `z.discriminatedUnion(...)` — merges all\n * variant properties. **All merged properties become optional** because\n * no single property is guaranteed across the original variants.\n * - `intersection(union(...), union(...))` — combines the above; any\n * property reachable through a union is optional in the result.\n *\n * Rejected shapes (throws `ZodNestError`):\n * - Any non-object leaf at any depth: primitives, tuples, transforms,\n * nullable/optional wrappers around non-objects.\n *\n * Behavior details:\n * - Property collisions resolve right-arm-wins (mirrors `z.object`'s spread\n * semantics; for unions, later variants override earlier ones).\n * - The original schema's `.meta({ id })` on the root is *not* preserved —\n * the merged object is anonymous and lives only in the operation body.\n * - Per-property `.meta({ id })` schemas keep their `$ref` emission via\n * normal traversal.\n * - The spec emission becomes less precise (a union arm's \"you must supply\n * variant A or variant B\" becomes \"any subset of all variants' fields\").\n * This is the documented trade-off for Swagger UI compatibility — runtime\n * validation via `ZodValidationPipe(originalSchema)` still enforces the\n * precise shape.\n */\nexport const flattenObjectIntersection = (\n schema: z.ZodType,\n registry: ZodNestRegistry,\n decoratorName: string,\n): z.ZodObject => {\n const collected = collectObjectShapes(schema);\n if (collected === null) {\n throw new ZodNestError(\n `${decoratorName} \\`flatten: true\\` requires every leaf of the schema to be a ` +\n `\\`z.object({...})\\` — intersections and unions of objects are supported, but ` +\n `primitives, tuples, transforms, and other non-object leaves are not. Drop ` +\n `\\`flatten: true\\` to emit the original schema with its composition intact.`,\n );\n }\n const mergedShape: Record<string, z.ZodType> = {};\n for (const shape of collected.shapes) {\n Object.assign(mergedShape, shape);\n }\n if (collected.unionCrossed) {\n // Wrap each property in `.optional()` — no single property is guaranteed\n // across the original union variants, so the merged spec must allow any\n // subset. Runtime validation against the original schema still enforces\n // the precise variant shape.\n for (const [key, value] of Object.entries(mergedShape)) {\n mergedShape[key] = value.optional();\n }\n }\n // Register the root if it has a `.meta({ id })` so the schema's natural\n // (non-flattened) emission lands in `components.schemas[id]` via the\n // exposure-by-registration rule in `applyZodNest`. No-op when anonymous.\n registerSchema(schema, registry);\n // Walk named descendants of the *original* schema so per-property $refs\n // resolve at emission — the merged shape may miss meta entries carried on\n // nodes it doesn't directly reference.\n for (const [child, childId] of discoverDependents(schema)) {\n registry.register(child, childId);\n }\n return z.object(mergedShape);\n};\n"]}
@@ -10,6 +10,7 @@ var DEFS_PREFIX = "#/$defs/";
10
10
  var ZOD_NEST_ERROR_EXTENSION = "x-zod-nest-error";
11
11
  var ZOD_NEST_ERROR_DUPLICATE_ID = "duplicate-id";
12
12
  var ZOD_NEST_DTO_EXTENSION = "x-zod-nest-dto";
13
+ var ZOD_NEST_ITEM_STREAM_EXTENSION = "x-zod-nest-item-stream";
13
14
 
14
15
  // src/schema/discover-dependents.ts
15
16
  var INNER_TYPE_WRAPPERS = /* @__PURE__ */ new Set([
@@ -825,6 +826,7 @@ exports.ZOD_DTO_SYMBOL = ZOD_DTO_SYMBOL;
825
826
  exports.ZOD_NEST_DTO_EXTENSION = ZOD_NEST_DTO_EXTENSION;
826
827
  exports.ZOD_NEST_ERROR_DUPLICATE_ID = ZOD_NEST_ERROR_DUPLICATE_ID;
827
828
  exports.ZOD_NEST_ERROR_EXTENSION = ZOD_NEST_ERROR_EXTENSION;
829
+ exports.ZOD_NEST_ITEM_STREAM_EXTENSION = ZOD_NEST_ITEM_STREAM_EXTENSION;
828
830
  exports.ZodNestError = ZodNestError;
829
831
  exports.ZodNestUnrepresentableError = ZodNestUnrepresentableError;
830
832
  exports.ZodValidationException = ZodValidationException;
@@ -843,5 +845,5 @@ exports.registerSchema = registerSchema;
843
845
  exports.resolveAnonId = resolveAnonId;
844
846
  exports.resolveSchemaRef = resolveSchemaRef;
845
847
  exports.toOpenApi = toOpenApi;
846
- //# sourceMappingURL=chunk-Q3SWJZBB.js.map
847
- //# sourceMappingURL=chunk-Q3SWJZBB.js.map
848
+ //# sourceMappingURL=chunk-J2MGUXBB.js.map
849
+ //# sourceMappingURL=chunk-J2MGUXBB.js.map