zod-nest 3.0.2 → 3.2.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/helpers/fragments.ts","../../src/schema/custom-override.ts","../../src/multipart/file-checks.ts","../../src/multipart/file-marker.ts","../../src/multipart/build-file-schema.ts","../../src/multipart/metadata.ts","../../src/schema/discover-dependents.ts","../../src/schema/constants.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/schema/anon-id.ts","../../src/decorators/internal/zod-schema-ref.ts","../../src/decorators/internal/zod-param-expand.ts","../../src/decorators/internal/flatten-intersection.ts","../../src/dto/predicates.ts","../../src/multipart/zod-multipart.decorator.ts","../../src/exceptions/validation.exception.ts","../../src/multipart/param-decorators.ts","../../src/fastify/index.ts"],"names":["binaryFragment","type","format","binary","opts","customOverrideMap","WeakMap","isWrapper","arg","overrideJSONSchema","schema","overrideSchema","input","output","schemaDescription","description","set","peekRegistration","get","createCustomOverride","io","zodSchema","jsonSchema","record","undefined","fragment","key","Object","keys","Reflect","deleteProperty","assign","normalizeExtension","extension","startsWith","toLowerCase","mimeTypeCheck","accessors","options","allowed","Set","mimeTypes","map","mimeType","payload","value","has","issues","push","code","message","join","extensionCheck","extensions","fileName","matched","some","endsWith","sizeCheck","readSize","size","maxSize","fileSchemas","WeakSet","isZodType","innerOf","def","innerType","element","unwrapOnce","inner","_zod","markFileSchema","add","isFileSchema","resolveFragment","contentMediaType","singleMimeType","length","collectChecks","params","checks","withId","id","meta","buildFileSchema","base","z","custom","predicate","checked","check","MultipartFilesIn","Request","Body","ZOD_MULTIPART_METADATA_KEY","Symbol","for","INNER_TYPE_WRAPPERS","readId","globalRegistry","resolveLazyTarget","getter","error","ReferenceError","collectChildren","out","shape","values","catchall","opt","left","right","items","it","rest","keyType","valueType","in","discoverDependents","visited","stack","current","pop","child","COMPONENTS_SCHEMAS_PREFIX","DEFS_PREFIX","ZOD_NEST_ERROR_EXTENSION","ZOD_NEST_ERROR_DUPLICATE_ID","createRegistry","seen","Map","forceExposed","anonymous","pendingRoots","recordOnce","flushPendingDiscovery","root","splice","childId","zodRegistry","register","flags","expose","existing","hasCollision","getCollisions","ids","forceExposedIds","anonymousIds","defaultRegistry","registerSchema","registry","explicit","metaId","lineageMap","propsMap","DEFAULT_BUILD_REF","createCompositionOverride","buildRef","ctx","entry","parentCache","parent","parentId","childProps","properties","childRequired","required","parentPropSet","parentReqSet","deltaProps","entries","overriddenKeys","deltaRequired","filter","delta","additionalProperties","allOf","$ref","unevaluatedProperties","ZodNestError","Error","name","ZodNestUnrepresentableError","path","zodType","formatPath","String","primitiveOverride","combine","overrides","list","candidate","o","rewriteRefs","node","rootRef","Array","isArray","item","obj","ref","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","markPipeCoverage","covered","target","traits","buildToJsonSchemaOptions","compositionOverride","uri","customOverride","merged","override","unrepresentableHits","coveredByPipe","wrapped","unrepresentable","metadata","cycles","reused","consumeUnrepresentable","firstHit","find","hit","resolveRootId","toOpenApi","built","toJSONSchema","result","ANON_BODY_PREFIX","anonIdCache","counter","resolveAnonId","prefix","cached","resolveSchemaRef","kind","deferAnonInline","anonId","isZodObject","intersectionArms","unionOptions","collectObjectShapes","shapes","unionCrossed","allShapes","variant","variantResult","arms","flattenObjectIntersection","decoratorName","collected","mergedShape","optional","object","isZodSchema","ZodType","MULTIPART_CONTENT_TYPE","toSchema","toShape","partitionKeys","fileKeys","textKeys","resolveBody","flatten","resolved","createZodMultipart","defaultFilesIn","filesIn","propertyKey","descriptor","handler","TypeError","defineMetadata","swaggerDescriptor","ApiConsumes","ApiBody","ZodValidationException","BadRequestException","zodError","argMetadata","statusCode","HttpStatus","BAD_REQUEST","errors","treeifyError","cause","readMetadata","decorator","getMetadata","getHandler","isMultipartMetadata","requireShape","schemaFor","pick","wanted","picked","validate","argType","safeParseAsync","success","data","metatype","assertFilesOnRequest","resolveUploadedFile","request","switchToHttp","getRequest","file","resolveUploadedFiles","files","resolveMultipartBody","_data","createParamDecorator","ZodMultipartBody","isFastifyMultipartFile","toBuffer","mimetype","filename","fastifyMultipartFile","FastifyMultipartFileSchema","ZodMultipart"],"mappings":";;;;;;;;;;AAuCO,IAAMA,cAAAA,GAAiB;EAAEC,IAAAA,EAAM,QAAA;EAAUC,MAAAA,EAAQ;AAAS,CAAA;AAsG1D,IAAMC,MAAAA,2BAAUC,IAAAA,MAAgD;EACrE,GAAGJ,cAAAA;EACH,GAAGI;AACL,CAAA,CAAA,EAHsB,QAAA,CAAA;;;AClGtB,IAAMC,iBAAAA,uBAAwBC,OAAAA,EAAAA;AAE9B,IAAMC,4BAAY,MAAA,CAAA,CAChBC,GAAAA,KAC2D,OAAA,IAAWA,GAAAA,IAAO,YAAYA,GAAAA,EAFzE,WAAA,CAAA;AA8BX,IAAMC,kBAAAA,mBAAqB,MAAA,CAAA,CAChCC,MAAAA,EACAF,GAAAA,KAAAA;AAEA,EAAA,MAAMG,cAAAA,GAAkCJ,SAAAA,CAAUC,GAAAA,CAAAA,GAAO;IAAE,GAAGA;GAAI,GAAI;IAAEI,KAAAA,EAAOJ,GAAAA;IAAKK,MAAAA,EAAQL;AAAI,GAAA;AAEhG,EAAA,MAAMM,oBAAoBJ,MAAAA,CAAOK,WAAAA;AACjC,EAAA,IAAI,OAAOD,sBAAsB,QAAA,EAAU;AACzCH,IAAAA,cAAAA,CAAeI,WAAAA,GAAcD,iBAAAA;AAC/B,EAAA;AAEAT,EAAAA,iBAAAA,CAAkBW,GAAAA,CAAIN,QAAQC,cAAAA,CAAAA;AAE9B,EAAA,OAAOD,MAAAA;AACT,CAAA,E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kBAAAA,CAAmBtM,gBAAAA,CAAiBE,IAAI","file":"index.js","sourcesContent":["import type { SchemaObject } from '../schema/openapi.types.js';\n\n/**\n * Common JSON Schema fragment catalog — reusable building blocks for assembling\n * fragments by hand: alongside `z.custom<T>()`, in `overrideJSONSchema` calls,\n * in custom override callbacks, in tests that build expected fragments.\n *\n * The catalog overlaps with what Zod constructs already emit (`z.uuid()` →\n * `uuidFragment` shape, `z.email()` → `emailFragment` shape, etc.) — the\n * helpers don't *replace* those Zod constructs; they're a parallel catalog\n * for programmatic fragment assembly.\n *\n * Each fragment is `as const satisfies SchemaObject` so its literal type\n * powers the dispatch in {@link enrich} — passing wrong-family options\n * fails at compile time.\n */\n\n// ---------------------------------------------------------------------------\n// Layer 1 — Fragment catalog\n// ---------------------------------------------------------------------------\n\n// String formats (RFC-defined)\nexport const dateTimeFragment = {\n type: 'string',\n format: 'date-time',\n} as const satisfies SchemaObject;\nexport const dateFragment = { type: 'string', format: 'date' } as const satisfies SchemaObject;\nexport const timeFragment = { type: 'string', format: 'time' } as const satisfies SchemaObject;\nexport const uuidFragment = { type: 'string', format: 'uuid' } as const satisfies SchemaObject;\nexport const emailFragment = { type: 'string', format: 'email' } as const satisfies SchemaObject;\nexport const uriFragment = { type: 'string', format: 'uri' } as const satisfies SchemaObject;\nexport const hostnameFragment = {\n type: 'string',\n format: 'hostname',\n} as const satisfies SchemaObject;\nexport const ipv4Fragment = { type: 'string', format: 'ipv4' } as const satisfies SchemaObject;\nexport const ipv6Fragment = { type: 'string', format: 'ipv6' } as const satisfies SchemaObject;\n\n// Binary / encoded payloads\nexport const binaryFragment = { type: 'string', format: 'binary' } as const satisfies SchemaObject;\nexport const byteFragment = { type: 'string', format: 'byte' } as const satisfies SchemaObject;\n\n// Numeric formats (OpenAPI 3.1)\nexport const int32Fragment = { type: 'integer', format: 'int32' } as const satisfies SchemaObject;\nexport const int64Fragment = { type: 'integer', format: 'int64' } as const satisfies SchemaObject;\nexport const floatFragment = { type: 'number', format: 'float' } as const satisfies SchemaObject;\nexport const doubleFragment = { type: 'number', format: 'double' } as const satisfies SchemaObject;\n\n// Object passthrough\nexport const opaqueFragment = {\n type: 'object',\n additionalProperties: true,\n} as const satisfies SchemaObject;\n\n// ---------------------------------------------------------------------------\n// Layer 2 — Per-family option types\n// ---------------------------------------------------------------------------\n\nexport interface StringFormatOptions {\n description?: string;\n examples?: string[];\n minLength?: number;\n maxLength?: number;\n pattern?: string;\n}\n\nexport interface BinaryFragmentOptions {\n description?: string;\n contentMediaType?: string;\n contentEncoding?: string;\n}\n\nexport interface NumberFormatOptions {\n description?: string;\n examples?: number[];\n minimum?: number;\n maximum?: number;\n exclusiveMinimum?: number;\n exclusiveMaximum?: number;\n multipleOf?: number;\n}\n\nexport interface OpaqueFragmentOptions {\n description?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Layer 3 — Type-strict generic enrich\n// ---------------------------------------------------------------------------\n\n// `binary` discriminates before the generic string-format branch because its\n// option set diverges (contentMediaType / contentEncoding instead of length\n// constraints). Order matters here.\ntype OptionsFor<T> = T extends { readonly format: 'binary' }\n ? BinaryFragmentOptions\n : T extends {\n readonly format:\n | 'date-time'\n | 'date'\n | 'time'\n | 'uuid'\n | 'email'\n | 'uri'\n | 'hostname'\n | 'ipv4'\n | 'ipv6'\n | 'byte';\n }\n ? StringFormatOptions\n : T extends { readonly format: 'int32' | 'int64' | 'float' | 'double' }\n ? NumberFormatOptions\n : T extends { readonly type: 'object'; readonly additionalProperties: true }\n ? OpaqueFragmentOptions\n : never;\n\n/**\n * Merge a catalog fragment with extras whose shape is dictated by the base\n * fragment's family. Passing wrong-family extras (e.g. a `contentMediaType`\n * onto `uuidFragment`) is a compile-time error.\n *\n * Returns a fresh `SchemaObject` — the original fragment is never mutated.\n */\nexport const enrich = <T extends SchemaObject>(base: T, extras: OptionsFor<T>): SchemaObject => ({\n ...base,\n ...extras,\n});\n\n// ---------------------------------------------------------------------------\n// Layer 3b — Sugar functions\n// ---------------------------------------------------------------------------\n\n/**\n * Binary-content fragment with typed enrichment. Sugar for\n * `enrich(binaryFragment, opts)` — exists because the `binary` option set\n * (`contentMediaType` / `contentEncoding`) is nuanced enough to deserve a\n * dedicated entry point and discoverable via auto-complete.\n *\n * @example\n * overrideJSONSchema(z.instanceof(File), binary());\n * overrideJSONSchema(z.instanceof(File), binary({ contentMediaType: 'application/pdf' }));\n */\nexport const binary = (opts?: BinaryFragmentOptions): SchemaObject => ({\n ...binaryFragment,\n ...opts,\n});\n\n/**\n * Opaque-object fragment with typed enrichment. Sugar for\n * `enrich(opaqueFragment, opts)` — exists for parity with {@link binary}\n * and because opaque passthrough payloads commonly carry a description\n * explaining why the API doesn't introspect them.\n *\n * @example\n * overrideJSONSchema(z.unknown(), opaque({ description: 'JWT passthrough' }));\n */\nexport const opaque = (opts?: OpaqueFragmentOptions): SchemaObject => ({\n ...opaqueFragment,\n ...opts,\n});\n","import type { z } from 'zod';\nimport type { $ZodType } from 'zod/v4/core';\nimport type { SchemaObject } from './openapi.types.js';\nimport type { Override } from './override.js';\n\n/**\n * Argument shape for {@link overrideJSONSchema}. Two forms:\n *\n * - A raw `SchemaObject` — applied to both input and output emission.\n * - A `{ input?, output? }` wrapper — distinct fragments per emission side,\n * for coercion shapes where input and output diverge (e.g.\n * `z.union([z.array(item), item.transform((v) => [v])])` accepts\n * `T | T[]` on input but always emits `T[]` on output).\n *\n * The wrapper form is detected by the presence of an `input` or `output`\n * key. Neither is a JSON Schema / OpenAPI 3.1 keyword, so the discriminator\n * is unambiguous in practice.\n */\nexport type OverrideJSONSchemaArg = SchemaObject | { input?: SchemaObject; output?: SchemaObject };\n\nexport interface StoredFragments {\n input?: SchemaObject;\n output?: SchemaObject;\n /**\n * Description captured from the Zod schema at `overrideJSONSchema(...)` call\n * time (`.describe(...)` / `.meta({ description })` both write to\n * `z.globalRegistry`). Applied as a fallback at emission time when the\n * per-direction fragment doesn't supply its own `description`. Fragment-\n * supplied descriptions still win.\n */\n description?: string;\n}\n\n/**\n * Per-instance JSON Schema registration store. Keyed by the Zod core type\n * (`$ZodType`) because that's what the override sees on `ctx.zodSchema`;\n * `z.ZodType` widens to `$ZodType` without a cast at the public API boundary.\n * Same WeakMap pattern as `composition.ts`'s `lineageMap`\n * (CLAUDE.md: \"transient, per-instance → WeakMap\").\n *\n * Value holds the per-direction fragments separately so the override factory\n * can pick the right one without surfacing `io` on `OverrideContext`.\n */\nconst customOverrideMap = new WeakMap<$ZodType, StoredFragments>();\n\nconst isWrapper = (\n arg: OverrideJSONSchemaArg,\n): arg is { input?: SchemaObject; output?: SchemaObject } => 'input' in arg || 'output' in arg;\n\n/**\n * Register a fixed JSON Schema fragment for a specific Zod schema instance.\n *\n * Designed for shapes JSON Schema can't model directly — `z.custom<T>()` and\n * `z.instanceof(...)` (e.g. multipart `File` fields) — which Zod emits as `{}`,\n * tripping `ZodNestUnrepresentableError` in strict mode. Also useful for\n * coercion shapes where input and output diverge (`singleOrArray`-style\n * helpers).\n *\n * Two call shapes:\n *\n * ```ts\n * // 1. Single fragment — applied verbatim to both input and output emission.\n * overrideJSONSchema(FileSchema, { type: 'string', format: 'binary' });\n *\n * // 2. Divergent fragments — separate fragments per emission side. Omit a\n * // side to leave Zod's default emission untouched on that side.\n * overrideJSONSchema(arrayOrItem, {\n * input: { anyOf: [arrFrag, itemFrag] },\n * output: arrFrag,\n * });\n * ```\n *\n * Idempotent: subsequent calls for the same schema overwrite the prior\n * registration (last-write-wins).\n */\nexport const overrideJSONSchema = <T extends z.ZodType>(\n schema: T,\n arg: OverrideJSONSchemaArg,\n): T => {\n const overrideSchema: StoredFragments = isWrapper(arg) ? { ...arg } : { input: arg, output: arg };\n\n const schemaDescription = schema.description;\n if (typeof schemaDescription === 'string') {\n overrideSchema.description = schemaDescription;\n }\n\n customOverrideMap.set(schema, overrideSchema);\n\n return schema;\n};\n\n/**\n * Read-only lookup into the registration store. Used by the engine to detect\n * when a pipe-typed schema covers its inner descent target with a relevant-io\n * fragment — see `buildToJsonSchemaOptions` in `engine.ts`. Returning a\n * possibly-`undefined` `StoredFragments` keeps the engine ignorant of the\n * underlying WeakMap.\n */\nexport const peekRegistration = (schema: $ZodType): StoredFragments | undefined =>\n customOverrideMap.get(schema);\n\n/**\n * Internal override factory consulted by the engine. Closes over the current\n * emission direction so the lookup can pick the right registered fragment\n * without surfacing `io` on the `OverrideContext` public contract. Mirrors\n * `createCompositionOverride` at `engine.ts:98`.\n *\n * Mutates `ctx.jsonSchema` in-place (clears existing keys, then assigns the\n * fragment) because Zod's override pipeline doesn't propagate\n * `ctx.jsonSchema = newObj` reassignments — only mutations on the existing\n * object reach the caller (see `composition.ts` for the same constraint).\n *\n * Falls back to the schema's captured `description` (from `.describe(...)` /\n * `.meta({ description })`) when the per-direction fragment doesn't supply\n * one. Captured at `overrideJSONSchema(...)` call time so the inheritance\n * doesn't depend on Zod's emission-time metadata pass. `title` is\n * deliberately not inherited.\n *\n * No-ops if the schema isn't registered, or if the registered record has no\n * fragment for the current `io` direction.\n */\nexport const createCustomOverride = (io: 'input' | 'output'): Override => {\n return ({ zodSchema, jsonSchema }) => {\n const record = customOverrideMap.get(zodSchema);\n if (record === undefined) {\n return;\n }\n const fragment = record[io];\n if (fragment === undefined) {\n return;\n }\n for (const key of Object.keys(jsonSchema)) {\n Reflect.deleteProperty(jsonSchema, key);\n }\n Object.assign(jsonSchema, fragment);\n if (fragment.description === undefined && record.description !== undefined) {\n jsonSchema.description = record.description;\n }\n };\n};\n","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\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 = 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 { z } from 'zod';\n\nimport type { $ZodType, $ZodTypes } from 'zod/v4/core';\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\nconst readId = (schema: z.ZodType): string | undefined => {\n const meta = z.globalRegistry.get(schema);\n if (meta === undefined) {\n return undefined;\n }\n const id = (meta as { id?: unknown }).id;\n return typeof id === 'string' ? id : undefined;\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 out: z.ZodType[] = [];\n const shape = def.shape as Record<string, z.ZodType> | undefined;\n if (shape !== undefined) {\n for (const value of Object.values(shape)) {\n out.push(value);\n }\n }\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 const id = readId(child);\n if (id !== undefined) {\n out.push([child, id]);\n }\n stack.push(child);\n }\n }\n return out;\n};\n","/** 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","import { z } from 'zod';\n\nimport { discoverDependents } from './discover-dependents.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 filters its output against this snapshot to keep\n * only zod-nest-known ids.\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 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, used when no explicit `options.registry` is passed. */\nexport const defaultRegistry: ZodNestRegistry = 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 const meta = registry.zodRegistry.get(schema);\n const metaId = meta === undefined ? undefined : (meta as { id?: unknown }).id;\n if (typeof metaId !== 'string' || metaId === '') {\n return undefined;\n }\n registry.register(schema, metaId, flags);\n return metaId;\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';\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 = new WeakMap<$ZodType, LineageEntry>();\n\n// Parent flat-key cache, populated eagerly by `extend()` at registration.\n// `reused: 'inline'` inlines the parent's shape into the child rather than\n// firing the override on the parent as a separate node, so the override\n// can't be relied on to populate this — extend() does it eagerly.\nconst propsMap = new WeakMap<\n $ZodType,\n { properties: readonly string[]; required: readonly string[] }\n>();\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 { shape } = schema;\n const properties = Object.keys(shape);\n const required = properties.filter((key) => {\n const propSchema = shape[key];\n return propSchema !== undefined && !isOptionalProp(propSchema);\n });\n return { properties, required };\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 if (!propsMap.has(parent)) {\n propsMap.set(parent, computeShapeKeys(parent));\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 = propsMap.get(entry.parent);\n if (parentCache === undefined) {\n // Defensive: `extend()` pre-caches the parent at registration time, so\n // by the time the child's override fires this should be set.\n return;\n }\n\n const parentId = registry.zodRegistry.get(entry.parent)?.id;\n if (parentId === undefined) {\n // Anonymous parent — fall back to Zod's flat emission.\n return;\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 registerSchema(entry.parent, registry);\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 { 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\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 =\n io === 'output' ? def.out : def.in._zod.traits.has('$ZodTransform') ? def.out : def.in;\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 const id = registry.zodRegistry.get(schema)?.id;\n return typeof id === 'string' && id !== '' ? id : undefined;\n};\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","import type { z } from 'zod';\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 = new WeakMap<z.ZodType, string>();\nlet counter = 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 counter += 1;\n const id = `${prefix}${counter}`;\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 { toOpenApi } from '../../schema/engine.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`, emit it inline, and return the JSON Schema body.\n * Used by `@ZodBody({ flatten: true })` so Swagger UI's\n * `multipart/form-data` `try-it-out` form renders correctly — the UI\n * doesn't follow `$ref` or unwrap `allOf` / `oneOf`, so it needs a flat\n * 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 `toOpenApi` 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): Record<string, unknown> => {\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 of Object.keys(mergedShape)) {\n const value = mergedShape[key];\n if (value !== undefined) {\n mergedShape[key] = value.optional();\n }\n }\n }\n const merged = z.object(mergedShape);\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`. The inline operation\n // body remains the flat merged form for Swagger UI compatibility — the\n // catalog gets the structural composition (`allOf` / `oneOf`). No-op\n // when the schema is anonymous.\n registerSchema(schema, registry);\n // Walk named descendants of the *original* schema so per-property $refs\n // resolve when bulk-emit runs. `toOpenApi` below will also register\n // descendants of the merged shape, but the original may carry meta entries\n // on nodes that the merged object's shape doesn't directly reference.\n for (const [child, childId] of discoverDependents(schema)) {\n registry.register(child, childId);\n }\n const { schema: body } = toOpenApi(merged, { io: 'input', registry });\n return body as Record<string, unknown>;\n};\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 { 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 { 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\nconst toSchema = (body: MultipartBody): z.ZodType =>\n isZodSchema(body) ? body : z.object({ ...body });\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. Anonymous bodies emit inline because Swagger\n * UI's `multipart/form-data` form generator doesn't follow `$ref` — a\n * referenced body renders one stub field instead of file pickers. Naming the\n * body (`id` or `.meta({ id })`) opts into the `$ref` and that trade-off.\n */\nconst resolveBody = (\n schema: z.ZodType,\n options: ZodMultipartOptions | undefined,\n registry: ZodNestRegistry,\n): Record<string, unknown> | { readonly $ref: string } => {\n if (options?.flatten === true) {\n return flattenObjectIntersection(schema, registry, '@ZodMultipart');\n }\n const resolved = resolveSchemaRef(schema, {\n ...(options?.id !== undefined ? { id: options.id } : {}),\n registry,\n });\n return resolved.kind === 'ref' ? resolved.ref : resolved.schema;\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 { 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 { 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","import type { z } from 'zod';\nimport type { BaseFileOptions } from '../multipart/build-file-schema.js';\nimport type { FileAccessors } from '../multipart/file-checks.js';\n\nimport { buildFileSchema } from '../multipart/build-file-schema.js';\nimport { MultipartFilesIn } from '../multipart/metadata.js';\nimport { createZodMultipart } from '../multipart/zod-multipart.decorator.js';\n\n/**\n * Shape `@fastify/multipart` attaches to the body under\n * `attachFieldsToBody: true`. The bytes are still a stream — `toBuffer()`\n * reads them — so there is no `size` field to validate against.\n */\nexport interface FastifyMultipartFileLike {\n type: 'file';\n fieldname: string;\n filename: string;\n encoding: string;\n mimetype: string;\n toBuffer: () => Promise<Buffer>;\n}\n\n/**\n * Options for the `@fastify/multipart` file helper.\n *\n * There is deliberately no `maxSize`: a `MultipartFile` reports no size\n * before its stream is read, so the size limit belongs in the plugin's\n * `limits.fileSize`.\n *\n * `mimeTypes` and `extensions` match the client-supplied values. They are not\n * content sniffing; use `@nestjs/common`'s `FileTypeValidator` when you need\n * magic-number checks.\n */\nexport type FastifyMultipartFileOptions = BaseFileOptions;\n\nconst isFastifyMultipartFile = (value: unknown): boolean =>\n value !== null &&\n typeof value === 'object' &&\n 'type' in value &&\n value.type === 'file' &&\n 'mimetype' in value &&\n 'filename' in value &&\n 'toBuffer' in value &&\n typeof value.toBuffer === 'function';\n\nconst accessors: FileAccessors<FastifyMultipartFileLike> = {\n mimeType: (file) => file.mimetype,\n fileName: (file) => file.filename,\n};\n\n/** `@fastify/multipart` file, constrained by `options` and emitted as `format: 'binary'`. */\nexport const fastifyMultipartFile = (\n options?: FastifyMultipartFileOptions,\n): z.ZodType<FastifyMultipartFileLike, FastifyMultipartFileLike> =>\n buildFileSchema<FastifyMultipartFileLike>({\n predicate: isFastifyMultipartFile,\n accessors,\n options,\n });\n\n/** Unconstrained {@link fastifyMultipartFile}, for shapes that need no per-field checks. */\nexport const FastifyMultipartFileSchema = fastifyMultipartFile();\n\n/**\n * Declares an endpoint's whole `multipart/form-data` body. Defaults to\n * `filesIn: 'body'` — register `@fastify/multipart` with\n * `attachFieldsToBody: true` so files arrive there alongside the text fields.\n *\n * There is no `@ZodUploadedFile` on this entry point: with the files in the\n * body, `@ZodMultipartBody()` already covers them.\n */\nexport const ZodMultipart = createZodMultipart(MultipartFilesIn.Body);\n\nexport { ZodMultipartBody } from '../multipart/param-decorators.js';\nexport { MULTIPART_CONTENT_TYPE } from '../multipart/zod-multipart.decorator.js';\nexport type { ZodMultipartOptions } from '../multipart/zod-multipart.decorator.js';\nexport type { MultipartShape } from '../multipart/metadata.js';\n"]}