zod-nest 2.0.1 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +15 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.js +49 -5
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +49 -5
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/schema/constants.ts","../src/schema/discover-dependents.ts","../src/schema/registry.ts","../src/schema/composition.ts","../src/schema/custom-override.ts","../src/schema/errors.ts","../src/schema/override.ts","../src/schema/post-process.ts","../src/schema/engine.ts","../src/dto/marker.ts","../src/dto/symbols.ts","../src/dto/output-dto.ts","../src/dto/create-zod-dto.ts","../src/dto/predicates.ts","../src/exceptions/serialization.exception.ts","../src/exceptions/validation.exception.ts","../src/logging/validation-logger.ts","../src/response/stream.ts","../src/module/options.ts","../src/pipes/validation.pipe.ts","../src/response/default-status.ts","../src/response/metadata.ts","../src/schema/anon-id.ts","../src/response/normalize-type.ts","../src/decorators/zod-response.swagger-bridge.ts","../src/decorators/zod-response.decorator.ts","../src/decorators/internal/zod-schema-ref.ts","../src/decorators/internal/zod-param-expand.ts","../src/decorators/internal/flatten-intersection.ts","../src/decorators/zod-body.decorator.ts","../src/decorators/internal/query-marker.ts","../src/decorators/zod-query.decorator.ts","../src/decorators/internal/constants.ts","../src/decorators/zod-headers.decorator.ts","../src/decorators/zod-cookies.decorator.ts","../src/interceptors/serializer.interceptor.ts","../src/module/zod-nest.module.ts","../src/document/bulk-emit.ts","../src/document/http-methods.ts","../src/document/walk-refs.ts","../src/document/collect-usage.ts","../src/document/errors.ts","../src/document/dangling-refs.ts","../src/document/expand-param-markers.ts","../src/document/expose-closure.ts","../src/document/constants.ts","../src/document/inline-anon.ts","../src/document/merge-schemas.ts","../src/document/rewrite-refs.ts","../src/document/strip-markers.ts","../src/document/apply-zod-nest.ts"],"names":["COMPONENTS_SCHEMAS_PREFIX","DEFS_PREFIX","ZOD_NEST_ERROR_EXTENSION","ZOD_NEST_ERROR_DUPLICATE_ID","ZOD_NEST_DTO_EXTENSION","INNER_TYPE_WRAPPERS","Set","readId","schema","meta","z","globalRegistry","get","undefined","id","collectChildren","def","_zod","type","out","shape","value","Object","values","push","catchall","element","options","map","opt","left","right","items","it","rest","keyType","valueType","in","getter","has","innerType","discoverDependents","visited","WeakSet","stack","length","current","pop","add","child","createRegistry","seen","Map","forceExposed","anonymous","recordOnce","set","zodRegistry","register","flags","expose","existing","childId","hasCollision","size","getCollisions","ids","keys","forceExposedIds","anonymousIds","defaultRegistry","registerSchema","registry","explicit","metaId","lineageMap","WeakMap","propsMap","OPTIONAL_WRAPPER_TYPES","isOptionalProp","propSchema","computeShapeKeys","properties","required","filter","key","extend","parent","build","result","op","getLineage","DEFAULT_BUILD_REF","createCompositionOverride","opts","buildRef","ctx","jsonSchema","zodSchema","entry","parentCache","parentId","childProps","childRequired","parentPropSet","parentReqSet","deltaProps","entries","deltaRequired","delta","additionalProperties","allOf","$ref","unevaluatedProperties","customOverrideMap","isWrapper","arg","overrideJSONSchema","overrideSchema","input","output","schemaDescription","description","peekRegistration","createCustomOverride","io","record","fragment","Reflect","deleteProperty","assign","ZodNestError","Error","message","name","ZodNestUnrepresentableError","path","zodType","formatPath","String","join","primitiveOverride","format","combine","overrides","list","candidate","o","rewriteRefs","node","selfRef","Array","isArray","item","obj","ref","startsWith","slice","postProcess","raw","refs","rawDefs","$defs","body","root","$schema","STRICT_REQUIRES_OVERRIDE","isStrictlyUnrepresentable","markPipeCoverage","covered","target","traits","buildToJsonSchemaOptions","params","strict","compositionOverride","uri","customOverride","merged","override","unrepresentableHits","coveredByPipe","wrapped","unrepresentable","metadata","cycles","reused","consumeUnrepresentable","firstHit","find","hit","toOpenApi","built","toJSONSchema","makeZodDtoMarker","dtoId","__zodNestDto","isZodDtoMarker","ZOD_DTO_SYMBOL","Symbol","for","outputCache","buildSiblingClass","SiblingClass","Output","parse","safeParse","_OPENAPI_METADATA_FACTORY","defineProperty","configurable","resolveOutput","cached","sibling","anonCounter","warnedOnAnonymous","resolveFallbackId","className","fallback","console","warn","createZodDto","cachedId","ensureRegistered","named","ZodDtoBase","isZodDto","isZodSchema","ZodType","ZodSerializationException","InternalServerErrorException","zodError","executionContext","statusCode","HttpStatus","INTERNAL_SERVER_ERROR","cause","ZodValidationException","BadRequestException","argMetadata","BAD_REQUEST","errors","treeifyError","DEFAULT_LOGGER_CONTEXT","REDACTED","PREVIEW_RESERVE_BYTES","noopLogValidationFailure","isPlainRecord","CIRCULAR","redactValue","redactSet","toLowerCase","capLoggedValue","maxBytes","serialized","JSON","stringify","_truncated","_originalBytes","_reason","byteSize","Buffer","byteLength","previewBudget","Math","max","_preview","loggerContextFor","side","messageFor","createValidationLogger","redactKeys","logger","err","redacted","sized","maxLoggedValueBytes","payload","dto","status","handler","argType","loggerContext","severity","error","DEFAULT_CONTENT_TYPE","DEFAULT_STREAM_CONTENT_TYPES","PREFIX_WILDCARD_SUFFIX","normalizeContentType","contentType","semicolonIndex","indexOf","mediaType","trim","normalizeStreamMatcher","contentTypes","exact","prefixes","normalized","endsWith","DEFAULT_STREAM_MATCHER","matchesStream","matcher","prefix","isHeaderEntry","headerContentType","headers","getMetadata","HEADERS_METADATA","resolveContentType","variant","fromHeader","isStreamResponse","stream","DEFAULT_REDACT_KEYS","DEFAULT_MAX_LOGGED_VALUE_BYTES","ZOD_NEST_OPTIONS","resolveLogFlags","validationLogs","normalizeZodNestOptions","Logger","loggerOpts","streamMatcher","streamContentTypes","createValidationException","createSerializationException","logInputFailure","logOutputFailure","isOptionsObject","defaultExceptionFactory","ZodValidationPipe","explicitSchema","explicitDtoName","moduleOptions","parsed","parseArg","dtoName","factory","transform","resolveSchema","safeParseAsync","success","data","resolveDtoLabel","metatype","optionSchema","resolvedSchema","POST_DEFAULT_STATUS","GENERIC_DEFAULT_STATUS","defaultStatusFor","httpCode","HTTP_CODE_METADATA","method","METHOD_METADATA","RequestMethod","POST","resolveEffectiveStatus","ZOD_RESPONSES_METADATA_KEY","appendResponseVariant","defineMetadata","ANON_RESPONSE_PREFIX","ANON_BODY_PREFIX","anonIdCache","counter","resolveAnonId","responseDtoCache","schemaToOutputDto","namedId","anonId","toResponseDto","index","where","TypeError","extractDescriptionFields","desc","links","asDtoFunction","buildApiResponseOptions","base","buildTupleSchema","dtos","prefixItems","d","getSchemaPath","buildContentResponseOptions","content","applyCustomContentResponse","propertyKey","descriptor","kind","ApiExtraModels","ApiResponse","applySwaggerResponseDecorator","effectiveStatus","effectiveContentType","buildArrayKind","headEntry","restEntries","head","validationSchema","array","tupleSchemas","tuple","buildKind","normaliseStatus","ZodResponse","passthroughOnError","swaggerDescriptor","queueMicrotask","resolveSchemaRef","deferAnonInline","isZodObject","expandObjectSchema","decoratorName","resolution","forceRequired","paramSchemaBody","intersectionArms","unionOptions","collectObjectShapes","shapes","unionCrossed","allShapes","variantResult","arms","flattenObjectIntersection","collected","mergedShape","optional","object","ZodBody","apiBodySchema","resolveBodySchema","ApiBody","flatten","API_PARAMETERS_METADATA_KEY","appendQueryMarker","_target","_propertyKey","marker","ZodQuery","expanded","applyDecorators","ApiQuery","API_PARAMETERS_KEY","ZodHeaders","newEntries","ZodCookies","defaultSerializationFactory","formatDtoLabel","formatHandlerLabel","context","getClass","getHandler","matchesWildcard","wildcard","charCodeAt","floor","selectVariant","variants","effective","ZodSerializerInterceptor","reflector","intercept","next","getType","handle","pipe","mergeMap","from","response","switchToHttp","getResponse","isSoft","ZodNestModule","forRoot","module","global","providers","provide","useValue","APP_PIPE","useClass","APP_INTERCEPTOR","exports","URI","bulkEmit","knownIds","inputSchemas","runPass","outputSchemas","filtered","schemas","HTTP_METHODS","forEachOperation","doc","fn","paths","pathItem","pathRecord","walkRefs","visit","collectUsage","classToDtoId","buildClassToDtoIdMap","inputExposedIds","collectInputExposedIds","outputExposedIds","collectOutputExposedIds","components","readMarker","operation","operationsOf","collectRefsFromOperation","requestBody","collectRefsFromContent","parameters","param","collectRefFromSchema","collectIdFromMarkerParam","renamed","collectRefsFromResponses","responses","ZodNestDocumentError","code","details","assertNoDanglingRefs","dangling","lines","hintFor","usedInput","usedOutput","expandParamMarkers","queryParamStyle","componentIds","expandedAny","expandParameterList","pruneOrphanObjectSchema","i","resolveMarker","useRef","buildRefQueryParam","expandOne","style","explode","capitalize","requiredSet","collectRequired","propName","propSchemaRaw","buildParameter","effectiveRequired","charAt","toUpperCase","prototype","hasOwnProperty","call","referenced","targetRef","extendExposureViaRefs","closeOverRefs","seed","bodies","queue","shift","OUTPUT_SUFFIX","inlineAnonymousBodies","anonIds","bodyByRef","inlineRefs","structuredClone","mergeSchemas","collisions","ensureComponentsSchemas","renames","divergentOutputIds","exposedIds","applyTruthTable","applyCollisionDecoration","inputExposed","outputExposed","inputBody","outputBody","writeOrThrowAmbiguous","canonicalEqual","isMarkerPlaceholder","a","b","decorateIfPresent","replace","rewriteResponseSubtree","stripMarkers","stripMarkerFromSchema","dropJsonSchemaMetadata","stripMarkerParameters","$id","props","withForcedExposure","forced","OPENAPI_VERSION","applyZodNest","exposed","extended","openapi"],"mappings":";;;;;;;;;;;;;AACO,IAAMA,yBAAAA,GAA4B;AAGlC,IAAMC,WAAAA,GAAc,UAAA;AAGpB,IAAMC,wBAAAA,GAA2B;AAGjC,IAAMC,2BAAAA,GAA8B;AAQpC,IAAMC,sBAAAA,GAAyB;ACdtC,IAAMC,mBAAAA,uBAA0BC,GAAAA,CAAI;AAClC,EAAA,UAAA;AACA,EAAA,UAAA;AACA,EAAA,SAAA;AACA,EAAA,UAAA;AACA,EAAA,OAAA;AACA,EAAA,aAAA;AACA,EAAA,SAAA;AACA,EAAA,UAAA;AACA,EAAA;AACD,CAAA,CAAA;AAED,IAAMC,MAAAA,2BAAUC,MAAAA,KAAAA;AACd,EAAA,MAAMC,IAAAA,GAAOC,CAAAA,CAAEC,cAAAA,CAAe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,IAAAA,YAAAA;AACAE,IAAAA,aAAAA;IACAhE,SAAAA,EAAWgL,QAAAA;AACX9B,IAAAA,UAAAA,EAAYnf,SAASP,aAAAA;GACvB,CAAA;AACAkd,EAAAA,kBAAAA,CAAmB;AAAErC,IAAAA,GAAAA;AAAKP,IAAAA,YAAAA;AAAcE,IAAAA,aAAAA;AAAe2C,IAAAA,eAAAA,EAAiBtb,IAAAA,CAAKsb;GAAgB,CAAA;AAC7FhY,EAAAA,YAAAA,CAAY;AAAE0V,IAAAA,GAAAA;AAAK+E,IAAAA,OAAAA;AAASC,IAAAA;GAAmB,CAAA;AAC/CgB,EAAAA,YAAAA,CAAahG,GAAAA,CAAAA;AACbuE,EAAAA,qBAAAA,CAAsB;AAAEvE,IAAAA,GAAAA;AAAKta,IAAAA;GAAS,CAAA;AACtCqc,EAAAA,oBAAAA,CAAqB;AAAE/B,IAAAA,GAAAA;IAAKrE,SAAAA,EAAWgL;GAAS,CAAA;AAChD3G,EAAAA,GAAAA,CAAI4G,OAAAA,GAAUJ,eAAAA;AAEd,EAAA,OAAOxG,GAAAA;AACT,CAAA,EA5B4B,cAAA","file":"index.mjs","sourcesContent":["/** OpenAPI 3.1 `$ref` prefix for entries in `components.schemas`. */\nexport const COMPONENTS_SCHEMAS_PREFIX = '#/components/schemas/';\n\n/** JSON Schema `$ref` prefix for entries in `$defs` (single-schema emission). */\nexport const DEFS_PREFIX = '#/$defs/';\n\n/** OpenAPI extension key zod-nest uses to surface engine errors inside emitted schemas. */\nexport const ZOD_NEST_ERROR_EXTENSION = 'x-zod-nest-error';\n\n/** Value of `x-zod-nest-error` when a registry id is claimed by more than one schema. */\nexport const ZOD_NEST_ERROR_DUPLICATE_ID = 'duplicate-id';\n\n/**\n * OpenAPI extension key used by `createZodDto` to mark a class for `applyZodNest`.\n * The marker carries `{ __zodNestDto: true, dtoId, io }` so `applyZodNest` can\n * locate every zod-nest DTO in the @nestjs/swagger document and inject the\n * real Zod-derived schema.\n */\nexport const ZOD_NEST_DTO_EXTENSION = 'x-zod-nest-dto';\n","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\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 [def.getter() as unknown as z.ZodType];\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","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\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 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 // `discoverDependents` walks the Zod tree once and yields every named\n // descendant transitively (cycle-safe via its own visited set).\n for (const [child, childId] of discoverDependents(schema)) {\n recordOnce(child, childId);\n }\n },\n hasCollision: (id) => {\n const set = seen.get(id);\n return set !== undefined && set.size > 1;\n },\n getCollisions: () => {\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: () => [...seen.keys()],\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\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 * 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, { op: 'extend', parent });\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 if (parentPropSet.has(key)) {\n continue;\n }\n deltaProps[key] = value;\n }\n const deltaRequired = childRequired.filter((key) => !parentReqSet.has(key));\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","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","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';\n\nexport interface PostProcessResult {\n schema: SchemaObject;\n refs: Map<string, SchemaObject>;\n}\n\nconst rewriteRefs = (node: unknown, selfRef: string | undefined): void => {\n if (Array.isArray(node)) {\n for (const item of node) {\n rewriteRefs(item, selfRef);\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 === '#' && selfRef !== undefined) {\n // Zod emits '#' for cycle refs back to the document root. When we lift a\n // named schema into its own components.schemas entry, '#' should resolve\n // to that entry's own URI.\n obj.$ref = selfRef;\n }\n for (const value of Object.values(obj)) {\n rewriteRefs(value, selfRef);\n }\n};\n\nexport const postProcess = (raw: SchemaObject): 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 root: SchemaObject = { ...raw };\n delete root.$schema;\n delete root.$defs;\n\n // Root has no own self-uri at the 2a level. If the root is a bare `$ref` to a\n // lifted named schema (the common case when input itself has `.meta({ id })`),\n // we'll have already rewritten it to '#/components/schemas/<id>'.\n rewriteRefs(root, undefined);\n\n for (const [id, body] of refs) {\n rewriteRefs(body, `${COMPONENTS_SCHEMAS_PREFIX}${id}`);\n }\n\n return { schema: root, 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\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).length === 0;\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\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\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 { Io } from './dto.types.js';\n\n/**\n * Payload of the `x-zod-nest-dto` placeholder property that\n * `_OPENAPI_METADATA_FACTORY` returns. `applyZodNest` reads this off\n * each `components.schemas.<DtoName>.properties[x-zod-nest-dto]` entry,\n * uses `dtoId` to look up the schema in the registry, and replaces the\n * synthetic schema body with the real Zod-derived schema.\n *\n * `type` and `required` are benign filler that satisfy @nestjs/swagger's\n * property-type guard (without them, the explorer throws \"A circular\n * dependency has been detected\"). They have no semantic meaning and are\n * stripped along with the rest of the marker by `applyZodNest`.\n */\nexport interface ZodDtoMarker {\n readonly type: () => typeof Object;\n readonly required: false;\n readonly __zodNestDto: true;\n readonly dtoId: string;\n readonly io: Io;\n}\n\nexport const makeZodDtoMarker = (dtoId: string, io: Io): ZodDtoMarker => ({\n type: () => Object,\n required: false,\n __zodNestDto: true,\n dtoId,\n io,\n});\n\nexport const isZodDtoMarker = (value: unknown): value is ZodDtoMarker => {\n if (value === null || typeof value !== 'object') {\n return false;\n }\n return (value as { __zodNestDto?: unknown }).__zodNestDto === true;\n};\n","/** Runtime tag placed on every class returned by `createZodDto`. */\nexport const ZOD_DTO_SYMBOL: unique symbol = Symbol.for('zod-nest.dto');\n","import type { z } from 'zod';\nimport type { Io, ZodDto } from './dto.types.js';\n\nimport { ZOD_NEST_DTO_EXTENSION } from '../schema/constants.js';\nimport { makeZodDtoMarker } from './marker.js';\nimport { ZOD_DTO_SYMBOL } from './symbols.js';\n\n/**\n * Cache of `parent -> output-sibling` so repeated reads of `Dto.Output` return\n * the same class instance. WeakMap so the sibling can be GC'd if the parent is.\n */\nconst outputCache = new WeakMap<ZodDto<z.ZodType>, ZodDto<z.ZodType>>();\n\n/**\n * `.Output` is always a distinct sibling class — it carries `io: 'output'` so\n * `applyZodNest` can run the output-side emission and apply the\n * suffix truth table (`Foo` alone vs `Foo` + `FooOutput`) based on actual JSON\n * Schema equality at doc-build time. The earlier \"return self when io-identical\"\n * optimization was dropped because `z.object()` already diverges at the JSON\n * Schema level (input is permissive, output sets `additionalProperties: false`),\n * which would have made the sibling reused only for non-object roots — not\n * worth the implementation complexity.\n */\nconst buildSiblingClass = <TSchema extends z.ZodType>(\n parent: ZodDto<TSchema>,\n schema: TSchema,\n): ZodDto<TSchema> => {\n const SiblingClass = class {\n static readonly schema = schema;\n static readonly io: Io = 'output';\n static readonly [ZOD_DTO_SYMBOL] = true as const;\n\n static get id(): string {\n return parent.id;\n }\n\n static get Output(): ZodDto<TSchema> {\n return this as unknown as ZodDto<TSchema>;\n }\n\n static parse(input: unknown): z.infer<TSchema> {\n return schema.parse(input) as z.infer<TSchema>;\n }\n\n static safeParse(input: unknown): z.ZodSafeParseResult<z.infer<TSchema>> {\n return schema.safeParse(input) as z.ZodSafeParseResult<z.infer<TSchema>>;\n }\n\n static _OPENAPI_METADATA_FACTORY(): Record<string, unknown> {\n return { [ZOD_NEST_DTO_EXTENSION]: makeZodDtoMarker(parent.id, 'output') };\n }\n };\n // `@nestjs/swagger` keys `components.schemas` by the class's `.name`. Every\n // sibling produced here is the same anonymous `class` expression, so they all\n // report `\"SiblingClass\"` and would collapse into one component when more than\n // one `.Output` DTO is used across responses. Pin the name to the parent id so\n // distinct DTOs register distinctly. A getter keeps id resolution lazy (the\n // parent id may not be resolvable until the schema is first registered).\n Object.defineProperty(SiblingClass, 'name', { get: () => parent.id, configurable: true });\n return SiblingClass as unknown as ZodDto<TSchema>;\n};\n\nexport const resolveOutput = <TSchema extends z.ZodType>(\n parent: ZodDto<TSchema>,\n schema: TSchema,\n): ZodDto<TSchema> => {\n const cached = outputCache.get(parent as ZodDto<z.ZodType>);\n if (cached !== undefined) {\n return cached as ZodDto<TSchema>;\n }\n const sibling = buildSiblingClass(parent, schema);\n outputCache.set(parent as ZodDto<z.ZodType>, sibling as ZodDto<z.ZodType>);\n return sibling;\n};\n","import type { z } from 'zod';\nimport type { ZodNestRegistry } from '../schema/registry.js';\nimport type { CreateZodDtoOptions, Io, ZodDto } from './dto.types.js';\n\nimport { ZOD_NEST_DTO_EXTENSION } from '../schema/constants.js';\nimport { defaultRegistry, registerSchema } from '../schema/registry.js';\nimport { makeZodDtoMarker } from './marker.js';\nimport { resolveOutput } from './output-dto.js';\nimport { ZOD_DTO_SYMBOL } from './symbols.js';\n\nlet anonCounter = 0;\nlet warnedOnAnonymous = false;\n\nconst resolveFallbackId = (className: string): string => {\n if (className !== '' && className.length > 1) {\n return className;\n }\n anonCounter += 1;\n const fallback = `_AnonZodDto_${anonCounter}`;\n if (!warnedOnAnonymous) {\n warnedOnAnonymous = true;\n // eslint-disable-next-line no-console\n console.warn(\n `[zod-nest] Could not resolve a DTO id from class name (got \"${className}\"). ` +\n `Using \"${fallback}\". Set an explicit id via \\`schema.meta({ id: 'Foo' })\\` ` +\n `(preferred) or \\`createZodDto(schema, { id: 'Foo' })\\` — important under ` +\n `minification, where class names become single mangled characters.`,\n );\n }\n return fallback;\n};\n\nexport const createZodDto = <TSchema extends z.ZodType>(\n schema: TSchema,\n options?: CreateZodDtoOptions,\n): ZodDto<TSchema> => {\n const registry: ZodNestRegistry = options?.registry ?? defaultRegistry;\n const io: Io = 'input';\n let cachedId: string | undefined;\n\n const ensureRegistered = (className: string): string => {\n if (cachedId !== undefined) {\n return cachedId;\n }\n // `registerSchema` resolves explicit id → `.meta({ id })`. When both miss,\n // fall back to the DTO-specific className → anonymous-counter chain\n // (with one-time minification warning).\n const named = registerSchema(schema, registry, { id: options?.id, expose: options?.expose });\n if (named !== undefined) {\n cachedId = named;\n return cachedId;\n }\n cachedId = resolveFallbackId(className);\n registry.register(schema, cachedId, { expose: options?.expose });\n return cachedId;\n };\n\n const ZodDtoBase = class {\n static readonly schema = schema;\n static readonly io: Io = io;\n static readonly [ZOD_DTO_SYMBOL] = true as const;\n\n static get id(): string {\n return ensureRegistered(this.name);\n }\n\n static get Output(): ZodDto<TSchema> {\n return resolveOutput(this as unknown as ZodDto<TSchema>, schema);\n }\n\n static parse(input: unknown): z.infer<TSchema> {\n return schema.parse(input) as z.infer<TSchema>;\n }\n\n static safeParse(input: unknown): z.ZodSafeParseResult<z.infer<TSchema>> {\n return schema.safeParse(input) as z.ZodSafeParseResult<z.infer<TSchema>>;\n }\n\n static _OPENAPI_METADATA_FACTORY(): Record<string, unknown> {\n return { [ZOD_NEST_DTO_EXTENSION]: makeZodDtoMarker(ensureRegistered(this.name), io) };\n }\n };\n\n return ZodDtoBase as unknown as ZodDto<TSchema>;\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 { HttpStatus, InternalServerErrorException } from '@nestjs/common';\n\nimport type { ExecutionContext } from '@nestjs/common';\nimport type { z } from 'zod';\n\n/**\n * Default exception thrown by `ZodSerializerInterceptor` in strict mode\n * (i.e. when `@ZodResponse({ passthroughOnError: true })` is NOT set) on\n * response-validation failure.\n *\n * Body shape (returned by `getResponse()`):\n * ```\n * {\n * statusCode: 500,\n * message: 'Response validation failed',\n * }\n * ```\n *\n * The zod error tree is **deliberately not exposed in the response body** —\n * a serialization failure is a server-side contract violation, and leaking\n * the schema-shape error tree to clients discloses internal structure. The\n * full treeified error is logged through `ZodNestModule`'s validation-log\n * channel (with redaction + truncation) so operators get the diagnostic\n * information without it reaching the wire.\n *\n * Custom exception filters can still introspect the failure: `zodError` and\n * `executionContext` are kept as own properties on the instance.\n */\nexport class ZodSerializationException extends InternalServerErrorException {\n readonly zodError: z.ZodError;\n readonly executionContext?: ExecutionContext;\n\n constructor(zodError: z.ZodError, executionContext?: ExecutionContext) {\n super(\n {\n statusCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'Response validation failed',\n },\n { cause: zodError },\n );\n this.zodError = zodError;\n this.executionContext = executionContext;\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 { z } from 'zod';\n\nimport type { LoggerService } from '@nestjs/common';\n\nexport const DEFAULT_LOGGER_CONTEXT = 'ZodValidation';\nconst REDACTED = '[REDACTED]';\nconst PREVIEW_RESERVE_BYTES = 100;\n\nexport interface ValidationLogContext {\n /** Which side of the request emitted the failure. */\n side: 'input' | 'output';\n /** Severity to log at; the formatter does not decide this. */\n severity: 'warn' | 'error';\n /** Pre-formatted DTO label, e.g. `'UserDto'`, `'[UserDto]'`, `'[A, B]'`. */\n dto: string;\n /** Output side only — HTTP response status code. */\n status?: number;\n /** Output side only — `Controller.method` best-effort. */\n handler?: string;\n /** Input side only — `body` / `query` / `param` / `custom`. */\n argType?: string;\n}\n\nexport interface ValidationLoggerOptions {\n logger: LoggerService;\n redactKeys: readonly string[];\n maxLoggedValueBytes: number;\n}\n\nexport type LogValidationFailure = (\n err: z.ZodError,\n value: unknown,\n ctx: ValidationLogContext,\n) => void;\n\nexport const noopLogValidationFailure: LogValidationFailure = () => {};\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n\nconst CIRCULAR = '[CIRCULAR]';\n\nconst redactValue = (\n value: unknown,\n redactSet: ReadonlySet<string>,\n seen: WeakSet<object> = new WeakSet(),\n): unknown => {\n if (Array.isArray(value)) {\n if (seen.has(value)) {\n return CIRCULAR;\n }\n seen.add(value);\n return value.map((item) => redactValue(item, redactSet, seen));\n }\n if (!isPlainRecord(value)) {\n return value;\n }\n if (seen.has(value)) {\n return CIRCULAR;\n }\n seen.add(value);\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n if (redactSet.has(key.toLowerCase())) {\n out[key] = REDACTED;\n continue;\n }\n out[key] = redactValue(value[key], redactSet, seen);\n }\n return out;\n};\n\nconst capLoggedValue = (value: unknown, maxBytes: number): unknown => {\n let serialized: string | undefined;\n try {\n serialized = JSON.stringify(value);\n } catch {\n return { _truncated: true, _originalBytes: -1, _reason: 'unserializable' };\n }\n if (serialized === undefined) {\n return value;\n }\n const byteSize = Buffer.byteLength(serialized, 'utf8');\n if (byteSize <= maxBytes) {\n return value;\n }\n const previewBudget = Math.max(0, maxBytes - PREVIEW_RESERVE_BYTES);\n return {\n _truncated: true,\n _originalBytes: byteSize,\n _preview: serialized.slice(0, previewBudget),\n };\n};\n\nconst loggerContextFor = (side: 'input' | 'output'): string =>\n side === 'output' ? 'ZodSerializerInterceptor' : 'ZodValidationPipe';\n\nconst messageFor = (side: 'input' | 'output'): string =>\n side === 'output' ? 'Response validation failed' : 'Request validation failed';\n\nexport const createValidationLogger = (opts: ValidationLoggerOptions): LogValidationFailure => {\n const redactSet = new Set(opts.redactKeys.map((key) => key.toLowerCase()));\n const { logger } = opts;\n\n return (err, value, ctx) => {\n const redacted = redactValue(value, redactSet);\n const sized = capLoggedValue(redacted, opts.maxLoggedValueBytes);\n const payload: Record<string, unknown> = {\n message: messageFor(ctx.side),\n side: ctx.side,\n dto: ctx.dto,\n errors: z.treeifyError(err),\n value: sized,\n };\n if (ctx.status !== undefined) {\n payload.status = ctx.status;\n }\n if (ctx.handler !== undefined) {\n payload.handler = ctx.handler;\n }\n if (ctx.argType !== undefined) {\n payload.argType = ctx.argType;\n }\n const loggerContext = loggerContextFor(ctx.side);\n if (ctx.severity === 'error') {\n logger.error(payload, undefined, loggerContext);\n return;\n }\n logger.warn(payload, loggerContext);\n };\n};\n","import { HEADERS_METADATA } from '@nestjs/common/constants.js';\n\nimport type { ResponseVariant } from './metadata.js';\n\n/**\n * Media type assumed when `@ZodResponse` declares no `contentType`. Responses\n * at this type carry the standard JSON-validated body and flow through the\n * unchanged `type` / `isArray` swagger path in `applySwaggerResponseDecorator`.\n */\nexport const DEFAULT_CONTENT_TYPE = 'application/json';\n\n/**\n * Content types whose bodies zod-nest treats as streams by default: the\n * handler writes them straight to the response buffer (SSE, NDJSON, raw\n * binary, files), so `ZodSerializerInterceptor` skips validation and the\n * OpenAPI media-type key becomes the stream type rather than `application/json`.\n *\n * A trailing `/*` marks a family prefix — `image/*` matches `image/png`,\n * `image/jpeg`, … — everything else matches exactly. Consumers extend this set\n * *additively* via `ZodNestModuleOptions.streamContentTypes`; the defaults are\n * always retained so SSE / NDJSON detection can't be accidentally dropped.\n */\nexport const DEFAULT_STREAM_CONTENT_TYPES: readonly string[] = [\n 'text/event-stream',\n 'application/x-ndjson',\n 'application/octet-stream',\n 'application/pdf',\n 'image/*',\n 'audio/*',\n 'video/*',\n];\n\n/**\n * Normalised stream-content-type matcher: exact media types in a `Set` for\n * O(1) lookup, family prefixes (`image/`, …) checked with `startsWith`. Built\n * once by `normalizeStreamMatcher` from the default list (decoration time) or\n * the default ∪ module-configured list (runtime).\n */\nexport interface StreamContentTypeMatcher {\n exact: ReadonlySet<string>;\n prefixes: readonly string[];\n}\n\nconst PREFIX_WILDCARD_SUFFIX = '/*';\n\n/**\n * Lowercase a content type and drop any `;`-delimited parameters\n * (`text/event-stream; charset=utf-8` → `text/event-stream`).\n */\nconst normalizeContentType = (contentType: string): string => {\n const semicolonIndex = contentType.indexOf(';');\n const mediaType = semicolonIndex === -1 ? contentType : contentType.slice(0, semicolonIndex);\n return mediaType.trim().toLowerCase();\n};\n\nexport const normalizeStreamMatcher = (\n contentTypes: readonly string[],\n): StreamContentTypeMatcher => {\n const exact = new Set<string>();\n const prefixes: string[] = [];\n for (const entry of contentTypes) {\n const normalized = normalizeContentType(entry);\n if (normalized.endsWith(PREFIX_WILDCARD_SUFFIX)) {\n // 'image/*' → 'image/' so `startsWith('image/')` matches the family.\n prefixes.push(normalized.slice(0, normalized.length - 1));\n continue;\n }\n if (normalized.endsWith('/')) {\n prefixes.push(normalized);\n continue;\n }\n exact.add(normalized);\n }\n return { exact, prefixes };\n};\n\n/** Default matcher used at decoration time, where module options aren't yet available. */\nexport const DEFAULT_STREAM_MATCHER: StreamContentTypeMatcher = normalizeStreamMatcher(\n DEFAULT_STREAM_CONTENT_TYPES,\n);\n\nexport const matchesStream = (contentType: string, matcher: StreamContentTypeMatcher): boolean => {\n const normalized = normalizeContentType(contentType);\n if (matcher.exact.has(normalized)) {\n return true;\n }\n for (const prefix of matcher.prefixes) {\n if (normalized.startsWith(prefix)) {\n return true;\n }\n }\n return false;\n};\n\ninterface HeaderMetadataEntry {\n name: string;\n value: unknown;\n}\n\nconst isHeaderEntry = (value: unknown): value is HeaderMetadataEntry => {\n if (value === null || typeof value !== 'object') {\n return false;\n }\n return 'name' in value && typeof value.name === 'string';\n};\n\n/**\n * Read the `Content-Type` value declared via `@Header('Content-Type', …)` on a\n * handler. NestJS stores `[{ name, value }]` under `HEADERS_METADATA`; thunk\n * values (`@Header('Content-Type', () => …)`) are ignored — only literal\n * strings can be resolved statically.\n */\nconst headerContentType = (handler: object): string | undefined => {\n const headers = Reflect.getMetadata(HEADERS_METADATA, handler);\n if (!Array.isArray(headers)) {\n return undefined;\n }\n for (const entry of headers) {\n if (!isHeaderEntry(entry)) {\n continue;\n }\n if (entry.name.toLowerCase() !== 'content-type') {\n continue;\n }\n if (typeof entry.value !== 'string') {\n continue;\n }\n return entry.value;\n }\n return undefined;\n};\n\n/**\n * Resolve the effective response content type for a variant. Precedence:\n * 1. explicit `contentType` option (returned verbatim);\n * 2. a `@Header('Content-Type', …)` value, but only when it matches a known\n * stream type (so an arbitrary header doesn't silently rewrite the doc);\n * 3. `application/json`.\n */\nexport const resolveContentType = (\n variant: ResponseVariant,\n handler: object,\n matcher: StreamContentTypeMatcher,\n): string => {\n if (variant.contentType !== undefined) {\n return variant.contentType;\n }\n const fromHeader = headerContentType(handler);\n if (fromHeader !== undefined && matchesStream(fromHeader, matcher)) {\n return normalizeContentType(fromHeader);\n }\n return DEFAULT_CONTENT_TYPE;\n};\n\n/**\n * Whether a response variant should be treated as a stream — i.e. written\n * directly to the buffer and *not* validated. Explicit `stream` wins; otherwise\n * the effective content type is matched against the known stream set.\n */\nexport const isStreamResponse = (\n variant: ResponseVariant,\n handler: object,\n matcher: StreamContentTypeMatcher,\n): boolean => {\n if (variant.stream !== undefined) {\n return variant.stream;\n }\n return matchesStream(resolveContentType(variant, handler, matcher), matcher);\n};\n","import { Logger } from '@nestjs/common';\n\nimport type { ArgumentMetadata, ExecutionContext, LoggerService } from '@nestjs/common';\nimport type { z } from 'zod';\nimport type { LogValidationFailure } from '../logging/validation-logger.js';\nimport type { StreamContentTypeMatcher } from '../response/stream.js';\n\nimport {\n createValidationLogger,\n DEFAULT_LOGGER_CONTEXT,\n noopLogValidationFailure,\n} from '../logging/validation-logger.js';\nimport { DEFAULT_STREAM_CONTENT_TYPES, normalizeStreamMatcher } from '../response/stream.js';\n\n/**\n * Module-scope factory for the exception thrown by `ZodValidationPipe` on\n * input validation failure. Mirrors the existing per-pipe option but lives\n * at module scope; per-instance constructor arg wins.\n */\nexport type CreateValidationException = (err: z.ZodError, argMetadata: ArgumentMetadata) => unknown;\n\n/**\n * Module-scope factory for the exception thrown by `ZodSerializerInterceptor`\n * on output validation failure (strict mode only). Soft mode never calls\n * this factory.\n */\nexport type CreateSerializationException = (\n err: z.ZodError,\n executionContext: ExecutionContext,\n) => unknown;\n\n/** Public options accepted by `ZodNestModule.forRoot()`. */\nexport interface ZodNestModuleOptions {\n createValidationException?: CreateValidationException;\n createSerializationException?: CreateSerializationException;\n /**\n * Failure-only validation logging. `true` enables both input and output;\n * the granular form lets each side be toggled independently. Default: off.\n */\n validationLogs?: boolean | { input?: boolean; output?: boolean };\n /** Override Nest's built-in `Logger` (e.g. pino/winston adapter). */\n logger?: LoggerService;\n /**\n * Keys whose values get scrubbed from logged input/response objects.\n * Matched case-insensitively at any depth. Supplying this option\n * REPLACES the default list (no merge).\n */\n redactKeys?: readonly string[];\n /**\n * Maximum size in bytes (UTF-8) for any single logged value. Oversized\n * values become `{ _truncated: true, _originalBytes, _preview }`.\n */\n maxLoggedValueBytes?: number;\n /**\n * Additional response content types treated as streams — written directly\n * to the response buffer and never validated by `ZodSerializerInterceptor`.\n * MERGED with the built-in `DEFAULT_STREAM_CONTENT_TYPES` (SSE, NDJSON,\n * octet-stream, pdf, `image/*`, `audio/*`, `video/*`), so the defaults are\n * always retained. A trailing `/*` entry matches a media-type family.\n */\n streamContentTypes?: readonly string[];\n}\n\n/**\n * Resolved options consumed by pipe + interceptor. `forRoot()` builds this\n * once and stuffs it into a provider for the `ZOD_NEST_OPTIONS` injection\n * token; downstream code never re-checks the raw `validationLogs` flag.\n */\nexport interface NormalizedZodNestOptions {\n createValidationException: CreateValidationException | undefined;\n createSerializationException: CreateSerializationException | undefined;\n /** No-op when `validationLogs.input` resolved to false. */\n logInputFailure: LogValidationFailure;\n /** No-op when `validationLogs.output` resolved to false. */\n logOutputFailure: LogValidationFailure;\n /** Built-in defaults ∪ `streamContentTypes`, used by the interceptor's stream check. */\n streamMatcher: StreamContentTypeMatcher;\n}\n\nexport const DEFAULT_REDACT_KEYS: readonly string[] = [\n // Credentials\n 'password',\n 'secret',\n 'apiKey',\n // Auth headers + tokens\n 'authorization',\n 'bearer',\n 'token',\n 'accessToken',\n 'refreshToken',\n 'jwt',\n // Session cookies\n 'cookie',\n 'set-cookie',\n];\n\nexport const DEFAULT_MAX_LOGGED_VALUE_BYTES = 4096;\n\n/** DI token for `NormalizedZodNestOptions`. */\nexport const ZOD_NEST_OPTIONS = Symbol('zod-nest.options');\n\ninterface ResolvedFlags {\n input: boolean;\n output: boolean;\n}\n\nconst resolveLogFlags = (validationLogs: ZodNestModuleOptions['validationLogs']): ResolvedFlags => {\n if (typeof validationLogs === 'boolean') {\n return { input: validationLogs, output: validationLogs };\n }\n return {\n input: validationLogs?.input ?? false,\n output: validationLogs?.output ?? false,\n };\n};\n\nexport const normalizeZodNestOptions = (opts?: ZodNestModuleOptions): NormalizedZodNestOptions => {\n const flags = resolveLogFlags(opts?.validationLogs);\n const redactKeys = opts?.redactKeys ?? DEFAULT_REDACT_KEYS;\n const maxLoggedValueBytes = opts?.maxLoggedValueBytes ?? DEFAULT_MAX_LOGGED_VALUE_BYTES;\n const logger: LoggerService = opts?.logger ?? new Logger(DEFAULT_LOGGER_CONTEXT);\n const loggerOpts = { logger, redactKeys, maxLoggedValueBytes };\n const streamMatcher = normalizeStreamMatcher([\n ...DEFAULT_STREAM_CONTENT_TYPES,\n ...(opts?.streamContentTypes ?? []),\n ]);\n\n return {\n createValidationException: opts?.createValidationException,\n createSerializationException: opts?.createSerializationException,\n logInputFailure: flags.input ? createValidationLogger(loggerOpts) : noopLogValidationFailure,\n logOutputFailure: flags.output ? createValidationLogger(loggerOpts) : noopLogValidationFailure,\n streamMatcher,\n };\n};\n","import { Inject, Injectable, Optional } from '@nestjs/common';\n\nimport type { ArgumentMetadata, PipeTransform } from '@nestjs/common';\nimport type { z } from 'zod';\nimport type { LogValidationFailure } from '../logging/validation-logger.js';\nimport type { NormalizedZodNestOptions } from '../module/options.js';\nimport type {\n CreateValidationException,\n ZodValidationPipeArg,\n ZodValidationPipeOptions,\n} from './types.js';\n\nimport { isZodDto } from '../dto/predicates.js';\nimport { ZodValidationException } from '../exceptions/validation.exception.js';\nimport { noopLogValidationFailure } from '../logging/validation-logger.js';\nimport { ZOD_NEST_OPTIONS } from '../module/options.js';\n\nconst isZodSchema = (value: unknown): value is z.ZodType =>\n value !== null && typeof value === 'object' && '_zod' in value;\n\nconst isOptionsObject = (value: unknown): value is ZodValidationPipeOptions =>\n value !== null && typeof value === 'object' && !isZodSchema(value);\n\nconst defaultExceptionFactory: CreateValidationException = (zodError, argMetadata) =>\n new ZodValidationException(zodError, argMetadata);\n\ninterface ParsedArg {\n schema: z.ZodType | undefined;\n factory: CreateValidationException | undefined;\n dtoName: string | undefined;\n}\n\n@Injectable()\nexport class ZodValidationPipe implements PipeTransform {\n private readonly explicitSchema: z.ZodType | undefined;\n private readonly explicitDtoName: string | undefined;\n private readonly createValidationException: CreateValidationException;\n private readonly logInputFailure: LogValidationFailure;\n\n constructor(\n @Optional() arg?: ZodValidationPipeArg,\n @Optional() @Inject(ZOD_NEST_OPTIONS) moduleOptions?: NormalizedZodNestOptions,\n ) {\n const parsed = ZodValidationPipe.parseArg(arg);\n this.explicitSchema = parsed.schema;\n this.explicitDtoName = parsed.dtoName;\n this.createValidationException =\n parsed.factory ?? moduleOptions?.createValidationException ?? defaultExceptionFactory;\n this.logInputFailure = moduleOptions?.logInputFailure ?? noopLogValidationFailure;\n }\n\n async transform(value: unknown, metadata: ArgumentMetadata): Promise<unknown> {\n const schema = this.resolveSchema(metadata);\n if (schema === undefined) {\n return value;\n }\n const result = await schema.safeParseAsync(value);\n if (result.success) {\n return result.data;\n }\n this.logInputFailure(result.error, value, {\n side: 'input',\n severity: 'warn',\n dto: this.resolveDtoLabel(metadata),\n argType: metadata.type,\n });\n throw this.createValidationException(result.error, metadata);\n }\n\n private resolveSchema(metadata: ArgumentMetadata): z.ZodType | undefined {\n if (this.explicitSchema !== undefined) {\n return this.explicitSchema;\n }\n const metatype: unknown = metadata.metatype;\n if (!isZodDto(metatype)) {\n return undefined;\n }\n return metatype.schema;\n }\n\n private resolveDtoLabel(metadata: ArgumentMetadata): string {\n if (this.explicitDtoName !== undefined) {\n return this.explicitDtoName;\n }\n const metatype: unknown = metadata.metatype;\n if (isZodDto(metatype)) {\n return metatype.name;\n }\n return 'schema';\n }\n\n private static parseArg(arg: ZodValidationPipeArg | undefined): ParsedArg {\n if (arg === undefined) {\n return { schema: undefined, factory: undefined, dtoName: undefined };\n }\n if (isZodDto(arg)) {\n return { schema: arg.schema, factory: undefined, dtoName: arg.name };\n }\n if (isZodSchema(arg)) {\n return { schema: arg, factory: undefined, dtoName: undefined };\n }\n if (!isOptionsObject(arg)) {\n return { schema: undefined, factory: undefined, dtoName: undefined };\n }\n const optionSchema = arg.schema;\n const dtoName = isZodDto(optionSchema) ? optionSchema.name : undefined;\n const resolvedSchema = isZodDto(optionSchema) ? optionSchema.schema : optionSchema;\n return {\n schema: resolvedSchema,\n factory: arg.createValidationException,\n dtoName,\n };\n }\n}\n","import { RequestMethod } from '@nestjs/common';\nimport { HTTP_CODE_METADATA, METHOD_METADATA } from '@nestjs/common/constants.js';\n\nimport type { ResponseStatusWildcard, ResponseVariant } from './metadata.js';\n\nconst POST_DEFAULT_STATUS = 201;\nconst GENERIC_DEFAULT_STATUS = 200;\n\n/**\n * Compute the default HTTP status code for a handler when `@ZodResponse(...)`\n * is invoked without an explicit `status`. Lookup order (highest → lowest):\n *\n * 1. `@HttpCode(n)` on the handler — explicit per-handler status override.\n * NestJS sets `HTTP_CODE_METADATA` to the numeric status when present.\n * 2. HTTP method default — `POST` → `201`, everything else → `200`.\n *\n * The method default itself falls back to `200` when `METHOD_METADATA` is\n * absent — pinned by tests so a future NestJS rename surfaces as a test\n * failure rather than a silent regression.\n */\nexport const defaultStatusFor = (handler: object): number => {\n const httpCode = Reflect.getMetadata(HTTP_CODE_METADATA, handler) as number | undefined;\n if (typeof httpCode === 'number') {\n return httpCode;\n }\n const method = Reflect.getMetadata(METHOD_METADATA, handler) as RequestMethod | undefined;\n if (method === RequestMethod.POST) {\n return POST_DEFAULT_STATUS;\n }\n return GENERIC_DEFAULT_STATUS;\n};\n\n/**\n * Resolve the effective status for a variant. Precedence chain:\n *\n * 1. Explicit numeric `@ZodResponse({ status })` — returned verbatim.\n * 2. Wildcard `@ZodResponse({ status: 'NXX' })` — returned verbatim; the\n * interceptor matcher handles range comparison against `response.statusCode`.\n * 3. Omitted status (or `'default'` collapsed at decoration time) —\n * `@HttpCode(n)` then HTTP-method default via `defaultStatusFor()`.\n *\n * Resolution is deferred to request time because `@ZodResponse` runs before\n * NestJS' route + `@HttpCode` decorators — none of their metadata is set\n * when the decorator evaluates.\n */\nexport const resolveEffectiveStatus = (\n variant: ResponseVariant,\n handler: object,\n): number | ResponseStatusWildcard => {\n if (variant.status !== undefined) {\n return variant.status;\n }\n return defaultStatusFor(handler);\n};\n","import type { z } from 'zod';\nimport type { ZodDto } from '../dto/dto.types.js';\n\n/**\n * Public metadata key for the array of `ResponseVariant` records attached\n * to handler methods by `@ZodResponse(...)`. Symbol.for() so external\n * consumers (e.g. custom interceptors or doc builders) can read the same\n * registry across realms.\n */\nexport const ZOD_RESPONSES_METADATA_KEY = Symbol.for('zod-nest.responses');\n\nexport type ResponseVariantKind = 'single' | 'array' | 'tuple';\n\n/**\n * OpenAPI 3.1 range keys accepted by `@ZodResponse({ status })`. Matched\n * by `ZodSerializerInterceptor` after exact numeric matches fail —\n * `'2XX'` covers 200–299, `'4XX'` covers 400–499, and so on.\n */\nexport type ResponseStatusWildcard = '1XX' | '2XX' | '3XX' | '4XX' | '5XX';\n\n/**\n * Description payload accepted by `@ZodResponse(...)` and passed through to\n * `applyZodNest`'s `@ApiResponse(...)` emitter. String form is shorthand for\n * `{ description }`; the object form lets users declare OpenAPI response\n * `headers` / `links` alongside the description.\n */\nexport type ZodResponseDescription =\n | string\n | {\n description: string;\n headers?: Record<string, unknown>;\n links?: Record<string, unknown>;\n };\n\n/**\n * One variant record per `@ZodResponse(...)` call. `dto` is kept alongside\n * `validationSchema` so `applyZodNest` can emit `@ApiResponse({ type })`\n * without unwrapping the runtime-only `z.array(...)` / `z.tuple([...])` wrapper.\n *\n * `status` is `undefined` when the user didn't pass one explicitly OR when\n * the user wrote `'default'` (the decorator collapses both to `undefined` —\n * they mean the same thing: \"resolve to the method's default status at\n * request time\"). The effective status is resolved lazily by\n * `resolveEffectiveStatus(variant, handler)` because `@ZodResponse` runs\n * *before* NestJS' route decorators (`@Get`, `@Post`, ...) under\n * TypeScript's bottom-up application order, so `METHOD_METADATA` is not\n * yet set when the decorator evaluates.\n *\n * A wildcard string (`'2XX'` / `'4XX'` / ...) is kept verbatim — the\n * matcher in `ZodSerializerInterceptor` handles range comparison.\n */\nexport interface ResponseVariant {\n status: number | ResponseStatusWildcard | undefined;\n kind: ResponseVariantKind;\n dto: ZodDto | readonly ZodDto[];\n validationSchema: z.ZodType;\n description?: ZodResponseDescription;\n passthroughOnError: boolean;\n /**\n * Raw `contentType` option from `@ZodResponse`, if set. `undefined` means\n * \"resolve lazily\" — `resolveContentType` falls back to a stream-typed\n * `@Header('Content-Type', …)` or `application/json`. Drives the OpenAPI\n * media-type key.\n */\n contentType?: string;\n /**\n * Raw `stream` option from `@ZodResponse`, if set. `undefined` means\n * \"infer\" — `isStreamResponse` treats the response as a stream when the\n * effective content type is a known stream type. Streams skip validation.\n */\n stream?: boolean;\n}\n\nexport const getResponseVariants = (handler: object): readonly ResponseVariant[] | undefined => {\n const meta = Reflect.getMetadata(ZOD_RESPONSES_METADATA_KEY, handler) as\n | ResponseVariant[]\n | undefined;\n return meta;\n};\n\n/**\n * Append a variant to the handler's metadata array. Implemented as a\n * prepend so the runtime ordering matches author order in the source —\n * TS decorators apply bottom-up, so the last-applied decorator (top of\n * the source) needs to land at the head of the array.\n */\nexport const appendResponseVariant = (handler: object, variant: ResponseVariant): void => {\n const existing =\n (Reflect.getMetadata(ZOD_RESPONSES_METADATA_KEY, handler) as ResponseVariant[] | undefined) ??\n [];\n Reflect.defineMetadata(ZOD_RESPONSES_METADATA_KEY, [variant, ...existing], handler);\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 type { z } from 'zod';\nimport type { ZodDto } from '../dto/dto.types.js';\n\nimport { createZodDto } from '../dto/create-zod-dto.js';\nimport { isZodDto, isZodSchema } from '../dto/predicates.js';\nimport { ANON_RESPONSE_PREFIX, resolveAnonId } from '../schema/anon-id.js';\nimport { defaultRegistry, registerSchema } from '../schema/registry.js';\n\n/**\n * Cache of `raw schema -> output DTO` so the same schema instance reused across\n * routes maps to one DTO (and therefore one OpenAPI component id). Without it,\n * an un-`.meta({ id })`'d schema would mint a fresh anonymous id per route.\n * WeakMap so the synthesised DTO is GC'd once the schema is. Mirrors the\n * `outputCache` pattern in `src/dto/output-dto.ts`.\n */\nconst responseDtoCache = new WeakMap<z.ZodType, ZodDto>();\n\nconst schemaToOutputDto = (schema: z.ZodType): ZodDto => {\n const cached = responseDtoCache.get(schema);\n if (cached !== undefined) {\n return cached;\n }\n // `createZodDto(schema)` as a plain expression is always type-safe — TS2509\n // (\"base constructor return type is not an object type\") only fires when the\n // result is used in an `extends` clause, never here. This is what lets a\n // raw union / intersection schema flow through unchanged.\n //\n // `createZodDto`'s anonymous-id fallback keys off the class name, which here\n // is the shared base \"ZodDtoBase\" — so an unnamed schema would not get a\n // unique id. Resolve the id ourselves: `.meta({ id })` when present, else a\n // generated synthetic id registered as `anonymous`.\n const namedId = registerSchema(schema);\n if (namedId !== undefined) {\n const dto = createZodDto(schema).Output;\n responseDtoCache.set(schema, dto);\n return dto;\n }\n // No resolvable id: register a synthetic anonymous id so the body is emitted\n // (under the document's `strict` / `override`) and referenced by `$ref`.\n // `applyZodNest`'s `inlineAnonymousBodies` pass inlines that body into the\n // response and prunes the synthetic component, so it never reaches the doc.\n const anonId = resolveAnonId(schema, ANON_RESPONSE_PREFIX);\n registerSchema(schema, defaultRegistry, { id: anonId, anonymous: true });\n const dto = createZodDto(schema, { id: anonId }).Output;\n responseDtoCache.set(schema, dto);\n return dto;\n};\n\n/**\n * Normalise one `@ZodResponse({ type })` entry into a `ZodDto`:\n * - a `ZodDto` is returned as-is (the caller already chose `.Output` or not);\n * - a raw Zod schema is wrapped as `createZodDto(schema).Output` — output IO,\n * because a response body is output-only — and cached per schema instance;\n * - anything else throws `TypeError` at decoration time so typos surface at\n * module load, not on the first request.\n *\n * `index` is supplied when the entry came from an array/tuple `type`, so the\n * thrown message can point at the offending slot.\n */\nexport const toResponseDto = (entry: unknown, index?: number): ZodDto => {\n if (isZodDto(entry)) {\n return entry;\n }\n if (isZodSchema(entry)) {\n return schemaToOutputDto(entry);\n }\n const where =\n index === undefined ? '@ZodResponse({ type })' : `@ZodResponse({ type }) element [${index}]`;\n throw new TypeError(\n `[zod-nest] ${where} must be a zod-nest DTO class (from createZodDto), ` +\n 'a Zod schema, or a non-empty array of those.',\n );\n};\n","import { ApiExtraModels, ApiResponse, getSchemaPath } from '@nestjs/swagger';\n\nimport type { Type } from '@nestjs/common';\nimport type { ApiResponseOptions } from '@nestjs/swagger';\nimport type { ZodDto } from '../dto/dto.types.js';\nimport type {\n ResponseStatusWildcard,\n ResponseVariant,\n ZodResponseDescription,\n} from '../response/metadata.js';\n\nimport { DEFAULT_CONTENT_TYPE } from '../response/stream.js';\n\n/**\n * Minimal shape for an OpenAPI 3.1 tuple schema. `@nestjs/swagger`'s\n * `SchemaObject` is modelled against OpenAPI 3.0 and doesn't declare\n * `prefixItems`. Building the literal here lets us avoid an `as` cast on\n * each `prefixItems` entry; the final assignment into `ApiResponseOptions.schema`\n * carries a single documented cast because that field's type is the 3.0\n * `SchemaObject`.\n */\ninterface TupleSchema {\n type: 'array';\n prefixItems: { $ref: string }[];\n items: false;\n}\n\ninterface DescriptionFields {\n description?: string;\n headers?: Record<string, unknown>;\n links?: Record<string, unknown>;\n}\n\nconst extractDescriptionFields = (desc: ZodResponseDescription | undefined): DescriptionFields => {\n if (desc === undefined) {\n return {};\n }\n if (typeof desc === 'string') {\n return { description: desc };\n }\n const out: DescriptionFields = { description: desc.description };\n if (desc.headers !== undefined) {\n out.headers = desc.headers;\n }\n if (desc.links !== undefined) {\n out.links = desc.links;\n }\n return out;\n};\n\n/**\n * `ZodDto` is the static side of a class produced by `createZodDto` — its\n * `new ()` signature satisfies `Type<unknown>`, but the structural intersection\n * with our static members (`schema`, `Output`, etc.) confuses TS into\n * rejecting a direct assignment to `ApiResponseOptions.type`. Narrow to\n * `Type<unknown>` (`@nestjs/common`'s constructor alias) at the boundary.\n */\nconst asDtoFunction = (dto: ZodDto): Type<unknown> => dto as unknown as Type<unknown>;\n\n/**\n * `@nestjs/swagger`'s `ApiResponseOptions.headers` is typed against the\n * OpenAPI 3.0 `HeadersObject` (`Record<string, HeaderObject | ReferenceObject>`).\n * `ZodResponseDescription.headers` keeps `Record<string, unknown>` so users\n * can pass through 3.1 / extension shapes without fighting the type. Cast\n * at the boundary; runtime contents flow through `@nestjs/swagger` unchanged.\n */\nconst buildApiResponseOptions = (\n base: { status: number | ResponseStatusWildcard } & DescriptionFields,\n body: { type: Type<unknown>; isArray?: true } | { schema: TupleSchema },\n): ApiResponseOptions => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- see header / schema comments above\n return { ...base, ...body } as any;\n};\n\nconst buildTupleSchema = (dtos: readonly ZodDto[]): TupleSchema => ({\n type: 'array',\n prefixItems: dtos.map((d) => ({ $ref: getSchemaPath(asDtoFunction(d)) })),\n items: false,\n});\n\n/**\n * OpenAPI schema for a non-JSON response body, keyed by `ResponseVariant.kind`:\n * single → a bare `$ref`; array → an `array` of `$ref`; tuple → a 3.1\n * `prefixItems` tuple. Each `$ref` targets the class name `@nestjs/swagger`\n * registers via `ApiExtraModels`; `applyZodNest` later rewrites it to the real\n * DTO id and replaces the placeholder body with the Zod-derived schema.\n */\ntype ContentSchema = { $ref: string } | { type: 'array'; items: { $ref: string } } | TupleSchema;\n\n/**\n * Build an `ApiResponseOptions` payload that pins a custom media-type key via\n * `content` (rather than `type` / `isArray`, which `@nestjs/swagger` always\n * wraps in `application/json`). Used for streamed / binary responses.\n */\nconst buildContentResponseOptions = (\n base: { status: number | ResponseStatusWildcard } & DescriptionFields,\n contentType: string,\n schema: ContentSchema,\n): ApiResponseOptions => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- 3.1 schema shapes (prefixItems) + the headers shape don't fit @nestjs/swagger's 3.0 types; see comments above\n return { ...base, content: { [contentType]: { schema } } } as any;\n};\n\n/**\n * Emit `@ApiResponse(...)` for a non-`application/json` content type. Registers\n * the variant's DTO(s) with `ApiExtraModels` so they land in\n * `components.schemas`, then references them by `$ref` under the custom media\n * type — the same placeholder-then-rewrite contract the tuple path relies on.\n */\nconst applyCustomContentResponse = (\n variant: ResponseVariant,\n base: { status: number | ResponseStatusWildcard } & DescriptionFields,\n contentType: string,\n target: object,\n propertyKey: string | symbol,\n descriptor: TypedPropertyDescriptor<unknown>,\n): void => {\n if (variant.kind === 'single') {\n const dto = variant.dto as ZodDto;\n ApiExtraModels(asDtoFunction(dto))(target, propertyKey, descriptor);\n const schema: ContentSchema = { $ref: getSchemaPath(asDtoFunction(dto)) };\n ApiResponse(buildContentResponseOptions(base, contentType, schema))(\n target,\n propertyKey,\n descriptor,\n );\n return;\n }\n\n const dtos = variant.dto as readonly ZodDto[];\n ApiExtraModels(...dtos.map(asDtoFunction))(target, propertyKey, descriptor);\n\n if (variant.kind === 'array') {\n // `buildArrayKind` guarantees `dtos.length === 1` for `array` kind — same\n // invariant the `application/json` array path relies on below.\n const dto = dtos[0]!;\n const schema: ContentSchema = {\n type: 'array',\n items: { $ref: getSchemaPath(asDtoFunction(dto)) },\n };\n ApiResponse(buildContentResponseOptions(base, contentType, schema))(\n target,\n propertyKey,\n descriptor,\n );\n return;\n }\n\n // tuple\n ApiResponse(buildContentResponseOptions(base, contentType, buildTupleSchema(dtos)))(\n target,\n propertyKey,\n descriptor,\n );\n};\n\n/**\n * Build an `ApiResponseOptions` payload for a `ResponseVariant` and apply\n * `@ApiResponse(...)` (plus `@ApiExtraModels(...)` for tuples) to the\n * handler. This is the swagger-side half of the composite `@ZodResponse`\n * decorator — the variant has already been registered for runtime\n * validation; this writes the matching OpenAPI doc entry.\n *\n * Tuple variants emit a raw `schema: { type: 'array', prefixItems: [...] }`\n * with one `$ref` per slot, and call `ApiExtraModels(...)` so `@nestjs/swagger`\n * registers each tuple-slot DTO in `components.schemas`. `applyZodNest` then\n * replaces the placeholder bodies with the real Zod-derived schemas.\n */\nexport const applySwaggerResponseDecorator = (\n variant: ResponseVariant,\n effectiveStatus: number | ResponseStatusWildcard,\n effectiveContentType: string,\n target: object,\n propertyKey: string | symbol,\n descriptor: TypedPropertyDescriptor<unknown>,\n): void => {\n const base = { status: effectiveStatus, ...extractDescriptionFields(variant.description) };\n\n if (effectiveContentType !== DEFAULT_CONTENT_TYPE) {\n applyCustomContentResponse(\n variant,\n base,\n effectiveContentType,\n target,\n propertyKey,\n descriptor,\n );\n return;\n }\n\n if (variant.kind === 'single') {\n const dto = variant.dto as ZodDto;\n ApiResponse(buildApiResponseOptions(base, { type: asDtoFunction(dto) }))(\n target,\n propertyKey,\n descriptor,\n );\n return;\n }\n\n if (variant.kind === 'array') {\n const dtos = variant.dto as readonly ZodDto[];\n // `buildArrayKind` guarantees `dtos.length === 1` for `array` kind.\n const dto = dtos[0]!;\n ApiResponse(buildApiResponseOptions(base, { type: asDtoFunction(dto), isArray: true }))(\n target,\n propertyKey,\n descriptor,\n );\n return;\n }\n\n // tuple\n const dtos = variant.dto as readonly ZodDto[];\n ApiExtraModels(...dtos.map(asDtoFunction))(target, propertyKey, descriptor);\n ApiResponse(buildApiResponseOptions(base, { schema: buildTupleSchema(dtos) }))(\n target,\n propertyKey,\n descriptor,\n );\n};\n","import { z } from 'zod';\n\nimport type { ZodDto } from '../dto/dto.types.js';\nimport type {\n ResponseStatusWildcard,\n ResponseVariant,\n ResponseVariantKind,\n ZodResponseDescription,\n} from '../response/metadata.js';\n\nimport { resolveEffectiveStatus } from '../response/default-status.js';\nimport { appendResponseVariant } from '../response/metadata.js';\nimport { toResponseDto } from '../response/normalize-type.js';\nimport { DEFAULT_STREAM_MATCHER, resolveContentType } from '../response/stream.js';\nimport { applySwaggerResponseDecorator } from './zod-response.swagger-bridge.js';\n\n/**\n * One entry in `@ZodResponse({ type })` — either a zod-nest DTO or a raw Zod\n * schema. A raw schema is normalised internally to `createZodDto(schema).Output`\n * (output IO, since a response body is output-only), so schemas that can't be\n * wrapped with `createZodDto` — `z.discriminatedUnion` / `z.union` /\n * `z.intersection`, whose `z.infer` is a union and so trip TS2509 in an\n * `extends` clause — can be passed straight to a response. See `toResponseDto`.\n */\nexport type ZodResponseEntry = ZodDto | z.ZodType;\n\n/**\n * Accepted shapes for `@ZodResponse({ type })`. Each slot is a `ZodResponseEntry`\n * (DTO or raw schema), and the two may be mixed within an array:\n * - `Dto` / `Schema` → validates as the entry's schema (single response).\n * - `[Entry]` (length 1) → validates as `z.array(entry.schema)`; matches Nest's\n * `@ApiResponse({ isArray: true })` convention without minting a separate\n * `*sDto` id.\n * - `[A, B, ...]` (length ≥ 2) → validates as `z.tuple([A.schema, B.schema, ...])`;\n * surfaces as an OpenAPI 3.1 `prefixItems` tuple via `applyZodNest`.\n *\n * Empty arrays and entries that are neither a DTO nor a schema throw `TypeError`\n * at decoration time so typos surface at module load, not the first request.\n */\nexport type ZodResponseType = ZodResponseEntry | readonly [ZodResponseEntry, ...ZodResponseEntry[]];\n\n/**\n * Accepted shapes for `@ZodResponse({ status })`:\n * - `number` — exact match against `response.statusCode` (most common case).\n * - `'1XX'` / `'2XX'` / `'3XX'` / `'4XX'` / `'5XX'` — OpenAPI 3.1 range key;\n * `'2XX'` matches 200–299, etc. Considered only after no exact numeric\n * variant matches the observed status.\n * - `'default'` — sugar for the handler's method default status. Collapsed\n * to `undefined` when the variant is built, so `resolveEffectiveStatus`\n * walks the same `@HttpCode → method-default` chain as an omitted `status`.\n * This deliberately does NOT implement a catch-all-fallback semantic; it\n * names the canonical-success card explicitly, matching what consumers\n * already write in `@ApiResponse({ status: 'default' })`.\n */\nexport type ResponseStatusInput = number | ResponseStatusWildcard | 'default';\n\nexport interface ZodResponseOptions {\n status?: ResponseStatusInput;\n type: ZodResponseType;\n description?: ZodResponseDescription;\n passthroughOnError?: boolean;\n /**\n * Response content type, used as the OpenAPI media-type key (`@ApiResponse`\n * `content`). Defaults to `'application/json'`. Set a stream type\n * (`'text/event-stream'`, `'application/x-ndjson'`, …) to document a streamed\n * body; combined with `stream` it also turns off response validation.\n */\n contentType?: string;\n /**\n * When `true`, the response is written directly to the buffer and\n * `ZodSerializerInterceptor` skips validation. When unset, it is inferred:\n * a stream-typed `contentType` (or a stream-typed `@Header('Content-Type', …)`)\n * implies `true`. See `DEFAULT_STREAM_CONTENT_TYPES`.\n */\n stream?: boolean;\n}\n\ninterface BuiltKind {\n kind: ResponseVariantKind;\n dto: ZodDto | readonly ZodDto[];\n validationSchema: z.ZodType;\n}\n\ntype NonEmptyEntryArray = readonly [ZodResponseEntry, ...ZodResponseEntry[]];\n\nconst buildArrayKind = (entries: NonEmptyEntryArray): BuiltKind => {\n // Destructure the entry tuple first (so `head` stays non-optional), then\n // normalise each through `toResponseDto` — which rejects non-DTO / non-schema\n // entries with a `TypeError` carrying the offending index.\n const [headEntry, ...restEntries] = entries;\n const head = toResponseDto(headEntry, 0);\n const rest = restEntries.map((entry, index) => toResponseDto(entry, index + 1));\n if (rest.length === 0) {\n return { kind: 'array', dto: [head], validationSchema: z.array(head.schema) };\n }\n const tupleSchemas: [z.ZodType, ...z.ZodType[]] = [head.schema, ...rest.map((d) => d.schema)];\n return { kind: 'tuple', dto: [head, ...rest], validationSchema: z.tuple(tupleSchemas) };\n};\n\nconst buildKind = (type: ZodResponseType): BuiltKind => {\n if (Array.isArray(type)) {\n if (type.length === 0) {\n throw new TypeError(\n '[zod-nest] @ZodResponse({ type: [] }) is invalid — provide at least one DTO or schema.',\n );\n }\n // After the length check, `type` is guaranteed non-empty; the static\n // `readonly [ZodResponseEntry, ...ZodResponseEntry[]]` annotation reflects\n // this so the destructure in `buildArrayKind` doesn't need a runtime guard.\n return buildArrayKind(type as NonEmptyEntryArray);\n }\n const dto = toResponseDto(type);\n return { kind: 'single', dto, validationSchema: dto.schema };\n};\n\n/**\n * Normalise the user-facing `status` input into the variant-internal shape:\n * `'default'` collapses to `undefined` so the matcher treats it the same as\n * an omitted status (resolve to `defaultStatusFor(handler)` at request time).\n * Numbers and `'NXX'` wildcards pass through untouched.\n */\nconst normaliseStatus = (\n status: ResponseStatusInput | undefined,\n): number | ResponseStatusWildcard | undefined => {\n if (status === 'default') {\n return undefined;\n }\n return status;\n};\n\n/**\n * Method-only decorator. Declares a typed response variant for the handler\n * AND applies the equivalent `@ApiResponse(...)` from `@nestjs/swagger` so\n * the OpenAPI document carries the response shape — no need for consumers\n * to hand-write `@ApiResponse` alongside `@ZodResponse`.\n *\n * Stack multiple decorations to declare per-status types; runtime lookup\n * is by `ZodSerializerInterceptor`'s two-pass matcher (exact numeric, then\n * `'NXX'` wildcard). The wrapped Zod schema (array / tuple) is built once\n * at decoration time — no per-request schema construction.\n *\n * **Decorator-ordering note.** TypeScript decorators apply bottom-up, so\n * `@ZodResponse` (typically written above `@Get` / `@HttpCode` /\n * `@Header(...)`) runs *before* those siblings have written their\n * `HTTP_CODE_METADATA` / `METHOD_METADATA` / `HEADERS_METADATA`. The\n * `@ApiResponse(...)` call is therefore always deferred via `queueMicrotask`,\n * so by the time it reads sibling metadata — the effective status *and* the\n * effective content type (including `@Header('Content-Type', …)` inference) —\n * everything has settled. The document is built much later\n * (`SwaggerModule.createDocument`), so the deferral is invisible to output.\n * See `docs/responses.md → \"Decorator ordering & the microtask trick\"`.\n */\nexport const ZodResponse = (opts: ZodResponseOptions): MethodDecorator => {\n const built = buildKind(opts.type);\n const status = normaliseStatus(opts.status);\n return (target, propertyKey, descriptor) => {\n const handler = descriptor.value;\n if (typeof handler !== 'function') {\n throw new TypeError('[zod-nest] @ZodResponse can only be applied to methods.');\n }\n const variant: ResponseVariant = {\n status,\n kind: built.kind,\n dto: built.dto,\n validationSchema: built.validationSchema,\n description: opts.description,\n passthroughOnError: opts.passthroughOnError ?? false,\n contentType: opts.contentType,\n stream: opts.stream,\n };\n appendResponseVariant(handler, variant);\n\n // `TypedPropertyDescriptor<unknown>` matches what the swagger bridge\n // expects; `MethodDecorator`'s descriptor parameter is `TypedPropertyDescriptor<T>`\n // for the inferred return type, structurally compatible at runtime.\n const swaggerDescriptor = descriptor as TypedPropertyDescriptor<unknown>;\n // Always defer: sibling `@HttpCode` / route method / `@Header` metadata is\n // not yet written when this decorator applies. The default stream matcher\n // is used here — module options (`streamContentTypes`) don't exist at\n // decoration time; they extend only the interceptor's runtime check.\n queueMicrotask(() => {\n const effectiveStatus = resolveEffectiveStatus(variant, handler);\n const contentType = resolveContentType(variant, handler, DEFAULT_STREAM_MATCHER);\n applySwaggerResponseDecorator(\n variant,\n effectiveStatus,\n contentType,\n target,\n propertyKey,\n swaggerDescriptor,\n );\n });\n };\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 type SchemaRefResolution =\n | { readonly kind: 'ref'; readonly ref: { readonly $ref: string } }\n | { readonly kind: 'inline'; readonly schema: Record<string, unknown> };\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 */\nexport const 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 { ApiBody } from '@nestjs/swagger';\nimport { z } from 'zod';\n\nimport type { ZodNestRegistry } from '../schema/registry.js';\n\nimport { defaultRegistry } from '../schema/registry.js';\nimport { flattenObjectIntersection } from './internal/flatten-intersection.js';\nimport { resolveSchemaRef } from './internal/zod-schema-ref.js';\n\ntype BodySchema = { readonly $ref: string } | Record<string, unknown>;\n\nexport interface ZodBodyOptions {\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 /** 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 * Merge an intersection of `z.object` arms into a single flat object body\n * emitted inline (no `$ref`, no `components.schemas` entry). Use when\n * Swagger UI's `multipart/form-data` `try-it-out` form needs to render the\n * body — the UI doesn't follow `$ref` or unwrap `allOf`. Throws\n * `ZodNestError` if the schema isn't an object or an intersection of\n * objects. No-op for a bare `z.object`. Defaults to `false`.\n */\n readonly flatten?: boolean;\n}\n\n/**\n * Method-level decorator that wires the OpenAPI `requestBody` for a handler\n * whose body schema doesn't fit a `createZodDto` class — typically a\n * `z.intersection` that contains a `z.union`, a `z.discriminatedUnion`, or\n * any schema whose `z.infer<>` is a TypeScript union (which TS refuses as a\n * class base with TS2509).\n *\n * Pair with `@Body(new ZodValidationPipe(schema))` at the parameter to keep\n * the handler arg precisely typed as `z.infer<typeof schema>`:\n *\n * ```ts\n * @Post()\n * @ZodBody(IntersectionWithUnion)\n * async post(\n * @Body(new ZodValidationPipe(IntersectionWithUnion))\n * body: z.infer<typeof IntersectionWithUnion>,\n * ) {}\n * ```\n *\n * The schema is registered in the registry when it has an id (via\n * `.meta({ id })` or `options.id`) so its body is emitted into\n * `components.schemas`. Anonymous schemas are inlined into the operation.\n */\nexport const ZodBody = (schema: z.ZodType, options?: ZodBodyOptions): MethodDecorator => {\n const apiBodySchema = resolveBodySchema(schema, options);\n return ApiBody({\n schema: apiBodySchema,\n ...(options?.description !== undefined ? { description: options.description } : {}),\n required: options?.required ?? true,\n });\n};\n\nconst resolveBodySchema = (schema: z.ZodType, options: ZodBodyOptions | undefined): BodySchema => {\n if (options?.flatten === true) {\n return flattenObjectIntersection(schema, options.registry ?? defaultRegistry, '@ZodBody');\n }\n const resolution = resolveSchemaRef(schema, {\n id: options?.id,\n registry: options?.registry,\n deferAnonInline: true,\n });\n return resolution.kind === 'ref' ? resolution.ref : resolution.schema;\n};\n","/**\n * `@nestjs/swagger`'s metadata key for explicit operation parameters — the\n * array `@ApiQuery` / `@ApiParam` / etc. append to. Hardcoded because the\n * `DECORATORS` constant that owns it (`DECORATORS.API_PARAMETERS`) is not\n * re-exported from the package's public barrel. The end-to-end smoke test\n * (`test/decorators/zod-decorators.swagger-smoke.spec.ts`) guards the contract.\n */\nconst API_PARAMETERS_METADATA_KEY = 'swagger/apiParameters';\n\n/**\n * Append a single zod-nest query marker to a handler's swagger parameter\n * metadata — the same `{ __zodNestDto, dtoId, io, in }` placeholder shape that\n * `createZodDto`'s `_OPENAPI_METADATA_FACTORY` produces for `@Query() dto`, so\n * `expandParamMarkers` resolves it through one code path. Deferring (rather\n * than expanding at decoration time) is what lets `@ZodQuery`'s ref decision\n * follow `applyZodNest`'s `queryParamStyle` preference, which isn't known until\n * the document is built.\n *\n * `type` is intentionally omitted: `@nestjs/swagger`'s `SchemaObjectFactory`\n * returns a typeless query parameter untouched, so the marker (and its custom\n * keys) survives `SwaggerModule.createDocument` verbatim for `expandParamMarkers`\n * to read. `name` is set to `dtoId` purely to give the placeholder a stable\n * identity before expansion replaces it.\n *\n * @param dtoId Registered component id of the query DTO schema.\n * @param ref Per-marker override of `queryParamStyle`; omitted from the marker\n * when `undefined` so the global preference applies.\n */\nexport const appendQueryMarker =\n (dtoId: string, ref: boolean | undefined): MethodDecorator =>\n (_target, _propertyKey, descriptor) => {\n const method = descriptor.value;\n if (typeof method !== 'function') {\n return descriptor;\n }\n const marker: Record<string, unknown> = {\n name: dtoId,\n in: 'query',\n __zodNestDto: true,\n dtoId,\n io: 'input',\n };\n if (ref !== undefined) {\n marker.ref = ref;\n }\n const existing: unknown = Reflect.getMetadata(API_PARAMETERS_METADATA_KEY, method);\n const params: unknown[] = Array.isArray(existing) ? existing : [];\n Reflect.defineMetadata(API_PARAMETERS_METADATA_KEY, [...params, marker], method);\n return descriptor;\n };\n","import { applyDecorators } from '@nestjs/common';\nimport { ApiQuery } from '@nestjs/swagger';\nimport { z } from 'zod';\n\nimport type { ZodNestRegistry } from '../schema/registry.js';\n\nimport { ZodNestError } from '../schema/errors.js';\nimport { defaultRegistry, registerSchema } from '../schema/registry.js';\nimport { appendQueryMarker } from './internal/query-marker.js';\nimport { expandObjectSchema, isZodObject, paramSchemaBody } from './internal/zod-param-expand.js';\n\nexport interface ZodQueryOptions {\n /** Forces this id on the root schema, overriding any `.meta({ id })`. */\n readonly id?: string;\n /** Registry to register into. Defaults to `defaultRegistry`. */\n readonly registry?: ZodNestRegistry;\n /**\n * Override how this query DTO is represented in the OpenAPI doc, taking\n * precedence over `applyZodNest`'s `queryParamStyle`:\n *\n * - `true` — one single schema-based query parameter that `$ref`s the DTO's\n * `components.schemas` entry (`style: 'form'`, `explode: true`).\n * - `false` — one parameter per top-level property.\n * - unset — follow the global `queryParamStyle` preference (default `'expand'`).\n *\n * Ref mode needs a named schema to reference: `ref: true` on an anonymous\n * schema (no `.meta({ id })` and no `id` option) throws `ZodNestError`.\n */\n readonly ref?: boolean;\n}\n\n/**\n * Method-level decorator describing a `@Query()` object schema as OpenAPI\n * query parameters.\n *\n * When the schema is named (`.meta({ id })` or the `id` option), the decorator\n * registers it and emits a single deferred marker, leaving the expand-vs-`$ref`\n * decision to `applyZodNest` — so an unset `ref` follows the global\n * `queryParamStyle` preference, `ref: true` collapses to one `$ref` query\n * parameter, and `ref: false` expands per property. This mirrors the\n * `@Query() dto` (`createZodDto`) path, which flows through the same marker.\n *\n * When the schema is anonymous, there is no component to reference, so the\n * decorator expands one `@ApiQuery` per property immediately (and rejects\n * `ref: true`).\n *\n * The user remains responsible for binding the actual query values to the\n * handler, typically via `@Query(new ZodValidationPipe(schema)) q: z.infer<typeof schema>`.\n */\nexport const ZodQuery = (schema: z.ZodType, options?: ZodQueryOptions): MethodDecorator => {\n if (!isZodObject(schema)) {\n throw new ZodNestError(\n `@ZodQuery 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 const id = registerSchema(schema, registry, { id: options?.id });\n if (id !== undefined) {\n return appendQueryMarker(id, options?.ref);\n }\n if (options?.ref === true) {\n throw new ZodNestError(\n `@ZodQuery({ ref: true }) requires a named schema — there is no component to \\`$ref\\`. ` +\n `Name the schema via \\`.meta({ id: 'Foo' })\\` or pass the \\`id\\` option, or drop \\`ref\\` to expand per property.`,\n );\n }\n const expanded = expandObjectSchema(schema, {\n id: options?.id,\n registry,\n decoratorName: '@ZodQuery',\n });\n return applyDecorators(\n ...expanded.map(({ name, required, resolution }) =>\n ApiQuery({ name, schema: paramSchemaBody(resolution), required }),\n ),\n );\n};\n","/**\n * `@nestjs/swagger`'s method-level parameters metadata key. Mirrored verbatim\n * from `@nestjs/swagger/dist/constants.js`'s `DECORATORS.API_PARAMETERS` —\n * inlined as a string literal so we don't reach into the package's deep\n * import paths (it isn't part of the package's public `exports` map).\n */\nexport const API_PARAMETERS_KEY = 'swagger/apiParameters';\n","import { z } from 'zod';\n\nimport { type ZodNestRegistry } from '../schema/registry.js';\nimport { API_PARAMETERS_KEY } from './internal/constants.js';\nimport { expandObjectSchema, paramSchemaBody } from './internal/zod-param-expand.js';\n\nexport interface ZodHeadersOptions {\n /** Forces this id on the root schema, overriding any `.meta({ id })`. */\n readonly id?: string;\n /** Registry to register into. Defaults to `defaultRegistry`. */\n readonly registry?: ZodNestRegistry;\n}\n\ninterface HeaderParameter {\n readonly name: string;\n readonly in: 'header';\n readonly required: boolean;\n readonly schema: { readonly $ref: string } | Record<string, unknown>;\n}\n\n/**\n * Method-level decorator that expands a `z.object` schema into one\n * header-parameter entry per property. Required-ness derives from each\n * property's Zod optionality.\n *\n * Writes directly to the `swagger/apiParameters` metadata key the explorer\n * reads. We bypass `@ApiHeader` because it injects a default `type: 'string'`\n * onto the schema (`api-header.decorator.js`), which pollutes our `$ref`\n * objects and inline JSON Schemas. The raw-metadata path keeps our schema\n * bodies intact.\n */\nexport const ZodHeaders = (schema: z.ZodType, options?: ZodHeadersOptions): MethodDecorator => {\n const expanded = expandObjectSchema(schema, {\n id: options?.id,\n registry: options?.registry,\n decoratorName: '@ZodHeaders',\n });\n const newEntries: HeaderParameter[] = expanded.map(({ name, required, resolution }) => ({\n name,\n in: 'header',\n required,\n schema: paramSchemaBody(resolution),\n }));\n return (_target, _propertyKey, descriptor) => {\n const handler = descriptor.value;\n if (typeof handler !== 'function') {\n throw new TypeError('[zod-nest] @ZodHeaders can only be applied to methods.');\n }\n const existing: unknown[] = Reflect.getMetadata(API_PARAMETERS_KEY, handler) ?? [];\n Reflect.defineMetadata(API_PARAMETERS_KEY, [...existing, ...newEntries], handler);\n };\n};\n","import { z } from 'zod';\n\nimport { type ZodNestRegistry } from '../schema/registry.js';\nimport { API_PARAMETERS_KEY } from './internal/constants.js';\nimport { expandObjectSchema, paramSchemaBody } from './internal/zod-param-expand.js';\n\nexport interface ZodCookiesOptions {\n /** Forces this id on the root schema, overriding any `.meta({ id })`. */\n readonly id?: string;\n /** Registry to register into. Defaults to `defaultRegistry`. */\n readonly registry?: ZodNestRegistry;\n}\n\ninterface CookieParameter {\n readonly name: string;\n readonly in: 'cookie';\n readonly required: boolean;\n readonly schema: { readonly $ref: string } | Record<string, unknown>;\n}\n\n/**\n * Method-level decorator that expands a `z.object` schema into one\n * cookie-parameter entry per property in the OpenAPI operation. There is no\n * `@ApiCookie` decorator in `@nestjs/swagger`, so we write directly to the\n * `swagger/apiParameters` metadata key the explorer reads — the same key\n * `@ApiQuery` / `@ApiParam` / `@ApiHeader` populate via their helper.\n */\nexport const ZodCookies = (schema: z.ZodType, options?: ZodCookiesOptions): MethodDecorator => {\n const expanded = expandObjectSchema(schema, {\n id: options?.id,\n registry: options?.registry,\n decoratorName: '@ZodCookies',\n });\n const newEntries: CookieParameter[] = expanded.map(({ name, required, resolution }) => ({\n name,\n in: 'cookie',\n required,\n schema: paramSchemaBody(resolution),\n }));\n return (_target, _propertyKey, descriptor) => {\n const handler = descriptor.value;\n if (typeof handler !== 'function') {\n throw new TypeError('[zod-nest] @ZodCookies can only be applied to methods.');\n }\n const existing: unknown[] = Reflect.getMetadata(API_PARAMETERS_KEY, handler) ?? [];\n Reflect.defineMetadata(API_PARAMETERS_KEY, [...existing, ...newEntries], handler);\n };\n};\n","import { Inject, Injectable, Optional } from '@nestjs/common';\nimport { Reflector } from '@nestjs/core';\nimport { from } from 'rxjs';\nimport { mergeMap } from 'rxjs/operators';\n\nimport type { CallHandler, ExecutionContext, NestInterceptor } from '@nestjs/common';\nimport type { Observable } from 'rxjs';\nimport type { ZodDto } from '../dto/dto.types.js';\nimport type { LogValidationFailure } from '../logging/validation-logger.js';\nimport type { CreateSerializationException, NormalizedZodNestOptions } from '../module/options.js';\nimport type { ResponseStatusWildcard, ResponseVariant } from '../response/metadata.js';\nimport type { StreamContentTypeMatcher } from '../response/stream.js';\n\nimport { ZodSerializationException } from '../exceptions/serialization.exception.js';\nimport { noopLogValidationFailure } from '../logging/validation-logger.js';\nimport { ZOD_NEST_OPTIONS } from '../module/options.js';\nimport { resolveEffectiveStatus } from '../response/default-status.js';\nimport { ZOD_RESPONSES_METADATA_KEY } from '../response/metadata.js';\nimport { DEFAULT_STREAM_MATCHER, isStreamResponse } from '../response/stream.js';\n\nconst defaultSerializationFactory: CreateSerializationException = (err, ctx) =>\n new ZodSerializationException(err, ctx);\n\n// Label by `.id` (the OpenAPI component name) rather than `.name` (the class\n// name): a DTO synthesised from a raw schema is an anonymous output sibling\n// whose class name is the unhelpful `\"SiblingClass\"`, while its `.id` is the\n// meaningful component id (from `.meta({ id })` or the anonymous fallback).\nconst formatDtoLabel = (variant: ResponseVariant): string => {\n if (variant.kind === 'single') {\n return (variant.dto as ZodDto).id;\n }\n const dtos = variant.dto as readonly ZodDto[];\n return `[${dtos.map((d) => d.id).join(', ')}]`;\n};\n\nconst formatHandlerLabel = (context: ExecutionContext): string =>\n `${context.getClass().name}.${context.getHandler().name}`;\n\n// '1XX' → 1, '2XX' → 2, etc. `charCodeAt(0) - 48` is the leading digit;\n// `Math.floor(status / 100)` is the response's hundreds bucket.\nconst matchesWildcard = (wildcard: ResponseStatusWildcard, status: number): boolean =>\n wildcard.charCodeAt(0) - 48 === Math.floor(status / 100);\n\n/**\n * Two-pass variant selection: exact numeric match wins outright, then the\n * `'NXX'` wildcard variants get a chance. Source order breaks ties within\n * each pass — first match wins, mirroring author intent (decorators apply\n * bottom-up but `appendResponseVariant` prepends, so the runtime array is\n * already in source order).\n */\nconst selectVariant = (\n variants: readonly ResponseVariant[],\n status: number,\n handler: object,\n): ResponseVariant | undefined => {\n for (const variant of variants) {\n const effective = resolveEffectiveStatus(variant, handler);\n if (typeof effective === 'number' && effective === status) {\n return variant;\n }\n }\n for (const variant of variants) {\n const effective = resolveEffectiveStatus(variant, handler);\n if (typeof effective === 'string' && matchesWildcard(effective, status)) {\n return variant;\n }\n }\n return undefined;\n};\n\n@Injectable()\nexport class ZodSerializerInterceptor implements NestInterceptor {\n private readonly logOutputFailure: LogValidationFailure;\n private readonly createSerializationException: CreateSerializationException;\n private readonly streamMatcher: StreamContentTypeMatcher;\n\n constructor(\n private readonly reflector: Reflector,\n @Optional() @Inject(ZOD_NEST_OPTIONS) options?: NormalizedZodNestOptions,\n ) {\n this.logOutputFailure = options?.logOutputFailure ?? noopLogValidationFailure;\n this.createSerializationException =\n options?.createSerializationException ?? defaultSerializationFactory;\n // Falls back to built-in defaults when the module isn't configured\n // (`ZodSerializerInterceptor` used standalone, without `ZodNestModule`).\n this.streamMatcher = options?.streamMatcher ?? DEFAULT_STREAM_MATCHER;\n }\n\n intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {\n if (context.getType() !== 'http') {\n return next.handle();\n }\n const handler = context.getHandler();\n const variants = this.reflector.get<readonly ResponseVariant[] | undefined>(\n ZOD_RESPONSES_METADATA_KEY,\n handler,\n );\n if (variants === undefined || variants.length === 0) {\n return next.handle();\n }\n return next\n .handle()\n .pipe(mergeMap((value) => from(this.transform(value, variants, context, handler))));\n }\n\n private async transform(\n value: unknown,\n variants: readonly ResponseVariant[],\n context: ExecutionContext,\n handler: object,\n ): Promise<unknown> {\n const response = context.switchToHttp().getResponse<{ statusCode?: number }>();\n const status = response.statusCode;\n if (status === undefined) {\n return value;\n }\n const variant = selectVariant(variants, status, handler);\n if (variant === undefined) {\n return value;\n }\n // Streams (SSE / NDJSON / binary) are written straight to the response\n // buffer — there's no single body to validate, so pass it through as-is.\n if (isStreamResponse(variant, handler, this.streamMatcher)) {\n return value;\n }\n const result = await variant.validationSchema.safeParseAsync(value);\n if (result.success) {\n return result.data;\n }\n const isSoft = variant.passthroughOnError;\n this.logOutputFailure(result.error, value, {\n side: 'output',\n severity: isSoft ? 'warn' : 'error',\n dto: formatDtoLabel(variant),\n status,\n handler: formatHandlerLabel(context),\n });\n if (isSoft) {\n return value;\n }\n throw this.createSerializationException(result.error, context);\n }\n}\n","import { APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';\n\nimport type { DynamicModule } from '@nestjs/common';\nimport type { ZodNestModuleOptions } from './options.js';\n\nimport { ZodSerializerInterceptor } from '../interceptors/serializer.interceptor.js';\nimport { ZodValidationPipe } from '../pipes/validation.pipe.js';\nimport { normalizeZodNestOptions, ZOD_NEST_OPTIONS } from './options.js';\n\n/**\n * Central wiring for the zod-nest pipe + interceptor. Call\n * `ZodNestModule.forRoot(options?)` from your root `AppModule` to register\n * `APP_PIPE` (`ZodValidationPipe`) and `APP_INTERCEPTOR`\n * (`ZodSerializerInterceptor`) globally, with shared options for\n * validation logging, redaction, and exception factories.\n *\n * `forRoot()` is optional — the pipe and interceptor also work as\n * regular `APP_PIPE` / `APP_INTERCEPTOR` providers if you prefer to\n * wire them manually; `@Optional()` injection of `ZOD_NEST_OPTIONS`\n * falls through to safe defaults.\n *\n * Marked `global` so the `ZOD_NEST_OPTIONS` token is injectable from\n * feature modules (e.g. a custom pipe that wants the same logger /\n * redact list as the module-wired one).\n */\nexport class ZodNestModule {\n static forRoot(options?: ZodNestModuleOptions): DynamicModule {\n const normalized = normalizeZodNestOptions(options);\n return {\n module: ZodNestModule,\n global: true,\n providers: [\n { provide: ZOD_NEST_OPTIONS, useValue: normalized },\n { provide: APP_PIPE, useClass: ZodValidationPipe },\n { provide: APP_INTERCEPTOR, useClass: ZodSerializerInterceptor },\n ],\n exports: [ZOD_NEST_OPTIONS],\n };\n }\n}\n","import { z } from 'zod';\n\nimport type { Override } from '../schema/override.js';\nimport type { ZodNestRegistry } from '../schema/registry.js';\n\nimport { buildToJsonSchemaOptions } from '../schema/engine.js';\n\nexport interface BulkEmitOptions {\n registry: ZodNestRegistry;\n override?: Override;\n /** When `true` (default), unrepresentable Zod constructs throw `ZodNestUnrepresentableError`. */\n strict?: boolean;\n}\n\nexport interface BulkEmitResult {\n /** Schemas emitted with `io: 'input'`. Filtered to zod-nest-known ids only. */\n inputSchemas: Map<string, unknown>;\n /** Schemas emitted with `io: 'output'`. Filtered to zod-nest-known ids only. */\n outputSchemas: Map<string, unknown>;\n}\n\nconst URI = (id: string): string => `#/components/schemas/${id}`;\n\n/**\n * Two-pass bulk emission against the registry's underlying `z.globalRegistry`.\n * Returns one map per io. Result is filtered to the ids zod-nest itself\n * registered (via `registry.ids()`) — `z.globalRegistry` may hold third-party\n * entries we don't own.\n *\n * Uses `buildToJsonSchemaOptions` so emission semantics (override chain,\n * cycles, unrepresentable detection, metadata) match the single-schema\n * `toOpenApi` path. The `uri` callback shapes every registered-schema\n * `$ref` directly to `#/components/schemas/<id>` — doc-level refs need no\n * rewrite at emission time. `reused: 'inline'` keeps Zod\n * from extracting anonymous reused sub-schemas into a virtual `__shared`\n * defs table whose refs would dangle against `components.schemas`.\n */\nexport const bulkEmit = (opts: BulkEmitOptions): BulkEmitResult => {\n const knownIds = new Set(opts.registry.ids());\n return {\n inputSchemas: runPass(opts, 'input', knownIds),\n outputSchemas: runPass(opts, 'output', knownIds),\n };\n};\n\nconst runPass = (\n opts: BulkEmitOptions,\n io: 'input' | 'output',\n knownIds: ReadonlySet<string>,\n): Map<string, unknown> => {\n const built = buildToJsonSchemaOptions({\n registry: opts.registry,\n io,\n override: opts.override,\n strict: opts.strict,\n reused: 'inline',\n uri: URI,\n });\n // Zod v4's bulk-mode emission always returns `{ schemas: Record<...> }` —\n // even for an empty registry the `schemas` key is present with `{}`.\n const raw = z.toJSONSchema(opts.registry.zodRegistry, built.options) as {\n schemas: Record<string, unknown>;\n };\n built.consumeUnrepresentable();\n\n // Iterate Zod's emission (the source of truth for what was actually\n // emitted) and keep only the ids we registered. Inverts the older\n // `for (knownIds) { if (raw.schemas has id) ... }` shape so the filter\n // branches are naturally covered by the existing \"filter outside ids\"\n // test instead of a defensive guard that was never exercised.\n const filtered = new Map<string, unknown>();\n for (const [id, schema] of Object.entries(raw.schemas)) {\n if (knownIds.has(id)) {\n filtered.set(id, schema);\n }\n }\n return filtered;\n};\n","import type { OpenAPIObject } from '@nestjs/swagger';\n\n/** OpenAPI 3.1 operation methods, in spec order. */\nexport const HTTP_METHODS: readonly string[] = [\n 'get',\n 'put',\n 'post',\n 'delete',\n 'options',\n 'head',\n 'patch',\n 'trace',\n];\n\n/**\n * Visits every `(pathItem, op)` pair in the doc, narrowed to plain records.\n * Centralises the defensive `paths → pathItem → op` walk that several\n * post-process passes need; callers that mutate `op` (e.g. swap\n * `op.parameters`) can do so in place.\n */\nexport const forEachOperation = (\n doc: OpenAPIObject,\n fn: (op: Record<string, unknown>) => void,\n): void => {\n const paths = doc.paths;\n if (paths === null || typeof paths !== 'object') {\n return;\n }\n for (const pathItem of Object.values(paths)) {\n if (pathItem === null || typeof pathItem !== 'object') {\n continue;\n }\n const pathRecord = pathItem as Record<string, unknown>;\n for (const method of HTTP_METHODS) {\n const op = pathRecord[method];\n if (op === null || typeof op !== 'object') {\n continue;\n }\n fn(op as Record<string, unknown>);\n }\n }\n};\n","/**\n * Visitor invoked for every `{ $ref: string }` node encountered during\n * `walkRefs`. Return a new string to mutate the ref in place; return\n * `undefined` to leave it untouched.\n */\nexport type RefVisitor = (ref: string) => string | undefined;\n\n/**\n * Deeply walks an OpenAPI sub-tree, invoking `visit` on every `$ref` string\n * value. Mutates the tree in place when the visitor returns a replacement.\n */\nexport const walkRefs = (node: unknown, visit: RefVisitor): void => {\n if (node === null || typeof node !== 'object') {\n return;\n }\n if (Array.isArray(node)) {\n for (const item of node) {\n walkRefs(item, visit);\n }\n return;\n }\n const obj = node as Record<string, unknown>;\n for (const key of Object.keys(obj)) {\n const value = obj[key];\n if (key === '$ref' && typeof value === 'string') {\n const next = visit(value);\n if (next !== undefined) {\n obj[key] = next;\n }\n continue;\n }\n walkRefs(value, visit);\n }\n};\n","import type { OpenAPIObject } from '@nestjs/swagger';\nimport type { ZodNestRegistry } from '../schema/registry.js';\n\nimport { isZodDtoMarker } from '../dto/marker.js';\nimport { COMPONENTS_SCHEMAS_PREFIX, ZOD_NEST_DTO_EXTENSION } from '../schema/constants.js';\nimport { HTTP_METHODS } from './http-methods.js';\nimport { walkRefs } from './walk-refs.js';\n\nexport interface CollectedUsage {\n /** dtoIds referenced as input via requestBody / parameters `$ref`s in the doc. */\n inputExposedIds: ReadonlySet<string>;\n /** dtoIds referenced as output via `@ZodResponse` on any controller handler. */\n outputExposedIds: ReadonlySet<string>;\n /** Map of `components.schemas` key (NestJS class name) → dtoId from the marker. */\n classToDtoId: ReadonlyMap<string, string>;\n}\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n\n/**\n * Pre-pass over an `applyZodNest` input. Walks the already-built OpenAPI doc\n * for both input-side ids (`requestBody` / `parameters` `$ref`s, plus query /\n * param marker placeholders) and output-side ids (`responses.*.content.*`\n * `$ref`s — `@ZodResponse`'s swagger bridge emits these via `@ApiResponse`, so\n * the document is the source of truth). Walking the document keeps exposure\n * scoped to the endpoints in *this* document — important when several Swagger\n * documents share one registry.\n */\nexport const collectUsage = (doc: OpenAPIObject, registry: ZodNestRegistry): CollectedUsage => {\n const classToDtoId = buildClassToDtoIdMap(doc);\n const knownIds = new Set(registry.ids());\n const inputExposedIds = collectInputExposedIds(doc, classToDtoId, knownIds);\n const outputExposedIds = collectOutputExposedIds(doc, classToDtoId, knownIds);\n return { inputExposedIds, outputExposedIds, classToDtoId };\n};\n\nconst buildClassToDtoIdMap = (doc: OpenAPIObject): Map<string, string> => {\n const map = new Map<string, string>();\n const schemas = doc.components?.schemas ?? {};\n for (const [className, schema] of Object.entries(schemas)) {\n const marker = readMarker(schema);\n if (marker === undefined) {\n continue;\n }\n map.set(className, marker.dtoId);\n }\n return map;\n};\n\nconst readMarker = (schema: unknown): { dtoId: string } | undefined => {\n if (!isPlainRecord(schema)) {\n return undefined;\n }\n if (!isPlainRecord(schema.properties)) {\n return undefined;\n }\n const marker = schema.properties[ZOD_NEST_DTO_EXTENSION];\n if (!isZodDtoMarker(marker)) {\n return undefined;\n }\n return { dtoId: marker.dtoId };\n};\n\nconst collectInputExposedIds = (\n doc: OpenAPIObject,\n classToDtoId: ReadonlyMap<string, string>,\n knownIds: ReadonlySet<string>,\n): Set<string> => {\n const ids = new Set<string>();\n const paths = doc.paths ?? {};\n for (const pathItem of Object.values(paths)) {\n if (!isPlainRecord(pathItem)) {\n continue;\n }\n for (const operation of operationsOf(pathItem)) {\n collectRefsFromOperation(operation, classToDtoId, knownIds, ids);\n }\n }\n return ids;\n};\n\nconst operationsOf = (pathItem: Record<string, unknown>): Record<string, unknown>[] => {\n const out: Record<string, unknown>[] = [];\n for (const method of HTTP_METHODS) {\n const op = pathItem[method];\n if (isPlainRecord(op)) {\n out.push(op);\n }\n }\n return out;\n};\n\nconst collectRefsFromOperation = (\n operation: Record<string, unknown>,\n classToDtoId: ReadonlyMap<string, string>,\n knownIds: ReadonlySet<string>,\n ids: Set<string>,\n): void => {\n // requestBody.content.*.schema.$ref\n if (isPlainRecord(operation.requestBody)) {\n collectRefsFromContent(operation.requestBody.content, classToDtoId, knownIds, ids);\n }\n // parameters[*].schema.$ref AND parameters[*] marker placeholders\n const parameters = operation.parameters;\n if (Array.isArray(parameters)) {\n for (const param of parameters) {\n if (!isPlainRecord(param)) {\n continue;\n }\n collectRefFromSchema(param.schema, classToDtoId, knownIds, ids);\n collectIdFromMarkerParam(param, ids);\n }\n }\n};\n\nconst collectIdFromMarkerParam = (param: Record<string, unknown>, ids: Set<string>): void => {\n if (param.__zodNestDto !== true) {\n return;\n }\n const dtoId = param.dtoId;\n if (typeof dtoId !== 'string' || dtoId === '') {\n return;\n }\n ids.add(dtoId);\n};\n\nconst collectRefsFromContent = (\n content: unknown,\n classToDtoId: ReadonlyMap<string, string>,\n knownIds: ReadonlySet<string>,\n ids: Set<string>,\n): void => {\n if (!isPlainRecord(content)) {\n return;\n }\n for (const mediaType of Object.values(content)) {\n if (!isPlainRecord(mediaType)) {\n continue;\n }\n collectRefFromSchema(mediaType.schema, classToDtoId, knownIds, ids);\n }\n};\n\nconst collectRefFromSchema = (\n schema: unknown,\n classToDtoId: ReadonlyMap<string, string>,\n knownIds: ReadonlySet<string>,\n ids: Set<string>,\n): void => {\n if (!isPlainRecord(schema)) {\n return;\n }\n // Deep-walk so refs nested inside an inline body (e.g. `@ZodBody` with\n // `flatten: true` emits `{ type: 'object', properties: { p: { $ref } } }`)\n // are seeded too — the closure pass `extendExposureViaRefs` only walks\n // emitted bodies, not inline operation bodies, so it can't pick up\n // nested refs that never lived in `inputSchemas` / `outputSchemas`.\n walkRefs(schema, (ref) => {\n if (!ref.startsWith(COMPONENTS_SCHEMAS_PREFIX)) {\n return undefined;\n }\n const className = ref.slice(COMPONENTS_SCHEMAS_PREFIX.length);\n // Class-DTO refs go through the rename map (NestJS materializes\n // `components.schemas[ClassName]` and the marker says the real dtoId is X).\n // Decorator-emitted refs (`@ZodBody` / `@ZodQuery` / ...) target the id\n // directly with no marker hop — match it against the registry's known ids.\n // Refs to anything else (third-party `@ApiResponse({ schema: { $ref } })`)\n // are left untouched.\n const renamed = classToDtoId.get(className);\n if (renamed !== undefined) {\n ids.add(renamed);\n } else if (knownIds.has(className)) {\n ids.add(className);\n }\n return undefined;\n });\n};\n\nconst collectOutputExposedIds = (\n doc: OpenAPIObject,\n classToDtoId: ReadonlyMap<string, string>,\n knownIds: ReadonlySet<string>,\n): Set<string> => {\n const ids = new Set<string>();\n const paths = doc.paths ?? {};\n for (const pathItem of Object.values(paths)) {\n if (!isPlainRecord(pathItem)) {\n continue;\n }\n for (const operation of operationsOf(pathItem)) {\n collectRefsFromResponses(operation.responses, classToDtoId, knownIds, ids);\n }\n }\n return ids;\n};\n\nconst collectRefsFromResponses = (\n responses: unknown,\n classToDtoId: ReadonlyMap<string, string>,\n knownIds: ReadonlySet<string>,\n ids: Set<string>,\n): void => {\n if (!isPlainRecord(responses)) {\n return;\n }\n for (const response of Object.values(responses)) {\n if (!isPlainRecord(response)) {\n continue;\n }\n collectRefsFromContent(response.content, classToDtoId, knownIds, ids);\n }\n};\n","import { ZodNestError } from '../schema/errors.js';\n\nexport type ZodNestDocumentErrorCode =\n | 'AMBIGUOUS_RENAME'\n | 'DANGLING_REF'\n | 'UNEXPANDABLE_PARAM_DTO';\n\n/**\n * Thrown by `applyZodNest` when the doc cannot be processed cleanly. Surfaces\n * at doc-build time so typos / mis-registrations fail in CI, not at runtime.\n *\n * `AMBIGUOUS_RENAME`: two distinct DTO classes target the same registry id\n * with differing bodies — the rename pass can't write `components.schemas[id]`\n * unambiguously.\n *\n * `DANGLING_REF`: a `$ref` in the doc points at a `components.schemas` key\n * that no longer exists after `applyZodNest`. Usually means a marker was\n * stripped but its rename target wasn't populated, or a user-supplied pre-pass\n * left a stale ref.\n *\n * `UNEXPANDABLE_PARAM_DTO`: a `@Query()` / `@Param()` / `@Headers()` /\n * `@Cookie()` handler argument resolved to a `createZodDto` whose schema is\n * not an object — the marker parameter can't be expanded into individual\n * parameters because there's no top-level `properties` record to iterate.\n */\nexport class ZodNestDocumentError extends ZodNestError {\n readonly code: ZodNestDocumentErrorCode;\n readonly details: Readonly<Record<string, unknown>>;\n\n constructor(\n code: ZodNestDocumentErrorCode,\n message: string,\n details: Record<string, unknown> = {},\n ) {\n super(`[zod-nest] ${code}: ${message}`);\n this.name = 'ZodNestDocumentError';\n this.code = code;\n this.details = details;\n }\n}\n","import type { OpenAPIObject } from '@nestjs/swagger';\nimport type { CollectedUsage } from './collect-usage.js';\n\nimport { COMPONENTS_SCHEMAS_PREFIX } from '../schema/constants.js';\nimport { ZodNestDocumentError } from './errors.js';\nimport { walkRefs } from './walk-refs.js';\n\nexport interface AssertNoDanglingRefsParams {\n doc: OpenAPIObject;\n collected: CollectedUsage;\n}\n\n/**\n * Final assertion pass over the doc. Walks every `$ref` and confirms that\n * any `#/components/schemas/<id>` target exists in `components.schemas`.\n * Throws `ZodNestDocumentError({ code: 'DANGLING_REF' })` listing all\n * offending refs with a per-ref hint inferred from `collected` — whether\n * the id was seen in input/output usage (suggests a registry mismatch) or\n * is otherwise unknown (likely a `meta.id` typo or unregistered DTO).\n *\n * Scoped to `#/components/schemas/` refs only — refs into other component\n * namespaces (`#/components/parameters/...`, `#/components/responses/...`)\n * are user-managed and not validated here.\n */\nexport const assertNoDanglingRefs = (params: AssertNoDanglingRefsParams): void => {\n const { doc, collected } = params;\n const schemas = (doc.components?.schemas ?? {}) as Record<string, unknown>;\n const dangling: string[] = [];\n walkRefs(doc, (ref) => {\n if (!ref.startsWith(COMPONENTS_SCHEMAS_PREFIX)) {\n return undefined;\n }\n const target = ref.slice(COMPONENTS_SCHEMAS_PREFIX.length);\n if (!(target in schemas)) {\n dangling.push(ref);\n }\n return undefined;\n });\n if (dangling.length === 0) {\n return;\n }\n const lines = dangling.map((ref) => ` - ${ref} — ${hintFor(ref, collected)}`);\n throw new ZodNestDocumentError(\n 'DANGLING_REF',\n `Found ${dangling.length} \\`$ref\\` target(s) that don't resolve to a ` +\n 'schema in `components.schemas`. The most common cause is a `meta.id` ' +\n 'typo on a DTO, a DTO used without `createZodDto`, or a `$ref` left ' +\n `behind by a pre-pass that mutated the doc before \\`applyZodNest\\`.\\n${lines.join('\\n')}`,\n { dangling },\n );\n};\n\nconst hintFor = (ref: string, collected: CollectedUsage): string => {\n const id = ref.slice(COMPONENTS_SCHEMAS_PREFIX.length);\n const usedInput = collected.inputExposedIds.has(id);\n const usedOutput = collected.outputExposedIds.has(id);\n if (usedInput && usedOutput) {\n return 'used as input and output but body missing — DTO is registered under a different id';\n }\n if (usedInput) {\n return 'used as input but body missing — DTO is registered under a different id';\n }\n if (usedOutput) {\n return 'used as output but body missing — DTO is registered under a different id';\n }\n return 'no DTO with this id was registered — check for a meta.id typo or a DTO used without createZodDto';\n};\n","import type { OpenAPIObject } from '@nestjs/swagger';\n\nimport { COMPONENTS_SCHEMAS_PREFIX } from '../schema/constants.js';\nimport { ZodNestDocumentError } from './errors.js';\nimport { forEachOperation } from './http-methods.js';\nimport { walkRefs } from './walk-refs.js';\n\n/**\n * How a named `@Query()` / `@ZodQuery` DTO is represented in the OpenAPI doc:\n *\n * - `'expand'` (default) — one parameter per top-level property of the DTO\n * schema, each inlined or `$ref`'d independently.\n * - `'ref'` — a single schema-based query parameter that references the DTO's\n * `components.schemas` entry (`style: 'form'`, `explode: true`,\n * `schema: { $ref }`). The wire format is identical to `'expand'`; only the\n * document representation collapses to the shared component.\n *\n * Query-only: path / header / cookie markers always expand regardless of this\n * setting, since the form-exploded-object pattern is a query serialization.\n */\nexport type QueryParamStyle = 'expand' | 'ref';\n\nexport interface ExpandParamMarkersParams {\n /** OpenAPI doc whose `paths.*.<op>.parameters[]` will be mutated in place. */\n doc: OpenAPIObject;\n /** Bulk-emitted input-side schemas keyed by `dtoId`. Source of truth for `io: 'input'` markers. */\n inputSchemas: ReadonlyMap<string, unknown>;\n /** Bulk-emitted output-side schemas keyed by `dtoId`. Source for the (rare) `io: 'output'` parameter marker. */\n outputSchemas: ReadonlyMap<string, unknown>;\n /**\n * Global preference for how `in: 'query'` DTO markers are represented.\n * Defaults to `'expand'`. A per-marker `ref` override (set by `@ZodQuery`)\n * wins over this when present.\n */\n queryParamStyle?: QueryParamStyle;\n}\n\ninterface MarkerParam extends Record<string, unknown> {\n in: string;\n dtoId: string;\n io: 'input' | 'output';\n /**\n * Per-marker override of `queryParamStyle`. `true` forces the single-`$ref`\n * query parameter, `false` forces per-property expansion, `undefined` falls\n * back to the global preference. Only `@ZodQuery({ ref })` sets it; the\n * `@Query() dto` marker omits it (follows the global preference).\n */\n ref?: boolean;\n}\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n\n/**\n * Replaces every `@Query()` / `@Param()` / `@Headers()` / `@Cookie()` marker\n * parameter — the `__zodNestDto: true` placeholder produced by\n * `createZodDto`'s `_OPENAPI_METADATA_FACTORY` when the DTO class is bound to\n * a non-body decorator — with one parameter per top-level property of the\n * DTO schema.\n *\n * A `'query'` marker is instead collapsed to a single schema-based parameter\n * (`style: 'form'`, `explode: true`, `schema: { $ref }`) when ref mode applies\n * — either the per-marker `ref` override (from `@ZodQuery`) or the global\n * `queryParamStyle: 'ref'` preference. Ref mode is query-only; path / header /\n * cookie markers always expand. See `QueryParamStyle`.\n *\n * Runs after `mergeSchemas` (so the real schema body lives in the\n * `inputSchemas` map, and the DTO's component is in `doc.components.schemas`\n * for ref mode) and before `rewriteRefs` (so any `$ref` inside a property\n * schema gets rewritten in the subsequent pass).\n *\n * After expansion, if `components.schemas.Object` (the synthetic placeholder\n * `@nestjs/swagger` materialises from the marker's `type: () => Object`) has\n * no remaining referrers, the entry is pruned. This matches the cleaner\n * output the predecessor library (`nestjs-zod`) emitted and keeps the doc\n * free of dead schemas.\n *\n * Throws `ZodNestDocumentError('UNEXPANDABLE_PARAM_DTO')` when a marker\n * parameter resolves to a non-object schema (array, union, primitive, …) —\n * those shapes have no `properties` record to iterate, so the only sensible\n * action is to fail loudly at doc-build time.\n */\nexport const expandParamMarkers = (params: ExpandParamMarkersParams): void => {\n const { doc, inputSchemas, outputSchemas } = params;\n const queryParamStyle = params.queryParamStyle ?? 'expand';\n const schemas = doc.components?.schemas;\n const componentIds =\n schemas !== null && typeof schemas === 'object'\n ? new Set(Object.keys(schemas))\n : new Set<string>();\n let expandedAny = false;\n forEachOperation(doc, (op) => {\n const parameters = op.parameters;\n if (!Array.isArray(parameters)) {\n return;\n }\n const next = expandParameterList(parameters, {\n inputSchemas,\n outputSchemas,\n queryParamStyle,\n componentIds,\n });\n if (next !== parameters) {\n op.parameters = next;\n expandedAny = true;\n }\n });\n // The synthetic `components.schemas.Object` only appears when at least one\n // marker parameter was processed by @nestjs/swagger — skip the full-doc\n // ref walk on the common no-marker path.\n if (expandedAny) {\n pruneOrphanObjectSchema(doc);\n }\n};\n\ninterface ExpandContext {\n readonly inputSchemas: ReadonlyMap<string, unknown>;\n readonly outputSchemas: ReadonlyMap<string, unknown>;\n readonly queryParamStyle: QueryParamStyle;\n readonly componentIds: ReadonlySet<string>;\n}\n\nconst expandParameterList = (\n parameters: readonly unknown[],\n context: ExpandContext,\n): readonly unknown[] => {\n let result: unknown[] | undefined;\n for (let i = 0; i < parameters.length; i++) {\n const param = parameters[i];\n const marker = readMarker(param);\n if (marker === undefined) {\n result?.push(param);\n continue;\n }\n if (result === undefined) {\n result = parameters.slice(0, i);\n }\n const map = marker.io === 'output' ? context.outputSchemas : context.inputSchemas;\n const body = map.get(marker.dtoId);\n result.push(...resolveMarker(marker, body, context));\n }\n return result ?? parameters;\n};\n\n/**\n * Decide whether a `'query'` marker collapses to a single schema-based\n * parameter (`ref`) or expands per-property. The per-marker `ref` override\n * wins; otherwise the global `queryParamStyle` decides. Ref mode is query-only\n * and needs the DTO's component to exist in the doc — `collectUsage` adds the\n * marker's dtoId to `inputExposedIds` so `mergeSchemas` emits it. If it somehow\n * still isn't present, fall back to expansion so the contract ships rather than\n * dangling.\n */\nconst resolveMarker = (marker: MarkerParam, body: unknown, context: ExpandContext): unknown[] => {\n const useRef = marker.ref ?? context.queryParamStyle === 'ref';\n if (marker.in === 'query' && useRef && context.componentIds.has(marker.dtoId)) {\n return [buildRefQueryParam(marker, body)];\n }\n return expandOne(marker, body);\n};\n\n/**\n * Build the single schema-based query parameter for `ref` mode. References the\n * DTO's `components.schemas` entry via `$ref`, with `style: 'form'` +\n * `explode: true` so the wire format matches the per-property expansion\n * (`?a=1&b=2`). The parameter is marked `required` when the schema has at\n * least one required field; per-field requiredness stays in the referenced\n * component's `required` array.\n */\nconst buildRefQueryParam = (marker: MarkerParam, body: unknown): Record<string, unknown> => {\n const required = isPlainRecord(body) && Array.isArray(body.required) && body.required.length > 0;\n return {\n name: marker.dtoId,\n in: 'query',\n required,\n style: 'form',\n explode: true,\n schema: { $ref: `${COMPONENTS_SCHEMAS_PREFIX}${marker.dtoId}` },\n };\n};\n\nconst readMarker = (value: unknown): MarkerParam | undefined => {\n if (!isPlainRecord(value)) {\n return undefined;\n }\n if (value.__zodNestDto !== true) {\n return undefined;\n }\n if (typeof value.dtoId !== 'string' || value.dtoId === '') {\n return undefined;\n }\n if (value.io !== 'input' && value.io !== 'output') {\n return undefined;\n }\n if (typeof value.in !== 'string' || value.in === '') {\n return undefined;\n }\n if (value.ref !== undefined && typeof value.ref !== 'boolean') {\n return undefined;\n }\n return value as MarkerParam;\n};\n\nconst expandOne = (marker: MarkerParam, body: unknown): unknown[] => {\n if (!isPlainRecord(body) || !isPlainRecord(body.properties)) {\n throw new ZodNestDocumentError(\n 'UNEXPANDABLE_PARAM_DTO',\n `Cannot expand \\`@${capitalize(marker.in)}() x: ${marker.dtoId}\\` — the DTO's schema is not an object with \\`properties\\`. ` +\n `Non-body parameter DTOs must be object schemas; arrays, unions, primitives, etc. cannot be split into individual ` +\n `parameters. Use \\`@Body()\\` for non-object DTOs, or restructure the schema as an object whose fields become the params.`,\n { dtoId: marker.dtoId, in: marker.in, io: marker.io },\n );\n }\n const properties = body.properties;\n const requiredSet = collectRequired(body.required);\n const out: unknown[] = [];\n for (const [propName, propSchemaRaw] of Object.entries(properties)) {\n if (!isPlainRecord(propSchemaRaw)) {\n continue;\n }\n out.push(buildParameter(marker, propName, propSchemaRaw, requiredSet.has(propName)));\n }\n return out;\n};\n\nconst collectRequired = (value: unknown): Set<string> => {\n if (!Array.isArray(value)) {\n return new Set();\n }\n const out = new Set<string>();\n for (const item of value) {\n if (typeof item === 'string') {\n out.add(item);\n }\n }\n return out;\n};\n\nconst buildParameter = (\n marker: MarkerParam,\n name: string,\n schema: Record<string, unknown>,\n required: boolean,\n): Record<string, unknown> => {\n let effectiveRequired = required;\n if (marker.in === 'path' && !effectiveRequired) {\n // eslint-disable-next-line no-console\n console.warn(\n `[zod-nest] Path parameter \\`${name}\\` on DTO \\`${marker.dtoId}\\` is marked optional ` +\n `in the Zod schema; OpenAPI 3.1 requires path parameters to be required. ` +\n `Coercing \\`required: true\\` so the emitted document is spec-valid. ` +\n `Fix by removing \\`.optional()\\` / \\`.nullish()\\` from the field, or by switching ` +\n `the decorator to @Query() / @Headers() if the field is genuinely optional.`,\n );\n effectiveRequired = true;\n }\n return {\n name,\n in: marker.in,\n required: effectiveRequired,\n schema,\n };\n};\n\nconst capitalize = (value: string): string => value.charAt(0).toUpperCase() + value.slice(1);\n\nconst pruneOrphanObjectSchema = (doc: OpenAPIObject): void => {\n const schemas = doc.components?.schemas as Record<string, unknown> | undefined;\n if (schemas === undefined || !Object.prototype.hasOwnProperty.call(schemas, 'Object')) {\n return;\n }\n let referenced = false;\n const targetRef = `${COMPONENTS_SCHEMAS_PREFIX}Object`;\n walkRefs(doc, (ref) => {\n if (ref === targetRef) {\n referenced = true;\n }\n return undefined;\n });\n if (!referenced) {\n delete schemas.Object;\n }\n};\n","import type { CollectedUsage } from './collect-usage.js';\n\nimport { COMPONENTS_SCHEMAS_PREFIX } from '../schema/constants.js';\nimport { walkRefs } from './walk-refs.js';\n\n/**\n * Closes the input/output exposure sets over `$ref`s. A nested `.meta({ id })`\n * schema declared without `createZodDto` is registered transitively (see\n * `registry.register`) and emitted by `bulkEmit`, but `collectUsage` won't\n * see it directly — it walks request/response bodies and `@ZodResponse`\n * metadata, not nested refs. Without this closure, `mergeSchemas` would\n * skip the nested body, leaving a dangling `$ref` in the final document.\n */\nexport const extendExposureViaRefs = (\n collected: CollectedUsage,\n inputSchemas: ReadonlyMap<string, unknown>,\n outputSchemas: ReadonlyMap<string, unknown>,\n): CollectedUsage => ({\n ...collected,\n inputExposedIds: closeOverRefs(collected.inputExposedIds, inputSchemas),\n outputExposedIds: closeOverRefs(collected.outputExposedIds, outputSchemas),\n});\n\n/**\n * BFS over `$ref`s starting from `seed`. For each `#/components/schemas/<id>`\n * encountered in a body, the target id joins the result and its own body is\n * scanned. Refs into other component buckets (`parameters`, `responses`, …)\n * are ignored — exposure closure only governs the schemas bucket. Ids that\n * appear in `seed` but not in `bodies` are kept (they may exist on the\n * other I/O side); they just don't contribute further reachable ids.\n */\nexport const closeOverRefs = (\n seed: ReadonlySet<string>,\n bodies: ReadonlyMap<string, unknown>,\n): Set<string> => {\n const out = new Set(seed);\n const queue = [...seed];\n while (queue.length > 0) {\n const id = queue.shift() as string;\n const body = bodies.get(id);\n if (body === undefined) {\n continue;\n }\n walkRefs(body, (ref) => {\n if (!ref.startsWith(COMPONENTS_SCHEMAS_PREFIX)) {\n return undefined;\n }\n const target = ref.slice(COMPONENTS_SCHEMAS_PREFIX.length);\n if (out.has(target)) {\n return undefined;\n }\n out.add(target);\n queue.push(target);\n return undefined;\n });\n }\n return out;\n};\n","/**\n * Suffix appended to a dtoId when its input and output emissions diverge —\n * input keeps the canonical id, output lifts to `<id>Output`.\n */\nexport const OUTPUT_SUFFIX = 'Output';\n","import type { OpenAPIObject } from '@nestjs/swagger';\nimport type { ZodNestRegistry } from '../schema/registry.js';\n\nimport { COMPONENTS_SCHEMAS_PREFIX } from '../schema/constants.js';\nimport { OUTPUT_SUFFIX } from './constants.js';\n\nexport interface InlineAnonymousBodiesParams {\n /** OpenAPI doc whose anonymous `$ref`s will be inlined in place. */\n doc: OpenAPIObject;\n /** Registry whose `anonymousIds()` identify the synthetic placeholder ids. */\n registry: ZodNestRegistry;\n}\n\n/**\n * Inlines every anonymous schema's body at its `$ref` site(s) and prunes the\n * synthetic component. An anonymous id is the placeholder minted for a schema\n * passed inline to `@ZodResponse` / `@ZodBody` with no resolvable id; it exists\n * only to carry the body through `bulkEmit` (so the body honors the document's\n * `strict` / `override`). By the time this runs the body has been written to\n * `components.schemas[id]` and cleaned by `stripMarkers`, so we clone it into\n * each referrer and drop the component.\n *\n * Runs after `mergeSchemas` + `rewriteRefs` + `stripMarkers`, before\n * `assertNoDanglingRefs`. The inlined body's nested member `$ref`s point at\n * real, exposed components (closed over by `extendExposureViaRefs`), so the\n * dangling-ref assertion still passes.\n *\n * A reused anonymous instance (same schema across N referrers) has its body\n * duplicated at each site — the author adds `.meta({ id })` to share it as a\n * named component instead. Both the canonical id and its divergent\n * `<id>Output` sibling (if input/output diverged) are inlined and pruned.\n */\nexport const inlineAnonymousBodies = ({ doc, registry }: InlineAnonymousBodiesParams): void => {\n const anonIds = registry.anonymousIds();\n if (anonIds.length === 0) {\n return;\n }\n const schemas = doc.components?.schemas;\n if (schemas === undefined) {\n return;\n }\n\n // Map each anonymous `$ref` string to the body it should be replaced with.\n // Include the `<id>Output` sibling so a schema used on both the input and\n // output side (and split by the I/O truth table) is inlined on both.\n const bodyByRef = new Map<string, Record<string, unknown>>();\n for (const anonId of anonIds) {\n for (const key of [anonId, `${anonId}${OUTPUT_SUFFIX}`]) {\n const body = schemas[key];\n if (isPlainRecord(body)) {\n bodyByRef.set(`${COMPONENTS_SCHEMAS_PREFIX}${key}`, body);\n }\n }\n }\n if (bodyByRef.size === 0) {\n return;\n }\n\n // Inline only within `paths` — anonymous ids are top-level body/response\n // placeholders, never referenced from another component schema.\n inlineRefs(doc.paths, bodyByRef);\n\n for (const ref of bodyByRef.keys()) {\n delete schemas[ref.slice(COMPONENTS_SCHEMAS_PREFIX.length)];\n }\n};\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n\n/**\n * Replaces every `{ $ref }` node whose target is in `bodyByRef` with a deep\n * clone of the body, in place. Does not recurse into a freshly-inlined body —\n * its refs are real member refs that must stay as `$ref`s.\n */\nconst inlineRefs = (\n node: unknown,\n bodyByRef: ReadonlyMap<string, Record<string, unknown>>,\n): void => {\n if (Array.isArray(node)) {\n for (const item of node) {\n inlineRefs(item, bodyByRef);\n }\n return;\n }\n if (!isPlainRecord(node)) {\n return;\n }\n const ref = node.$ref;\n if (typeof ref === 'string') {\n const body = bodyByRef.get(ref);\n if (body !== undefined) {\n for (const key of Object.keys(node)) {\n delete node[key];\n }\n Object.assign(node, structuredClone(body));\n return;\n }\n }\n for (const value of Object.values(node)) {\n inlineRefs(value, bodyByRef);\n }\n};\n","import stringify from 'fast-json-stable-stringify';\n\nimport type { OpenAPIObject } from '@nestjs/swagger';\nimport type { CollectedUsage } from './collect-usage.js';\n\nimport { isZodDtoMarker } from '../dto/marker.js';\nimport {\n ZOD_NEST_DTO_EXTENSION,\n ZOD_NEST_ERROR_DUPLICATE_ID,\n ZOD_NEST_ERROR_EXTENSION,\n} from '../schema/constants.js';\nimport { OUTPUT_SUFFIX } from './constants.js';\nimport { ZodNestDocumentError } from './errors.js';\n\nexport interface MergeSchemasParams {\n /** OpenAPI doc whose `components.schemas` will be mutated in place. */\n doc: OpenAPIObject;\n inputSchemas: ReadonlyMap<string, unknown>;\n outputSchemas: ReadonlyMap<string, unknown>;\n collected: CollectedUsage;\n /** Result of `registry.getCollisions()` — ids registered with two or more Zod schemas. */\n collisions: ReadonlyMap<string, ReadonlySet<unknown>>;\n}\n\nexport interface MergeSchemasResult {\n /** dtoIds whose input and output schemas diverged — output landed at `<id>Output`. */\n divergentOutputIds: ReadonlySet<string>;\n /** `className → dtoId` map for renames where they differ. */\n renames: ReadonlyMap<string, string>;\n}\n\n/**\n * Applies the I/O suffix truth table and class-name → dtoId rename pass to\n * the doc's `components.schemas`. Mutates the doc in place.\n *\n * Truth table per id (in `inputExposedIds ∪ outputExposedIds`):\n * - input-only → `components.schemas[id] = inputSchemas[id]`\n * - output-only → `components.schemas[id] = outputSchemas[id]`\n * - both & byte-equal → write either as `components.schemas[id]`\n * - both & differ → input as `id`, output as `<id>Output`\n *\n * Rename pass: for every `className → dtoId` mapping from the markers, if\n * `className !== dtoId` and the `className` key still exists in\n * `components.schemas`, delete it. The rename targets (`dtoId`) have already\n * been written by the truth-table step.\n *\n * Collision pass (parity with `engine.ts:62`): for every id in `collisions`,\n * replace its body in `components.schemas` with the duplicate-id error marker\n * so the broken contract is visible in Swagger UI.\n */\nexport const mergeSchemas = (params: MergeSchemasParams): MergeSchemasResult => {\n const { doc, inputSchemas, outputSchemas, collected, collisions } = params;\n const schemas = ensureComponentsSchemas(doc);\n const renames = new Map<string, string>();\n const divergentOutputIds = new Set<string>();\n\n const exposedIds = new Set([...collected.inputExposedIds, ...collected.outputExposedIds]);\n\n for (const id of exposedIds) {\n applyTruthTable(\n schemas,\n id,\n collected.inputExposedIds.has(id),\n collected.outputExposedIds.has(id),\n inputSchemas.get(id),\n outputSchemas.get(id),\n divergentOutputIds,\n );\n }\n\n for (const [className, dtoId] of collected.classToDtoId) {\n if (className === dtoId) {\n continue;\n }\n renames.set(className, dtoId);\n delete schemas[className];\n }\n\n applyCollisionDecoration(schemas, collisions, divergentOutputIds);\n\n return { divergentOutputIds, renames };\n};\n\nconst ensureComponentsSchemas = (doc: OpenAPIObject): Record<string, unknown> => {\n const components = (doc.components ?? {}) as Record<string, unknown>;\n doc.components = components as OpenAPIObject['components'];\n const schemas = (components.schemas ?? {}) as Record<string, unknown>;\n components.schemas = schemas;\n return schemas;\n};\n\nconst applyTruthTable = (\n schemas: Record<string, unknown>,\n id: string,\n inputExposed: boolean,\n outputExposed: boolean,\n inputBody: unknown,\n outputBody: unknown,\n divergentOutputIds: Set<string>,\n): void => {\n if (inputExposed && !outputExposed) {\n writeOrThrowAmbiguous(schemas, id, inputBody);\n return;\n }\n if (!inputExposed && outputExposed) {\n writeOrThrowAmbiguous(schemas, id, outputBody);\n return;\n }\n // Both exposed.\n if (canonicalEqual(inputBody, outputBody)) {\n writeOrThrowAmbiguous(schemas, id, inputBody);\n return;\n }\n writeOrThrowAmbiguous(schemas, id, inputBody);\n writeOrThrowAmbiguous(schemas, `${id}${OUTPUT_SUFFIX}`, outputBody);\n divergentOutputIds.add(id);\n};\n\nconst writeOrThrowAmbiguous = (\n schemas: Record<string, unknown>,\n key: string,\n body: unknown,\n): void => {\n if (body === undefined) {\n return;\n }\n const existing = schemas[key];\n if (existing === undefined || isMarkerPlaceholder(existing) || canonicalEqual(existing, body)) {\n schemas[key] = body;\n return;\n }\n throw new ZodNestDocumentError(\n 'AMBIGUOUS_RENAME',\n `Two distinct schemas target \\`components.schemas[${key}]\\` with differing bodies — ` +\n 'multiple createZodDto classes likely share the same dtoId. Set distinct `options.id` ' +\n 'values, or align the class names so renames are unambiguous.',\n { key },\n );\n};\n\nconst isMarkerPlaceholder = (value: unknown): boolean => {\n if (value === null || typeof value !== 'object') {\n return false;\n }\n const properties = (value as { properties?: unknown }).properties;\n if (properties === null || typeof properties !== 'object') {\n return false;\n }\n const marker = (properties as Record<string, unknown>)[ZOD_NEST_DTO_EXTENSION];\n return isZodDtoMarker(marker);\n};\n\nconst canonicalEqual = (a: unknown, b: unknown): boolean => {\n if (a === b) {\n return true;\n }\n if (a === undefined || b === undefined) {\n return false;\n }\n return stringify(a) === stringify(b);\n};\n\nconst applyCollisionDecoration = (\n schemas: Record<string, unknown>,\n collisions: ReadonlyMap<string, ReadonlySet<unknown>>,\n divergentOutputIds: ReadonlySet<string>,\n): void => {\n for (const [id] of collisions) {\n decorateIfPresent(schemas, id);\n if (divergentOutputIds.has(id)) {\n decorateIfPresent(schemas, `${id}${OUTPUT_SUFFIX}`);\n }\n }\n};\n\nconst decorateIfPresent = (schemas: Record<string, unknown>, key: string): void => {\n if (!(key in schemas)) {\n return;\n }\n schemas[key] = {\n description: `ERROR: duplicate zod-nest id <${key.replace(/Output$/, '')}>`,\n [ZOD_NEST_ERROR_EXTENSION]: ZOD_NEST_ERROR_DUPLICATE_ID,\n };\n};\n","import type { OpenAPIObject } from '@nestjs/swagger';\n\nimport { COMPONENTS_SCHEMAS_PREFIX } from '../schema/constants.js';\nimport { OUTPUT_SUFFIX } from './constants.js';\nimport { HTTP_METHODS } from './http-methods.js';\nimport { walkRefs } from './walk-refs.js';\n\nexport interface RewriteRefsParams {\n doc: OpenAPIObject;\n /** className → dtoId map from `mergeSchemas`. */\n renames: ReadonlyMap<string, string>;\n /** dtoIds whose output emission landed at `<id>Output`. */\n divergentOutputIds: ReadonlySet<string>;\n}\n\n/**\n * Single rewrite pass over the doc:\n *\n * 1. **Rename pass (whole doc)** — any `$ref` whose target id is in\n * `renames` gets rewritten from `#/components/schemas/<className>` to\n * `#/components/schemas/<dtoId>`. This applies in operations, parameters,\n * requestBody, responses, nested schemas, anywhere.\n * 2. **Output-suffix pass (responses only)** — within\n * `paths.*.{op}.responses.*`, any `$ref` whose (post-rename) target id\n * is in `divergentOutputIds` gets rewritten to\n * `#/components/schemas/<id>Output`. Scoped to response sub-trees so\n * input-side refs to the same id keep pointing at the canonical id.\n *\n * Ordering is significant: pass 1 runs first so pass 2 sees already-renamed\n * (dtoId-keyed) refs and only matches against `divergentOutputIds`.\n */\nexport const rewriteRefs = (params: RewriteRefsParams): void => {\n const { doc, renames, divergentOutputIds } = params;\n\n if (renames.size > 0) {\n walkRefs(doc, (ref) => {\n if (!ref.startsWith(COMPONENTS_SCHEMAS_PREFIX)) {\n return undefined;\n }\n const target = ref.slice(COMPONENTS_SCHEMAS_PREFIX.length);\n const renamed = renames.get(target);\n if (renamed === undefined) {\n return undefined;\n }\n return `${COMPONENTS_SCHEMAS_PREFIX}${renamed}`;\n });\n }\n\n if (divergentOutputIds.size === 0) {\n return;\n }\n\n const paths = doc.paths ?? {};\n for (const pathItem of Object.values(paths)) {\n if (pathItem === null || typeof pathItem !== 'object') {\n continue;\n }\n rewriteResponseSubtree(pathItem as Record<string, unknown>, divergentOutputIds);\n }\n};\n\nconst rewriteResponseSubtree = (\n pathItem: Record<string, unknown>,\n divergentOutputIds: ReadonlySet<string>,\n): void => {\n for (const method of HTTP_METHODS) {\n const op = pathItem[method];\n if (op === null || typeof op !== 'object') {\n continue;\n }\n const responses = (op as { responses?: unknown }).responses;\n if (responses === null || typeof responses !== 'object') {\n continue;\n }\n walkRefs(responses, (ref) => {\n if (!ref.startsWith(COMPONENTS_SCHEMAS_PREFIX)) {\n return undefined;\n }\n const target = ref.slice(COMPONENTS_SCHEMAS_PREFIX.length);\n if (!divergentOutputIds.has(target)) {\n return undefined;\n }\n return `${COMPONENTS_SCHEMAS_PREFIX}${target}${OUTPUT_SUFFIX}`;\n });\n }\n};\n","import type { OpenAPIObject } from '@nestjs/swagger';\n\nimport { isZodDtoMarker } from '../dto/marker.js';\nimport { ZOD_NEST_DTO_EXTENSION } from '../schema/constants.js';\nimport { forEachOperation } from './http-methods.js';\n\n/**\n * Removes `x-zod-nest-dto` placeholder entries from every\n * `components.schemas[K].properties` block, drops the JSON Schema 2020-12\n * metadata (`$schema`, `$id`) that Zod's bulk emission leaks onto every\n * component body, and removes any stray marker parameter that\n * `expandParamMarkers` left behind. Used as the final cleanup pass after\n * `mergeSchemas` + `expandParamMarkers` + `rewriteRefs`.\n *\n * In practice the schema marker has already been overwritten or its key\n * dropped by `mergeSchemas` whenever the DTO is exposed. The straggler case\n * is a registered DTO whose `dtoId === className` AND who was never exposed\n * (no `@Body` reference, no `@ZodResponse`) — `mergeSchemas` leaves the\n * marker in place, this pass strips it.\n *\n * The parameter strip is belt-and-braces — `expandParamMarkers` already\n * removes the marker placeholders by replacing them with expanded entries.\n * This pass catches anything that somehow slipped through (e.g. a future\n * caller that bypasses `applyZodNest`'s pipeline).\n *\n * The `$schema` / `$id` strip exists because Zod v4's bulk `toJSONSchema`\n * writes `$schema: \"https://json-schema.org/draft/2020-12/schema\"` and a\n * relative-URI-fragment `$id` (`#/components/schemas/<Id>`) onto every\n * emitted body. Swagger UI's strict ref resolver chokes on the `$id`\n * fragment — it re-anchors lookups against the leaf schema and then fails\n * to find `components` at the new root. The fields are redundant inside\n * OpenAPI anyway: the schema's identity comes from its `components.schemas`\n * key. We delete both.\n *\n * When the marker is the only property, the empty `properties` block is\n * dropped too. The `x-zod-nest-error` extension (engine collision policy)\n * is intentionally preserved so the broken contract stays visible in\n * Swagger UI.\n */\nexport const stripMarkers = (doc: OpenAPIObject): void => {\n const schemas = doc.components?.schemas;\n if (schemas !== undefined) {\n for (const schema of Object.values(schemas)) {\n stripMarkerFromSchema(schema);\n dropJsonSchemaMetadata(schema);\n }\n }\n stripMarkerParameters(doc);\n};\n\nconst dropJsonSchemaMetadata = (schema: unknown): void => {\n if (schema === null || typeof schema !== 'object') {\n return;\n }\n const body = schema as { $schema?: unknown; $id?: unknown };\n delete body.$schema;\n delete body.$id;\n};\n\nconst stripMarkerParameters = (doc: OpenAPIObject): void => {\n forEachOperation(doc, (op) => {\n const parameters = op.parameters;\n if (!Array.isArray(parameters)) {\n return;\n }\n op.parameters = parameters.filter((param) => !isZodDtoMarker(param));\n });\n};\n\nconst stripMarkerFromSchema = (schema: unknown): void => {\n if (schema === null || typeof schema !== 'object') {\n return;\n }\n const properties = (schema as { properties?: unknown }).properties;\n if (properties === null || typeof properties !== 'object') {\n return;\n }\n const props = properties as Record<string, unknown>;\n if (!(ZOD_NEST_DTO_EXTENSION in props)) {\n return;\n }\n delete props[ZOD_NEST_DTO_EXTENSION];\n if (Object.keys(props).length === 0) {\n delete (schema as { properties?: unknown }).properties;\n }\n};\n","import type { OpenAPIObject } from '@nestjs/swagger';\nimport type { Override } from '../schema/override.js';\nimport type { ZodNestRegistry } from '../schema/registry.js';\nimport type { CollectedUsage } from './collect-usage.js';\nimport type { QueryParamStyle } from './expand-param-markers.js';\n\nimport { defaultRegistry } from '../schema/registry.js';\nimport { bulkEmit } from './bulk-emit.js';\nimport { collectUsage } from './collect-usage.js';\nimport { assertNoDanglingRefs } from './dangling-refs.js';\nimport { expandParamMarkers } from './expand-param-markers.js';\nimport { extendExposureViaRefs } from './expose-closure.js';\nimport { inlineAnonymousBodies } from './inline-anon.js';\nimport { mergeSchemas } from './merge-schemas.js';\nimport { rewriteRefs } from './rewrite-refs.js';\nimport { stripMarkers } from './strip-markers.js';\n\nconst withForcedExposure = (\n collected: CollectedUsage,\n registry: ZodNestRegistry,\n): CollectedUsage => {\n // Exposure is reachability-scoped: only ids actually referenced by this\n // document's endpoints (and their transitive `$ref` deps) are emitted.\n // `{ expose: true }` is the author's explicit opt-in to document a schema\n // that no endpoint references — seed those onto the input side (the default\n // documentation side) so the closure pass pulls in their deps too.\n const forced = registry.forceExposedIds();\n if (forced.length === 0) {\n return collected;\n }\n return {\n inputExposedIds: new Set([...collected.inputExposedIds, ...forced]),\n outputExposedIds: collected.outputExposedIds,\n classToDtoId: collected.classToDtoId,\n };\n};\n\nconst OPENAPI_VERSION = '3.1.0';\n\nexport interface ApplyZodNestOptions {\n /**\n * `ZodNestRegistry` instance that holds the zod-nest DTOs. Defaults to\n * `defaultRegistry` (the process-wide singleton populated by `createZodDto`).\n * Pass an explicit registry for multi-app isolation.\n */\n registry?: ZodNestRegistry;\n /** User override pipe applied on top of the built-in override during emission. */\n override?: Override;\n /**\n * Strict mode (default `true`) throws `ZodNestUnrepresentableError` on\n * unrepresentable Zod constructs (bigint / date / symbol / transform / ...).\n * Set to `false` to emit `{}` for those instead.\n */\n strict?: boolean;\n /**\n * How named `@Query()` / `@ZodQuery` DTOs are represented in the document\n * (default `'expand'`):\n *\n * - `'expand'` — one query parameter per top-level property of the DTO.\n * - `'ref'` — a single schema-based query parameter referencing the DTO's\n * `components.schemas` entry (`style: 'form'`, `explode: true`). The wire\n * format is unchanged; only the spec representation collapses to the\n * shared component. Note: Swagger UI renders the two forms differently.\n *\n * Query-only — path / header / cookie DTOs always expand. A per-handler\n * `@ZodQuery({ ref })` override takes precedence over this preference.\n */\n queryParamStyle?: QueryParamStyle;\n}\n\n/**\n * Post-processor over the OpenAPI document emitted by\n * `SwaggerModule.createDocument`. Mutates the doc in place AND returns it for\n * compositional convenience. After this runs:\n *\n * - Every `components.schemas[<DtoClassName>]` placeholder with an\n * `x-zod-nest-dto` marker is replaced by the Zod-derived JSON Schema body,\n * keyed by the marker's `dtoId` (renaming as needed).\n * - Every `@Query()` / `@Param()` / `@Headers()` / `@Cookie()` marker\n * parameter is expanded into one parameter per top-level property of the\n * DTO's schema (`expandParamMarkers`) — except `@Query()` DTOs under\n * `queryParamStyle: 'ref'` (or a `@ZodQuery({ ref: true })` override), which\n * collapse to a single `$ref` schema-based query parameter. The synthetic\n * `components.schemas.Object` that `@nestjs/swagger` materialises for the\n * marker placeholder is pruned when it has no remaining referrers.\n * - The I/O suffix truth table is applied — equal input/output bodies collapse\n * to one `components.schemas[id]`; divergent bodies split as\n * `id` (input) + `idOutput` (output), with response-side refs rewritten.\n * - Anonymous body/response schemas (no `.meta({ id })`) are inlined at their\n * `$ref` sites and their synthetic components pruned (`inlineAnonymousBodies`).\n * - Only schemas reachable from this document's endpoints (plus their\n * transitive `$ref` deps, plus any `{ expose: true }` opt-ins) are kept —\n * unreferenced registered schemas are pruned. Exposure is document-scoped, so\n * several documents sharing one registry each carry only what they use.\n * - Every `$ref` whose target is missing throws `ZodNestDocumentError(DANGLING_REF)`.\n * - `doc.openapi` is set to `'3.1.0'` — zod-nest emits OpenAPI 3.1 only; this\n * guarantees the version string matches the emitted body regardless of the\n * `DocumentBuilder` configuration on the caller side.\n *\n * Composable with other doc-transform passes — apply other mutations before\n * or after this function.\n */\nexport const applyZodNest = (doc: OpenAPIObject, opts: ApplyZodNestOptions = {}): OpenAPIObject => {\n const registry = opts.registry ?? defaultRegistry;\n\n const collected = collectUsage(doc, registry);\n // Reachability-scoped exposure: `collectUsage` seeds what the document's\n // endpoints actually reference; `{ expose: true }` opt-ins are added on top.\n const exposed = withForcedExposure(collected, registry);\n const { inputSchemas, outputSchemas } = bulkEmit({\n registry,\n override: opts.override,\n strict: opts.strict,\n });\n const extended = extendExposureViaRefs(exposed, inputSchemas, outputSchemas);\n const { divergentOutputIds, renames } = mergeSchemas({\n doc,\n inputSchemas,\n outputSchemas,\n collected: extended,\n collisions: registry.getCollisions(),\n });\n expandParamMarkers({ doc, inputSchemas, outputSchemas, queryParamStyle: opts.queryParamStyle });\n rewriteRefs({ doc, renames, divergentOutputIds });\n stripMarkers(doc);\n inlineAnonymousBodies({ doc, registry });\n assertNoDanglingRefs({ doc, collected: extended });\n doc.openapi = OPENAPI_VERSION;\n\n return doc;\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/schema/constants.ts","../src/schema/discover-dependents.ts","../src/schema/registry.ts","../src/schema/composition.ts","../src/schema/custom-override.ts","../src/schema/errors.ts","../src/schema/override.ts","../src/schema/post-process.ts","../src/schema/engine.ts","../src/dto/marker.ts","../src/dto/symbols.ts","../src/dto/output-dto.ts","../src/dto/create-zod-dto.ts","../src/dto/predicates.ts","../src/exceptions/serialization.exception.ts","../src/exceptions/validation.exception.ts","../src/logging/validation-logger.ts","../src/response/stream.ts","../src/module/options.ts","../src/pipes/validation.pipe.ts","../src/response/default-status.ts","../src/response/metadata.ts","../src/schema/anon-id.ts","../src/response/normalize-type.ts","../src/decorators/zod-response.swagger-bridge.ts","../src/decorators/zod-response.decorator.ts","../src/decorators/internal/zod-schema-ref.ts","../src/decorators/internal/zod-param-expand.ts","../src/decorators/internal/flatten-intersection.ts","../src/decorators/zod-body.decorator.ts","../src/decorators/internal/query-marker.ts","../src/decorators/zod-query.decorator.ts","../src/decorators/internal/constants.ts","../src/decorators/zod-headers.decorator.ts","../src/decorators/zod-cookies.decorator.ts","../src/interceptors/serializer.interceptor.ts","../src/module/zod-nest.module.ts","../src/document/bulk-emit.ts","../src/document/http-methods.ts","../src/document/walk-refs.ts","../src/document/collect-usage.ts","../src/document/errors.ts","../src/document/dangling-refs.ts","../src/document/expand-param-markers.ts","../src/document/expose-closure.ts","../src/document/constants.ts","../src/document/inline-anon.ts","../src/document/merge-schemas.ts","../src/document/ref-titles.ts","../src/document/rewrite-refs.ts","../src/document/strip-markers.ts","../src/document/apply-zod-nest.ts"],"names":["COMPONENTS_SCHEMAS_PREFIX","DEFS_PREFIX","ZOD_NEST_ERROR_EXTENSION","ZOD_NEST_ERROR_DUPLICATE_ID","ZOD_NEST_DTO_EXTENSION","INNER_TYPE_WRAPPERS","Set","readId","schema","meta","z","globalRegistry","get","undefined","id","collectChildren","def","_zod","type","out","shape","value","Object","values","push","catchall","element","options","map","opt","left","right","items","it","rest","keyType","valueType","in","getter","has","innerType","discoverDependents","visited","WeakSet","stack","length","current","pop","add","child","createRegistry","seen","Map","forceExposed","anonymous","recordOnce","set","zodRegistry","register","flags","expose","existing","childId","hasCollision","size","getCollisions","ids","keys","forceExposedIds","anonymousIds","defaultRegistry","registerSchema","registry","explicit","metaId","lineageMap","WeakMap","propsMap","OPTIONAL_WRAPPER_TYPES","isOptionalProp","propSchema","computeShapeKeys","properties","required","filter","key","extend","parent","build","result","op","getLineage","DEFAULT_BUILD_REF","createCompositionOverride","opts","buildRef","ctx","jsonSchema","zodSchema","entry","parentCache","parentId","childProps","childRequired","parentPropSet","parentReqSet","deltaProps","entries","deltaRequired","delta","additionalProperties","allOf","$ref","unevaluatedProperties","customOverrideMap","isWrapper","arg","overrideJSONSchema","overrideSchema","input","output","schemaDescription","description","peekRegistration","createCustomOverride","io","record","fragment","Reflect","deleteProperty","assign","ZodNestError","Error","message","name","ZodNestUnrepresentableError","path","zodType","formatPath","String","join","primitiveOverride","format","combine","overrides","list","candidate","o","rewriteRefs","node","selfRef","Array","isArray","item","obj","ref","startsWith","slice","postProcess","raw","refs","rawDefs","$defs","body","root","$schema","STRICT_REQUIRES_OVERRIDE","isStrictlyUnrepresentable","markPipeCoverage","covered","target","traits","buildToJsonSchemaOptions","params","strict","compositionOverride","uri","customOverride","merged","override","unrepresentableHits","coveredByPipe","wrapped","unrepresentable","metadata","cycles","reused","consumeUnrepresentable","firstHit","find","hit","toOpenApi","built","toJSONSchema","makeZodDtoMarker","dtoId","__zodNestDto","isZodDtoMarker","ZOD_DTO_SYMBOL","Symbol","for","outputCache","buildSiblingClass","SiblingClass","Output","parse","safeParse","_OPENAPI_METADATA_FACTORY","defineProperty","configurable","resolveOutput","cached","sibling","anonCounter","warnedOnAnonymous","resolveFallbackId","className","fallback","console","warn","createZodDto","cachedId","ensureRegistered","named","ZodDtoBase","isZodDto","isZodSchema","ZodType","ZodSerializationException","InternalServerErrorException","zodError","executionContext","statusCode","HttpStatus","INTERNAL_SERVER_ERROR","cause","ZodValidationException","BadRequestException","argMetadata","BAD_REQUEST","errors","treeifyError","DEFAULT_LOGGER_CONTEXT","REDACTED","PREVIEW_RESERVE_BYTES","noopLogValidationFailure","isPlainRecord","CIRCULAR","redactValue","redactSet","toLowerCase","capLoggedValue","maxBytes","serialized","JSON","stringify","_truncated","_originalBytes","_reason","byteSize","Buffer","byteLength","previewBudget","Math","max","_preview","loggerContextFor","side","messageFor","createValidationLogger","redactKeys","logger","err","redacted","sized","maxLoggedValueBytes","payload","dto","status","handler","argType","loggerContext","severity","error","DEFAULT_CONTENT_TYPE","DEFAULT_STREAM_CONTENT_TYPES","PREFIX_WILDCARD_SUFFIX","normalizeContentType","contentType","semicolonIndex","indexOf","mediaType","trim","normalizeStreamMatcher","contentTypes","exact","prefixes","normalized","endsWith","DEFAULT_STREAM_MATCHER","matchesStream","matcher","prefix","isHeaderEntry","headerContentType","headers","getMetadata","HEADERS_METADATA","resolveContentType","variant","fromHeader","isStreamResponse","stream","DEFAULT_REDACT_KEYS","DEFAULT_MAX_LOGGED_VALUE_BYTES","ZOD_NEST_OPTIONS","resolveLogFlags","validationLogs","normalizeZodNestOptions","Logger","loggerOpts","streamMatcher","streamContentTypes","createValidationException","createSerializationException","logInputFailure","logOutputFailure","isOptionsObject","defaultExceptionFactory","ZodValidationPipe","explicitSchema","explicitDtoName","moduleOptions","parsed","parseArg","dtoName","factory","transform","resolveSchema","safeParseAsync","success","data","resolveDtoLabel","metatype","optionSchema","resolvedSchema","POST_DEFAULT_STATUS","GENERIC_DEFAULT_STATUS","defaultStatusFor","httpCode","HTTP_CODE_METADATA","method","METHOD_METADATA","RequestMethod","POST","resolveEffectiveStatus","ZOD_RESPONSES_METADATA_KEY","appendResponseVariant","defineMetadata","ANON_RESPONSE_PREFIX","ANON_BODY_PREFIX","anonIdCache","counter","resolveAnonId","responseDtoCache","schemaToOutputDto","namedId","anonId","toResponseDto","index","where","TypeError","extractDescriptionFields","desc","links","asDtoFunction","buildApiResponseOptions","base","buildTupleSchema","dtos","prefixItems","d","getSchemaPath","buildContentResponseOptions","content","applyCustomContentResponse","propertyKey","descriptor","kind","ApiExtraModels","ApiResponse","applySwaggerResponseDecorator","effectiveStatus","effectiveContentType","buildArrayKind","headEntry","restEntries","head","validationSchema","array","tupleSchemas","tuple","buildKind","normaliseStatus","ZodResponse","passthroughOnError","swaggerDescriptor","queueMicrotask","resolveSchemaRef","deferAnonInline","isZodObject","expandObjectSchema","decoratorName","resolution","forceRequired","paramSchemaBody","intersectionArms","unionOptions","collectObjectShapes","shapes","unionCrossed","allShapes","variantResult","arms","flattenObjectIntersection","collected","mergedShape","optional","object","ZodBody","apiBodySchema","resolveBodySchema","ApiBody","flatten","API_PARAMETERS_METADATA_KEY","appendQueryMarker","_target","_propertyKey","marker","ZodQuery","expanded","applyDecorators","ApiQuery","API_PARAMETERS_KEY","ZodHeaders","newEntries","ZodCookies","defaultSerializationFactory","formatDtoLabel","formatHandlerLabel","context","getClass","getHandler","matchesWildcard","wildcard","charCodeAt","floor","selectVariant","variants","effective","ZodSerializerInterceptor","reflector","intercept","next","getType","handle","pipe","mergeMap","from","response","switchToHttp","getResponse","isSoft","ZodNestModule","forRoot","module","global","providers","provide","useValue","APP_PIPE","useClass","APP_INTERCEPTOR","exports","URI","bulkEmit","knownIds","inputSchemas","runPass","outputSchemas","filtered","schemas","HTTP_METHODS","forEachOperation","doc","fn","paths","pathItem","pathRecord","walkRefs","visit","collectUsage","classToDtoId","buildClassToDtoIdMap","inputExposedIds","collectInputExposedIds","outputExposedIds","collectOutputExposedIds","components","readMarker","operation","operationsOf","collectRefsFromOperation","requestBody","collectRefsFromContent","parameters","param","collectRefFromSchema","collectIdFromMarkerParam","renamed","collectRefsFromResponses","responses","ZodNestDocumentError","code","details","assertNoDanglingRefs","dangling","lines","hintFor","usedInput","usedOutput","expandParamMarkers","queryParamStyle","componentIds","expandedAny","expandParameterList","pruneOrphanObjectSchema","i","resolveMarker","useRef","buildRefQueryParam","expandOne","style","explode","capitalize","requiredSet","collectRequired","propName","propSchemaRaw","buildParameter","effectiveRequired","charAt","toUpperCase","prototype","hasOwnProperty","call","referenced","targetRef","extendExposureViaRefs","closeOverRefs","seed","bodies","queue","shift","OUTPUT_SUFFIX","inlineAnonymousBodies","anonIds","bodyByRef","inlineRefs","structuredClone","mergeSchemas","collisions","ensureComponentsSchemas","renames","divergentOutputIds","exposedIds","applyTruthTable","applyCollisionDecoration","inputExposed","outputExposed","inputBody","outputBody","writeOrThrowAmbiguous","canonicalEqual","isMarkerPlaceholder","a","b","decorateIfPresent","replace","applyRefTitles","titleById","title","addRefTitles","rewriteResponseSubtree","stripMarkers","stripMarkerFromSchema","dropJsonSchemaMetadata","stripMarkerParameters","$id","props","withForcedExposure","forced","OPENAPI_VERSION","applyZodNest","exposed","extended","refTitles","openapi"],"mappings":";;;;;;;;;;;;;AACO,IAAMA,yBAAAA,GAA4B;AAGlC,IAAMC,WAAAA,GAAc,UAAA;AAGpB,IAAMC,wBAAAA,GAA2B;AAGjC,IAAMC,2BAAAA,GAA8B;AAQpC,IAAMC,sBAAAA,GAAyB;ACdtC,IAAMC,mBAAAA,uBAA0BC,GAAAA,CAAI;AAClC,EAAA,UAAA;AACA,EAAA,UAAA;AACA,EAAA,SAAA;AACA,EAAA,UAAA;AACA,EAAA,OAAA;AACA,EAAA,aAAA;AACA,EAAA,SAAA;AACA,EAAA,UAAA;AACA,EAAA;AACD,CAAA,CAAA;AAED,IAAMC,MAAAA,2BAAUC,MAAAA,KAAAA;AACd,EAAA,MAAMC,IAAAA,GAAOC,CAAAA,CAAEC,cAAAA,CAAeC,GAAAA,CAAIJ,MAAAA,CAAAA;AAClC,EAAA,IAAIC,SAASI,MAAAA,EAAW;AACtB,IAAA,OAAOA,MAAAA;AACT,EAAA;AACA,EAAA,MAAMC,KAAML,IAAAA,CAA0BK,EAAAA;AACtC,EAAA,OAAO,OAAOA,EAAAA,KAAO,QAAA,GAAWA,EAAAA,GAAKD,MAAAA;AACvC,CAAA,EAPe,QAAA,CAAA;AASf,IAAME,eAAAA,2B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I 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 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\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 [def.getter() as unknown as z.ZodType];\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","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\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 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 // `discoverDependents` walks the Zod tree once and yields every named\n // descendant transitively (cycle-safe via its own visited set).\n for (const [child, childId] of discoverDependents(schema)) {\n recordOnce(child, childId);\n }\n },\n hasCollision: (id) => {\n const set = seen.get(id);\n return set !== undefined && set.size > 1;\n },\n getCollisions: () => {\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: () => [...seen.keys()],\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\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 * 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, { op: 'extend', parent });\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 if (parentPropSet.has(key)) {\n continue;\n }\n deltaProps[key] = value;\n }\n const deltaRequired = childRequired.filter((key) => !parentReqSet.has(key));\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","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","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';\n\nexport interface PostProcessResult {\n schema: SchemaObject;\n refs: Map<string, SchemaObject>;\n}\n\nconst rewriteRefs = (node: unknown, selfRef: string | undefined): void => {\n if (Array.isArray(node)) {\n for (const item of node) {\n rewriteRefs(item, selfRef);\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 === '#' && selfRef !== undefined) {\n // Zod emits '#' for cycle refs back to the document root. When we lift a\n // named schema into its own components.schemas entry, '#' should resolve\n // to that entry's own URI.\n obj.$ref = selfRef;\n }\n for (const value of Object.values(obj)) {\n rewriteRefs(value, selfRef);\n }\n};\n\nexport const postProcess = (raw: SchemaObject): 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 root: SchemaObject = { ...raw };\n delete root.$schema;\n delete root.$defs;\n\n // Root has no own self-uri at the 2a level. If the root is a bare `$ref` to a\n // lifted named schema (the common case when input itself has `.meta({ id })`),\n // we'll have already rewritten it to '#/components/schemas/<id>'.\n rewriteRefs(root, undefined);\n\n for (const [id, body] of refs) {\n rewriteRefs(body, `${COMPONENTS_SCHEMAS_PREFIX}${id}`);\n }\n\n return { schema: root, 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\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).length === 0;\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\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\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 { Io } from './dto.types.js';\n\n/**\n * Payload of the `x-zod-nest-dto` placeholder property that\n * `_OPENAPI_METADATA_FACTORY` returns. `applyZodNest` reads this off\n * each `components.schemas.<DtoName>.properties[x-zod-nest-dto]` entry,\n * uses `dtoId` to look up the schema in the registry, and replaces the\n * synthetic schema body with the real Zod-derived schema.\n *\n * `type` and `required` are benign filler that satisfy @nestjs/swagger's\n * property-type guard (without them, the explorer throws \"A circular\n * dependency has been detected\"). They have no semantic meaning and are\n * stripped along with the rest of the marker by `applyZodNest`.\n */\nexport interface ZodDtoMarker {\n readonly type: () => typeof Object;\n readonly required: false;\n readonly __zodNestDto: true;\n readonly dtoId: string;\n readonly io: Io;\n}\n\nexport const makeZodDtoMarker = (dtoId: string, io: Io): ZodDtoMarker => ({\n type: () => Object,\n required: false,\n __zodNestDto: true,\n dtoId,\n io,\n});\n\nexport const isZodDtoMarker = (value: unknown): value is ZodDtoMarker => {\n if (value === null || typeof value !== 'object') {\n return false;\n }\n return (value as { __zodNestDto?: unknown }).__zodNestDto === true;\n};\n","/** Runtime tag placed on every class returned by `createZodDto`. */\nexport const ZOD_DTO_SYMBOL: unique symbol = Symbol.for('zod-nest.dto');\n","import type { z } from 'zod';\nimport type { Io, ZodDto } from './dto.types.js';\n\nimport { ZOD_NEST_DTO_EXTENSION } from '../schema/constants.js';\nimport { makeZodDtoMarker } from './marker.js';\nimport { ZOD_DTO_SYMBOL } from './symbols.js';\n\n/**\n * Cache of `parent -> output-sibling` so repeated reads of `Dto.Output` return\n * the same class instance. WeakMap so the sibling can be GC'd if the parent is.\n */\nconst outputCache = new WeakMap<ZodDto<z.ZodType>, ZodDto<z.ZodType>>();\n\n/**\n * `.Output` is always a distinct sibling class — it carries `io: 'output'` so\n * `applyZodNest` can run the output-side emission and apply the\n * suffix truth table (`Foo` alone vs `Foo` + `FooOutput`) based on actual JSON\n * Schema equality at doc-build time. The earlier \"return self when io-identical\"\n * optimization was dropped because `z.object()` already diverges at the JSON\n * Schema level (input is permissive, output sets `additionalProperties: false`),\n * which would have made the sibling reused only for non-object roots — not\n * worth the implementation complexity.\n */\nconst buildSiblingClass = <TSchema extends z.ZodType>(\n parent: ZodDto<TSchema>,\n schema: TSchema,\n): ZodDto<TSchema> => {\n const SiblingClass = class {\n static readonly schema = schema;\n static readonly io: Io = 'output';\n static readonly [ZOD_DTO_SYMBOL] = true as const;\n\n static get id(): string {\n return parent.id;\n }\n\n static get Output(): ZodDto<TSchema> {\n return this as unknown as ZodDto<TSchema>;\n }\n\n static parse(input: unknown): z.infer<TSchema> {\n return schema.parse(input) as z.infer<TSchema>;\n }\n\n static safeParse(input: unknown): z.ZodSafeParseResult<z.infer<TSchema>> {\n return schema.safeParse(input) as z.ZodSafeParseResult<z.infer<TSchema>>;\n }\n\n static _OPENAPI_METADATA_FACTORY(): Record<string, unknown> {\n return { [ZOD_NEST_DTO_EXTENSION]: makeZodDtoMarker(parent.id, 'output') };\n }\n };\n // `@nestjs/swagger` keys `components.schemas` by the class's `.name`. Every\n // sibling produced here is the same anonymous `class` expression, so they all\n // report `\"SiblingClass\"` and would collapse into one component when more than\n // one `.Output` DTO is used across responses. Pin the name to the parent id so\n // distinct DTOs register distinctly. A getter keeps id resolution lazy (the\n // parent id may not be resolvable until the schema is first registered).\n Object.defineProperty(SiblingClass, 'name', { get: () => parent.id, configurable: true });\n return SiblingClass as unknown as ZodDto<TSchema>;\n};\n\nexport const resolveOutput = <TSchema extends z.ZodType>(\n parent: ZodDto<TSchema>,\n schema: TSchema,\n): ZodDto<TSchema> => {\n const cached = outputCache.get(parent as ZodDto<z.ZodType>);\n if (cached !== undefined) {\n return cached as ZodDto<TSchema>;\n }\n const sibling = buildSiblingClass(parent, schema);\n outputCache.set(parent as ZodDto<z.ZodType>, sibling as ZodDto<z.ZodType>);\n return sibling;\n};\n","import type { z } from 'zod';\nimport type { ZodNestRegistry } from '../schema/registry.js';\nimport type { CreateZodDtoOptions, Io, ZodDto } from './dto.types.js';\n\nimport { ZOD_NEST_DTO_EXTENSION } from '../schema/constants.js';\nimport { defaultRegistry, registerSchema } from '../schema/registry.js';\nimport { makeZodDtoMarker } from './marker.js';\nimport { resolveOutput } from './output-dto.js';\nimport { ZOD_DTO_SYMBOL } from './symbols.js';\n\nlet anonCounter = 0;\nlet warnedOnAnonymous = false;\n\nconst resolveFallbackId = (className: string): string => {\n if (className !== '' && className.length > 1) {\n return className;\n }\n anonCounter += 1;\n const fallback = `_AnonZodDto_${anonCounter}`;\n if (!warnedOnAnonymous) {\n warnedOnAnonymous = true;\n // eslint-disable-next-line no-console\n console.warn(\n `[zod-nest] Could not resolve a DTO id from class name (got \"${className}\"). ` +\n `Using \"${fallback}\". Set an explicit id via \\`schema.meta({ id: 'Foo' })\\` ` +\n `(preferred) or \\`createZodDto(schema, { id: 'Foo' })\\` — important under ` +\n `minification, where class names become single mangled characters.`,\n );\n }\n return fallback;\n};\n\nexport const createZodDto = <TSchema extends z.ZodType>(\n schema: TSchema,\n options?: CreateZodDtoOptions,\n): ZodDto<TSchema> => {\n const registry: ZodNestRegistry = options?.registry ?? defaultRegistry;\n const io: Io = 'input';\n let cachedId: string | undefined;\n\n const ensureRegistered = (className: string): string => {\n if (cachedId !== undefined) {\n return cachedId;\n }\n // `registerSchema` resolves explicit id → `.meta({ id })`. When both miss,\n // fall back to the DTO-specific className → anonymous-counter chain\n // (with one-time minification warning).\n const named = registerSchema(schema, registry, { id: options?.id, expose: options?.expose });\n if (named !== undefined) {\n cachedId = named;\n return cachedId;\n }\n cachedId = resolveFallbackId(className);\n registry.register(schema, cachedId, { expose: options?.expose });\n return cachedId;\n };\n\n const ZodDtoBase = class {\n static readonly schema = schema;\n static readonly io: Io = io;\n static readonly [ZOD_DTO_SYMBOL] = true as const;\n\n static get id(): string {\n return ensureRegistered(this.name);\n }\n\n static get Output(): ZodDto<TSchema> {\n return resolveOutput(this as unknown as ZodDto<TSchema>, schema);\n }\n\n static parse(input: unknown): z.infer<TSchema> {\n return schema.parse(input) as z.infer<TSchema>;\n }\n\n static safeParse(input: unknown): z.ZodSafeParseResult<z.infer<TSchema>> {\n return schema.safeParse(input) as z.ZodSafeParseResult<z.infer<TSchema>>;\n }\n\n static _OPENAPI_METADATA_FACTORY(): Record<string, unknown> {\n return { [ZOD_NEST_DTO_EXTENSION]: makeZodDtoMarker(ensureRegistered(this.name), io) };\n }\n };\n\n return ZodDtoBase as unknown as ZodDto<TSchema>;\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 { HttpStatus, InternalServerErrorException } from '@nestjs/common';\n\nimport type { ExecutionContext } from '@nestjs/common';\nimport type { z } from 'zod';\n\n/**\n * Default exception thrown by `ZodSerializerInterceptor` in strict mode\n * (i.e. when `@ZodResponse({ passthroughOnError: true })` is NOT set) on\n * response-validation failure.\n *\n * Body shape (returned by `getResponse()`):\n * ```\n * {\n * statusCode: 500,\n * message: 'Response validation failed',\n * }\n * ```\n *\n * The zod error tree is **deliberately not exposed in the response body** —\n * a serialization failure is a server-side contract violation, and leaking\n * the schema-shape error tree to clients discloses internal structure. The\n * full treeified error is logged through `ZodNestModule`'s validation-log\n * channel (with redaction + truncation) so operators get the diagnostic\n * information without it reaching the wire.\n *\n * Custom exception filters can still introspect the failure: `zodError` and\n * `executionContext` are kept as own properties on the instance.\n */\nexport class ZodSerializationException extends InternalServerErrorException {\n readonly zodError: z.ZodError;\n readonly executionContext?: ExecutionContext;\n\n constructor(zodError: z.ZodError, executionContext?: ExecutionContext) {\n super(\n {\n statusCode: HttpStatus.INTERNAL_SERVER_ERROR,\n message: 'Response validation failed',\n },\n { cause: zodError },\n );\n this.zodError = zodError;\n this.executionContext = executionContext;\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 { z } from 'zod';\n\nimport type { LoggerService } from '@nestjs/common';\n\nexport const DEFAULT_LOGGER_CONTEXT = 'ZodValidation';\nconst REDACTED = '[REDACTED]';\nconst PREVIEW_RESERVE_BYTES = 100;\n\nexport interface ValidationLogContext {\n /** Which side of the request emitted the failure. */\n side: 'input' | 'output';\n /** Severity to log at; the formatter does not decide this. */\n severity: 'warn' | 'error';\n /** Pre-formatted DTO label, e.g. `'UserDto'`, `'[UserDto]'`, `'[A, B]'`. */\n dto: string;\n /** Output side only — HTTP response status code. */\n status?: number;\n /** Output side only — `Controller.method` best-effort. */\n handler?: string;\n /** Input side only — `body` / `query` / `param` / `custom`. */\n argType?: string;\n}\n\nexport interface ValidationLoggerOptions {\n logger: LoggerService;\n redactKeys: readonly string[];\n maxLoggedValueBytes: number;\n}\n\nexport type LogValidationFailure = (\n err: z.ZodError,\n value: unknown,\n ctx: ValidationLogContext,\n) => void;\n\nexport const noopLogValidationFailure: LogValidationFailure = () => {};\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n\nconst CIRCULAR = '[CIRCULAR]';\n\nconst redactValue = (\n value: unknown,\n redactSet: ReadonlySet<string>,\n seen: WeakSet<object> = new WeakSet(),\n): unknown => {\n if (Array.isArray(value)) {\n if (seen.has(value)) {\n return CIRCULAR;\n }\n seen.add(value);\n return value.map((item) => redactValue(item, redactSet, seen));\n }\n if (!isPlainRecord(value)) {\n return value;\n }\n if (seen.has(value)) {\n return CIRCULAR;\n }\n seen.add(value);\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n if (redactSet.has(key.toLowerCase())) {\n out[key] = REDACTED;\n continue;\n }\n out[key] = redactValue(value[key], redactSet, seen);\n }\n return out;\n};\n\nconst capLoggedValue = (value: unknown, maxBytes: number): unknown => {\n let serialized: string | undefined;\n try {\n serialized = JSON.stringify(value);\n } catch {\n return { _truncated: true, _originalBytes: -1, _reason: 'unserializable' };\n }\n if (serialized === undefined) {\n return value;\n }\n const byteSize = Buffer.byteLength(serialized, 'utf8');\n if (byteSize <= maxBytes) {\n return value;\n }\n const previewBudget = Math.max(0, maxBytes - PREVIEW_RESERVE_BYTES);\n return {\n _truncated: true,\n _originalBytes: byteSize,\n _preview: serialized.slice(0, previewBudget),\n };\n};\n\nconst loggerContextFor = (side: 'input' | 'output'): string =>\n side === 'output' ? 'ZodSerializerInterceptor' : 'ZodValidationPipe';\n\nconst messageFor = (side: 'input' | 'output'): string =>\n side === 'output' ? 'Response validation failed' : 'Request validation failed';\n\nexport const createValidationLogger = (opts: ValidationLoggerOptions): LogValidationFailure => {\n const redactSet = new Set(opts.redactKeys.map((key) => key.toLowerCase()));\n const { logger } = opts;\n\n return (err, value, ctx) => {\n const redacted = redactValue(value, redactSet);\n const sized = capLoggedValue(redacted, opts.maxLoggedValueBytes);\n const payload: Record<string, unknown> = {\n message: messageFor(ctx.side),\n side: ctx.side,\n dto: ctx.dto,\n errors: z.treeifyError(err),\n value: sized,\n };\n if (ctx.status !== undefined) {\n payload.status = ctx.status;\n }\n if (ctx.handler !== undefined) {\n payload.handler = ctx.handler;\n }\n if (ctx.argType !== undefined) {\n payload.argType = ctx.argType;\n }\n const loggerContext = loggerContextFor(ctx.side);\n if (ctx.severity === 'error') {\n logger.error(payload, undefined, loggerContext);\n return;\n }\n logger.warn(payload, loggerContext);\n };\n};\n","import { HEADERS_METADATA } from '@nestjs/common/constants.js';\n\nimport type { ResponseVariant } from './metadata.js';\n\n/**\n * Media type assumed when `@ZodResponse` declares no `contentType`. Responses\n * at this type carry the standard JSON-validated body and flow through the\n * unchanged `type` / `isArray` swagger path in `applySwaggerResponseDecorator`.\n */\nexport const DEFAULT_CONTENT_TYPE = 'application/json';\n\n/**\n * Content types whose bodies zod-nest treats as streams by default: the\n * handler writes them straight to the response buffer (SSE, NDJSON, raw\n * binary, files), so `ZodSerializerInterceptor` skips validation and the\n * OpenAPI media-type key becomes the stream type rather than `application/json`.\n *\n * A trailing `/*` marks a family prefix — `image/*` matches `image/png`,\n * `image/jpeg`, … — everything else matches exactly. Consumers extend this set\n * *additively* via `ZodNestModuleOptions.streamContentTypes`; the defaults are\n * always retained so SSE / NDJSON detection can't be accidentally dropped.\n */\nexport const DEFAULT_STREAM_CONTENT_TYPES: readonly string[] = [\n 'text/event-stream',\n 'application/x-ndjson',\n 'application/octet-stream',\n 'application/pdf',\n 'image/*',\n 'audio/*',\n 'video/*',\n];\n\n/**\n * Normalised stream-content-type matcher: exact media types in a `Set` for\n * O(1) lookup, family prefixes (`image/`, …) checked with `startsWith`. Built\n * once by `normalizeStreamMatcher` from the default list (decoration time) or\n * the default ∪ module-configured list (runtime).\n */\nexport interface StreamContentTypeMatcher {\n exact: ReadonlySet<string>;\n prefixes: readonly string[];\n}\n\nconst PREFIX_WILDCARD_SUFFIX = '/*';\n\n/**\n * Lowercase a content type and drop any `;`-delimited parameters\n * (`text/event-stream; charset=utf-8` → `text/event-stream`).\n */\nconst normalizeContentType = (contentType: string): string => {\n const semicolonIndex = contentType.indexOf(';');\n const mediaType = semicolonIndex === -1 ? contentType : contentType.slice(0, semicolonIndex);\n return mediaType.trim().toLowerCase();\n};\n\nexport const normalizeStreamMatcher = (\n contentTypes: readonly string[],\n): StreamContentTypeMatcher => {\n const exact = new Set<string>();\n const prefixes: string[] = [];\n for (const entry of contentTypes) {\n const normalized = normalizeContentType(entry);\n if (normalized.endsWith(PREFIX_WILDCARD_SUFFIX)) {\n // 'image/*' → 'image/' so `startsWith('image/')` matches the family.\n prefixes.push(normalized.slice(0, normalized.length - 1));\n continue;\n }\n if (normalized.endsWith('/')) {\n prefixes.push(normalized);\n continue;\n }\n exact.add(normalized);\n }\n return { exact, prefixes };\n};\n\n/** Default matcher used at decoration time, where module options aren't yet available. */\nexport const DEFAULT_STREAM_MATCHER: StreamContentTypeMatcher = normalizeStreamMatcher(\n DEFAULT_STREAM_CONTENT_TYPES,\n);\n\nexport const matchesStream = (contentType: string, matcher: StreamContentTypeMatcher): boolean => {\n const normalized = normalizeContentType(contentType);\n if (matcher.exact.has(normalized)) {\n return true;\n }\n for (const prefix of matcher.prefixes) {\n if (normalized.startsWith(prefix)) {\n return true;\n }\n }\n return false;\n};\n\ninterface HeaderMetadataEntry {\n name: string;\n value: unknown;\n}\n\nconst isHeaderEntry = (value: unknown): value is HeaderMetadataEntry => {\n if (value === null || typeof value !== 'object') {\n return false;\n }\n return 'name' in value && typeof value.name === 'string';\n};\n\n/**\n * Read the `Content-Type` value declared via `@Header('Content-Type', …)` on a\n * handler. NestJS stores `[{ name, value }]` under `HEADERS_METADATA`; thunk\n * values (`@Header('Content-Type', () => …)`) are ignored — only literal\n * strings can be resolved statically.\n */\nconst headerContentType = (handler: object): string | undefined => {\n const headers = Reflect.getMetadata(HEADERS_METADATA, handler);\n if (!Array.isArray(headers)) {\n return undefined;\n }\n for (const entry of headers) {\n if (!isHeaderEntry(entry)) {\n continue;\n }\n if (entry.name.toLowerCase() !== 'content-type') {\n continue;\n }\n if (typeof entry.value !== 'string') {\n continue;\n }\n return entry.value;\n }\n return undefined;\n};\n\n/**\n * Resolve the effective response content type for a variant. Precedence:\n * 1. explicit `contentType` option (returned verbatim);\n * 2. a `@Header('Content-Type', …)` value, but only when it matches a known\n * stream type (so an arbitrary header doesn't silently rewrite the doc);\n * 3. `application/json`.\n */\nexport const resolveContentType = (\n variant: ResponseVariant,\n handler: object,\n matcher: StreamContentTypeMatcher,\n): string => {\n if (variant.contentType !== undefined) {\n return variant.contentType;\n }\n const fromHeader = headerContentType(handler);\n if (fromHeader !== undefined && matchesStream(fromHeader, matcher)) {\n return normalizeContentType(fromHeader);\n }\n return DEFAULT_CONTENT_TYPE;\n};\n\n/**\n * Whether a response variant should be treated as a stream — i.e. written\n * directly to the buffer and *not* validated. Explicit `stream` wins; otherwise\n * the effective content type is matched against the known stream set.\n */\nexport const isStreamResponse = (\n variant: ResponseVariant,\n handler: object,\n matcher: StreamContentTypeMatcher,\n): boolean => {\n if (variant.stream !== undefined) {\n return variant.stream;\n }\n return matchesStream(resolveContentType(variant, handler, matcher), matcher);\n};\n","import { Logger } from '@nestjs/common';\n\nimport type { ArgumentMetadata, ExecutionContext, LoggerService } from '@nestjs/common';\nimport type { z } from 'zod';\nimport type { LogValidationFailure } from '../logging/validation-logger.js';\nimport type { StreamContentTypeMatcher } from '../response/stream.js';\n\nimport {\n createValidationLogger,\n DEFAULT_LOGGER_CONTEXT,\n noopLogValidationFailure,\n} from '../logging/validation-logger.js';\nimport { DEFAULT_STREAM_CONTENT_TYPES, normalizeStreamMatcher } from '../response/stream.js';\n\n/**\n * Module-scope factory for the exception thrown by `ZodValidationPipe` on\n * input validation failure. Mirrors the existing per-pipe option but lives\n * at module scope; per-instance constructor arg wins.\n */\nexport type CreateValidationException = (err: z.ZodError, argMetadata: ArgumentMetadata) => unknown;\n\n/**\n * Module-scope factory for the exception thrown by `ZodSerializerInterceptor`\n * on output validation failure (strict mode only). Soft mode never calls\n * this factory.\n */\nexport type CreateSerializationException = (\n err: z.ZodError,\n executionContext: ExecutionContext,\n) => unknown;\n\n/** Public options accepted by `ZodNestModule.forRoot()`. */\nexport interface ZodNestModuleOptions {\n createValidationException?: CreateValidationException;\n createSerializationException?: CreateSerializationException;\n /**\n * Failure-only validation logging. `true` enables both input and output;\n * the granular form lets each side be toggled independently. Default: off.\n */\n validationLogs?: boolean | { input?: boolean; output?: boolean };\n /** Override Nest's built-in `Logger` (e.g. pino/winston adapter). */\n logger?: LoggerService;\n /**\n * Keys whose values get scrubbed from logged input/response objects.\n * Matched case-insensitively at any depth. Supplying this option\n * REPLACES the default list (no merge).\n */\n redactKeys?: readonly string[];\n /**\n * Maximum size in bytes (UTF-8) for any single logged value. Oversized\n * values become `{ _truncated: true, _originalBytes, _preview }`.\n */\n maxLoggedValueBytes?: number;\n /**\n * Additional response content types treated as streams — written directly\n * to the response buffer and never validated by `ZodSerializerInterceptor`.\n * MERGED with the built-in `DEFAULT_STREAM_CONTENT_TYPES` (SSE, NDJSON,\n * octet-stream, pdf, `image/*`, `audio/*`, `video/*`), so the defaults are\n * always retained. A trailing `/*` entry matches a media-type family.\n */\n streamContentTypes?: readonly string[];\n}\n\n/**\n * Resolved options consumed by pipe + interceptor. `forRoot()` builds this\n * once and stuffs it into a provider for the `ZOD_NEST_OPTIONS` injection\n * token; downstream code never re-checks the raw `validationLogs` flag.\n */\nexport interface NormalizedZodNestOptions {\n createValidationException: CreateValidationException | undefined;\n createSerializationException: CreateSerializationException | undefined;\n /** No-op when `validationLogs.input` resolved to false. */\n logInputFailure: LogValidationFailure;\n /** No-op when `validationLogs.output` resolved to false. */\n logOutputFailure: LogValidationFailure;\n /** Built-in defaults ∪ `streamContentTypes`, used by the interceptor's stream check. */\n streamMatcher: StreamContentTypeMatcher;\n}\n\nexport const DEFAULT_REDACT_KEYS: readonly string[] = [\n // Credentials\n 'password',\n 'secret',\n 'apiKey',\n // Auth headers + tokens\n 'authorization',\n 'bearer',\n 'token',\n 'accessToken',\n 'refreshToken',\n 'jwt',\n // Session cookies\n 'cookie',\n 'set-cookie',\n];\n\nexport const DEFAULT_MAX_LOGGED_VALUE_BYTES = 4096;\n\n/** DI token for `NormalizedZodNestOptions`. */\nexport const ZOD_NEST_OPTIONS = Symbol('zod-nest.options');\n\ninterface ResolvedFlags {\n input: boolean;\n output: boolean;\n}\n\nconst resolveLogFlags = (validationLogs: ZodNestModuleOptions['validationLogs']): ResolvedFlags => {\n if (typeof validationLogs === 'boolean') {\n return { input: validationLogs, output: validationLogs };\n }\n return {\n input: validationLogs?.input ?? false,\n output: validationLogs?.output ?? false,\n };\n};\n\nexport const normalizeZodNestOptions = (opts?: ZodNestModuleOptions): NormalizedZodNestOptions => {\n const flags = resolveLogFlags(opts?.validationLogs);\n const redactKeys = opts?.redactKeys ?? DEFAULT_REDACT_KEYS;\n const maxLoggedValueBytes = opts?.maxLoggedValueBytes ?? DEFAULT_MAX_LOGGED_VALUE_BYTES;\n const logger: LoggerService = opts?.logger ?? new Logger(DEFAULT_LOGGER_CONTEXT);\n const loggerOpts = { logger, redactKeys, maxLoggedValueBytes };\n const streamMatcher = normalizeStreamMatcher([\n ...DEFAULT_STREAM_CONTENT_TYPES,\n ...(opts?.streamContentTypes ?? []),\n ]);\n\n return {\n createValidationException: opts?.createValidationException,\n createSerializationException: opts?.createSerializationException,\n logInputFailure: flags.input ? createValidationLogger(loggerOpts) : noopLogValidationFailure,\n logOutputFailure: flags.output ? createValidationLogger(loggerOpts) : noopLogValidationFailure,\n streamMatcher,\n };\n};\n","import { Inject, Injectable, Optional } from '@nestjs/common';\n\nimport type { ArgumentMetadata, PipeTransform } from '@nestjs/common';\nimport type { z } from 'zod';\nimport type { LogValidationFailure } from '../logging/validation-logger.js';\nimport type { NormalizedZodNestOptions } from '../module/options.js';\nimport type {\n CreateValidationException,\n ZodValidationPipeArg,\n ZodValidationPipeOptions,\n} from './types.js';\n\nimport { isZodDto } from '../dto/predicates.js';\nimport { ZodValidationException } from '../exceptions/validation.exception.js';\nimport { noopLogValidationFailure } from '../logging/validation-logger.js';\nimport { ZOD_NEST_OPTIONS } from '../module/options.js';\n\nconst isZodSchema = (value: unknown): value is z.ZodType =>\n value !== null && typeof value === 'object' && '_zod' in value;\n\nconst isOptionsObject = (value: unknown): value is ZodValidationPipeOptions =>\n value !== null && typeof value === 'object' && !isZodSchema(value);\n\nconst defaultExceptionFactory: CreateValidationException = (zodError, argMetadata) =>\n new ZodValidationException(zodError, argMetadata);\n\ninterface ParsedArg {\n schema: z.ZodType | undefined;\n factory: CreateValidationException | undefined;\n dtoName: string | undefined;\n}\n\n@Injectable()\nexport class ZodValidationPipe implements PipeTransform {\n private readonly explicitSchema: z.ZodType | undefined;\n private readonly explicitDtoName: string | undefined;\n private readonly createValidationException: CreateValidationException;\n private readonly logInputFailure: LogValidationFailure;\n\n constructor(\n @Optional() arg?: ZodValidationPipeArg,\n @Optional() @Inject(ZOD_NEST_OPTIONS) moduleOptions?: NormalizedZodNestOptions,\n ) {\n const parsed = ZodValidationPipe.parseArg(arg);\n this.explicitSchema = parsed.schema;\n this.explicitDtoName = parsed.dtoName;\n this.createValidationException =\n parsed.factory ?? moduleOptions?.createValidationException ?? defaultExceptionFactory;\n this.logInputFailure = moduleOptions?.logInputFailure ?? noopLogValidationFailure;\n }\n\n async transform(value: unknown, metadata: ArgumentMetadata): Promise<unknown> {\n const schema = this.resolveSchema(metadata);\n if (schema === undefined) {\n return value;\n }\n const result = await schema.safeParseAsync(value);\n if (result.success) {\n return result.data;\n }\n this.logInputFailure(result.error, value, {\n side: 'input',\n severity: 'warn',\n dto: this.resolveDtoLabel(metadata),\n argType: metadata.type,\n });\n throw this.createValidationException(result.error, metadata);\n }\n\n private resolveSchema(metadata: ArgumentMetadata): z.ZodType | undefined {\n if (this.explicitSchema !== undefined) {\n return this.explicitSchema;\n }\n const metatype: unknown = metadata.metatype;\n if (!isZodDto(metatype)) {\n return undefined;\n }\n return metatype.schema;\n }\n\n private resolveDtoLabel(metadata: ArgumentMetadata): string {\n if (this.explicitDtoName !== undefined) {\n return this.explicitDtoName;\n }\n const metatype: unknown = metadata.metatype;\n if (isZodDto(metatype)) {\n return metatype.name;\n }\n return 'schema';\n }\n\n private static parseArg(arg: ZodValidationPipeArg | undefined): ParsedArg {\n if (arg === undefined) {\n return { schema: undefined, factory: undefined, dtoName: undefined };\n }\n if (isZodDto(arg)) {\n return { schema: arg.schema, factory: undefined, dtoName: arg.name };\n }\n if (isZodSchema(arg)) {\n return { schema: arg, factory: undefined, dtoName: undefined };\n }\n if (!isOptionsObject(arg)) {\n return { schema: undefined, factory: undefined, dtoName: undefined };\n }\n const optionSchema = arg.schema;\n const dtoName = isZodDto(optionSchema) ? optionSchema.name : undefined;\n const resolvedSchema = isZodDto(optionSchema) ? optionSchema.schema : optionSchema;\n return {\n schema: resolvedSchema,\n factory: arg.createValidationException,\n dtoName,\n };\n }\n}\n","import { RequestMethod } from '@nestjs/common';\nimport { HTTP_CODE_METADATA, METHOD_METADATA } from '@nestjs/common/constants.js';\n\nimport type { ResponseStatusWildcard, ResponseVariant } from './metadata.js';\n\nconst POST_DEFAULT_STATUS = 201;\nconst GENERIC_DEFAULT_STATUS = 200;\n\n/**\n * Compute the default HTTP status code for a handler when `@ZodResponse(...)`\n * is invoked without an explicit `status`. Lookup order (highest → lowest):\n *\n * 1. `@HttpCode(n)` on the handler — explicit per-handler status override.\n * NestJS sets `HTTP_CODE_METADATA` to the numeric status when present.\n * 2. HTTP method default — `POST` → `201`, everything else → `200`.\n *\n * The method default itself falls back to `200` when `METHOD_METADATA` is\n * absent — pinned by tests so a future NestJS rename surfaces as a test\n * failure rather than a silent regression.\n */\nexport const defaultStatusFor = (handler: object): number => {\n const httpCode = Reflect.getMetadata(HTTP_CODE_METADATA, handler) as number | undefined;\n if (typeof httpCode === 'number') {\n return httpCode;\n }\n const method = Reflect.getMetadata(METHOD_METADATA, handler) as RequestMethod | undefined;\n if (method === RequestMethod.POST) {\n return POST_DEFAULT_STATUS;\n }\n return GENERIC_DEFAULT_STATUS;\n};\n\n/**\n * Resolve the effective status for a variant. Precedence chain:\n *\n * 1. Explicit numeric `@ZodResponse({ status })` — returned verbatim.\n * 2. Wildcard `@ZodResponse({ status: 'NXX' })` — returned verbatim; the\n * interceptor matcher handles range comparison against `response.statusCode`.\n * 3. Omitted status (or `'default'` collapsed at decoration time) —\n * `@HttpCode(n)` then HTTP-method default via `defaultStatusFor()`.\n *\n * Resolution is deferred to request time because `@ZodResponse` runs before\n * NestJS' route + `@HttpCode` decorators — none of their metadata is set\n * when the decorator evaluates.\n */\nexport const resolveEffectiveStatus = (\n variant: ResponseVariant,\n handler: object,\n): number | ResponseStatusWildcard => {\n if (variant.status !== undefined) {\n return variant.status;\n }\n return defaultStatusFor(handler);\n};\n","import type { z } from 'zod';\nimport type { ZodDto } from '../dto/dto.types.js';\n\n/**\n * Public metadata key for the array of `ResponseVariant` records attached\n * to handler methods by `@ZodResponse(...)`. Symbol.for() so external\n * consumers (e.g. custom interceptors or doc builders) can read the same\n * registry across realms.\n */\nexport const ZOD_RESPONSES_METADATA_KEY = Symbol.for('zod-nest.responses');\n\nexport type ResponseVariantKind = 'single' | 'array' | 'tuple';\n\n/**\n * OpenAPI 3.1 range keys accepted by `@ZodResponse({ status })`. Matched\n * by `ZodSerializerInterceptor` after exact numeric matches fail —\n * `'2XX'` covers 200–299, `'4XX'` covers 400–499, and so on.\n */\nexport type ResponseStatusWildcard = '1XX' | '2XX' | '3XX' | '4XX' | '5XX';\n\n/**\n * Description payload accepted by `@ZodResponse(...)` and passed through to\n * `applyZodNest`'s `@ApiResponse(...)` emitter. String form is shorthand for\n * `{ description }`; the object form lets users declare OpenAPI response\n * `headers` / `links` alongside the description.\n */\nexport type ZodResponseDescription =\n | string\n | {\n description: string;\n headers?: Record<string, unknown>;\n links?: Record<string, unknown>;\n };\n\n/**\n * One variant record per `@ZodResponse(...)` call. `dto` is kept alongside\n * `validationSchema` so `applyZodNest` can emit `@ApiResponse({ type })`\n * without unwrapping the runtime-only `z.array(...)` / `z.tuple([...])` wrapper.\n *\n * `status` is `undefined` when the user didn't pass one explicitly OR when\n * the user wrote `'default'` (the decorator collapses both to `undefined` —\n * they mean the same thing: \"resolve to the method's default status at\n * request time\"). The effective status is resolved lazily by\n * `resolveEffectiveStatus(variant, handler)` because `@ZodResponse` runs\n * *before* NestJS' route decorators (`@Get`, `@Post`, ...) under\n * TypeScript's bottom-up application order, so `METHOD_METADATA` is not\n * yet set when the decorator evaluates.\n *\n * A wildcard string (`'2XX'` / `'4XX'` / ...) is kept verbatim — the\n * matcher in `ZodSerializerInterceptor` handles range comparison.\n */\nexport interface ResponseVariant {\n status: number | ResponseStatusWildcard | undefined;\n kind: ResponseVariantKind;\n dto: ZodDto | readonly ZodDto[];\n validationSchema: z.ZodType;\n description?: ZodResponseDescription;\n passthroughOnError: boolean;\n /**\n * Raw `contentType` option from `@ZodResponse`, if set. `undefined` means\n * \"resolve lazily\" — `resolveContentType` falls back to a stream-typed\n * `@Header('Content-Type', …)` or `application/json`. Drives the OpenAPI\n * media-type key.\n */\n contentType?: string;\n /**\n * Raw `stream` option from `@ZodResponse`, if set. `undefined` means\n * \"infer\" — `isStreamResponse` treats the response as a stream when the\n * effective content type is a known stream type. Streams skip validation.\n */\n stream?: boolean;\n}\n\nexport const getResponseVariants = (handler: object): readonly ResponseVariant[] | undefined => {\n const meta = Reflect.getMetadata(ZOD_RESPONSES_METADATA_KEY, handler) as\n | ResponseVariant[]\n | undefined;\n return meta;\n};\n\n/**\n * Append a variant to the handler's metadata array. Implemented as a\n * prepend so the runtime ordering matches author order in the source —\n * TS decorators apply bottom-up, so the last-applied decorator (top of\n * the source) needs to land at the head of the array.\n */\nexport const appendResponseVariant = (handler: object, variant: ResponseVariant): void => {\n const existing =\n (Reflect.getMetadata(ZOD_RESPONSES_METADATA_KEY, handler) as ResponseVariant[] | undefined) ??\n [];\n Reflect.defineMetadata(ZOD_RESPONSES_METADATA_KEY, [variant, ...existing], handler);\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 type { z } from 'zod';\nimport type { ZodDto } from '../dto/dto.types.js';\n\nimport { createZodDto } from '../dto/create-zod-dto.js';\nimport { isZodDto, isZodSchema } from '../dto/predicates.js';\nimport { ANON_RESPONSE_PREFIX, resolveAnonId } from '../schema/anon-id.js';\nimport { defaultRegistry, registerSchema } from '../schema/registry.js';\n\n/**\n * Cache of `raw schema -> output DTO` so the same schema instance reused across\n * routes maps to one DTO (and therefore one OpenAPI component id). Without it,\n * an un-`.meta({ id })`'d schema would mint a fresh anonymous id per route.\n * WeakMap so the synthesised DTO is GC'd once the schema is. Mirrors the\n * `outputCache` pattern in `src/dto/output-dto.ts`.\n */\nconst responseDtoCache = new WeakMap<z.ZodType, ZodDto>();\n\nconst schemaToOutputDto = (schema: z.ZodType): ZodDto => {\n const cached = responseDtoCache.get(schema);\n if (cached !== undefined) {\n return cached;\n }\n // `createZodDto(schema)` as a plain expression is always type-safe — TS2509\n // (\"base constructor return type is not an object type\") only fires when the\n // result is used in an `extends` clause, never here. This is what lets a\n // raw union / intersection schema flow through unchanged.\n //\n // `createZodDto`'s anonymous-id fallback keys off the class name, which here\n // is the shared base \"ZodDtoBase\" — so an unnamed schema would not get a\n // unique id. Resolve the id ourselves: `.meta({ id })` when present, else a\n // generated synthetic id registered as `anonymous`.\n const namedId = registerSchema(schema);\n if (namedId !== undefined) {\n const dto = createZodDto(schema).Output;\n responseDtoCache.set(schema, dto);\n return dto;\n }\n // No resolvable id: register a synthetic anonymous id so the body is emitted\n // (under the document's `strict` / `override`) and referenced by `$ref`.\n // `applyZodNest`'s `inlineAnonymousBodies` pass inlines that body into the\n // response and prunes the synthetic component, so it never reaches the doc.\n const anonId = resolveAnonId(schema, ANON_RESPONSE_PREFIX);\n registerSchema(schema, defaultRegistry, { id: anonId, anonymous: true });\n const dto = createZodDto(schema, { id: anonId }).Output;\n responseDtoCache.set(schema, dto);\n return dto;\n};\n\n/**\n * Normalise one `@ZodResponse({ type })` entry into a `ZodDto`:\n * - a `ZodDto` is returned as-is (the caller already chose `.Output` or not);\n * - a raw Zod schema is wrapped as `createZodDto(schema).Output` — output IO,\n * because a response body is output-only — and cached per schema instance;\n * - anything else throws `TypeError` at decoration time so typos surface at\n * module load, not on the first request.\n *\n * `index` is supplied when the entry came from an array/tuple `type`, so the\n * thrown message can point at the offending slot.\n */\nexport const toResponseDto = (entry: unknown, index?: number): ZodDto => {\n if (isZodDto(entry)) {\n return entry;\n }\n if (isZodSchema(entry)) {\n return schemaToOutputDto(entry);\n }\n const where =\n index === undefined ? '@ZodResponse({ type })' : `@ZodResponse({ type }) element [${index}]`;\n throw new TypeError(\n `[zod-nest] ${where} must be a zod-nest DTO class (from createZodDto), ` +\n 'a Zod schema, or a non-empty array of those.',\n );\n};\n","import { ApiExtraModels, ApiResponse, getSchemaPath } from '@nestjs/swagger';\n\nimport type { Type } from '@nestjs/common';\nimport type { ApiResponseOptions } from '@nestjs/swagger';\nimport type { ZodDto } from '../dto/dto.types.js';\nimport type {\n ResponseStatusWildcard,\n ResponseVariant,\n ZodResponseDescription,\n} from '../response/metadata.js';\n\nimport { DEFAULT_CONTENT_TYPE } from '../response/stream.js';\n\n/**\n * Minimal shape for an OpenAPI 3.1 tuple schema. `@nestjs/swagger`'s\n * `SchemaObject` is modelled against OpenAPI 3.0 and doesn't declare\n * `prefixItems`. Building the literal here lets us avoid an `as` cast on\n * each `prefixItems` entry; the final assignment into `ApiResponseOptions.schema`\n * carries a single documented cast because that field's type is the 3.0\n * `SchemaObject`.\n */\ninterface TupleSchema {\n type: 'array';\n prefixItems: { $ref: string }[];\n items: false;\n}\n\ninterface DescriptionFields {\n description?: string;\n headers?: Record<string, unknown>;\n links?: Record<string, unknown>;\n}\n\nconst extractDescriptionFields = (desc: ZodResponseDescription | undefined): DescriptionFields => {\n if (desc === undefined) {\n return {};\n }\n if (typeof desc === 'string') {\n return { description: desc };\n }\n const out: DescriptionFields = { description: desc.description };\n if (desc.headers !== undefined) {\n out.headers = desc.headers;\n }\n if (desc.links !== undefined) {\n out.links = desc.links;\n }\n return out;\n};\n\n/**\n * `ZodDto` is the static side of a class produced by `createZodDto` — its\n * `new ()` signature satisfies `Type<unknown>`, but the structural intersection\n * with our static members (`schema`, `Output`, etc.) confuses TS into\n * rejecting a direct assignment to `ApiResponseOptions.type`. Narrow to\n * `Type<unknown>` (`@nestjs/common`'s constructor alias) at the boundary.\n */\nconst asDtoFunction = (dto: ZodDto): Type<unknown> => dto as unknown as Type<unknown>;\n\n/**\n * `@nestjs/swagger`'s `ApiResponseOptions.headers` is typed against the\n * OpenAPI 3.0 `HeadersObject` (`Record<string, HeaderObject | ReferenceObject>`).\n * `ZodResponseDescription.headers` keeps `Record<string, unknown>` so users\n * can pass through 3.1 / extension shapes without fighting the type. Cast\n * at the boundary; runtime contents flow through `@nestjs/swagger` unchanged.\n */\nconst buildApiResponseOptions = (\n base: { status: number | ResponseStatusWildcard } & DescriptionFields,\n body: { type: Type<unknown>; isArray?: true } | { schema: TupleSchema },\n): ApiResponseOptions => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- see header / schema comments above\n return { ...base, ...body } as any;\n};\n\nconst buildTupleSchema = (dtos: readonly ZodDto[]): TupleSchema => ({\n type: 'array',\n prefixItems: dtos.map((d) => ({ $ref: getSchemaPath(asDtoFunction(d)) })),\n items: false,\n});\n\n/**\n * OpenAPI schema for a non-JSON response body, keyed by `ResponseVariant.kind`:\n * single → a bare `$ref`; array → an `array` of `$ref`; tuple → a 3.1\n * `prefixItems` tuple. Each `$ref` targets the class name `@nestjs/swagger`\n * registers via `ApiExtraModels`; `applyZodNest` later rewrites it to the real\n * DTO id and replaces the placeholder body with the Zod-derived schema.\n */\ntype ContentSchema = { $ref: string } | { type: 'array'; items: { $ref: string } } | TupleSchema;\n\n/**\n * Build an `ApiResponseOptions` payload that pins a custom media-type key via\n * `content` (rather than `type` / `isArray`, which `@nestjs/swagger` always\n * wraps in `application/json`). Used for streamed / binary responses.\n */\nconst buildContentResponseOptions = (\n base: { status: number | ResponseStatusWildcard } & DescriptionFields,\n contentType: string,\n schema: ContentSchema,\n): ApiResponseOptions => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- 3.1 schema shapes (prefixItems) + the headers shape don't fit @nestjs/swagger's 3.0 types; see comments above\n return { ...base, content: { [contentType]: { schema } } } as any;\n};\n\n/**\n * Emit `@ApiResponse(...)` for a non-`application/json` content type. Registers\n * the variant's DTO(s) with `ApiExtraModels` so they land in\n * `components.schemas`, then references them by `$ref` under the custom media\n * type — the same placeholder-then-rewrite contract the tuple path relies on.\n */\nconst applyCustomContentResponse = (\n variant: ResponseVariant,\n base: { status: number | ResponseStatusWildcard } & DescriptionFields,\n contentType: string,\n target: object,\n propertyKey: string | symbol,\n descriptor: TypedPropertyDescriptor<unknown>,\n): void => {\n if (variant.kind === 'single') {\n const dto = variant.dto as ZodDto;\n ApiExtraModels(asDtoFunction(dto))(target, propertyKey, descriptor);\n const schema: ContentSchema = { $ref: getSchemaPath(asDtoFunction(dto)) };\n ApiResponse(buildContentResponseOptions(base, contentType, schema))(\n target,\n propertyKey,\n descriptor,\n );\n return;\n }\n\n const dtos = variant.dto as readonly ZodDto[];\n ApiExtraModels(...dtos.map(asDtoFunction))(target, propertyKey, descriptor);\n\n if (variant.kind === 'array') {\n // `buildArrayKind` guarantees `dtos.length === 1` for `array` kind — same\n // invariant the `application/json` array path relies on below.\n const dto = dtos[0]!;\n const schema: ContentSchema = {\n type: 'array',\n items: { $ref: getSchemaPath(asDtoFunction(dto)) },\n };\n ApiResponse(buildContentResponseOptions(base, contentType, schema))(\n target,\n propertyKey,\n descriptor,\n );\n return;\n }\n\n // tuple\n ApiResponse(buildContentResponseOptions(base, contentType, buildTupleSchema(dtos)))(\n target,\n propertyKey,\n descriptor,\n );\n};\n\n/**\n * Build an `ApiResponseOptions` payload for a `ResponseVariant` and apply\n * `@ApiResponse(...)` (plus `@ApiExtraModels(...)` for tuples) to the\n * handler. This is the swagger-side half of the composite `@ZodResponse`\n * decorator — the variant has already been registered for runtime\n * validation; this writes the matching OpenAPI doc entry.\n *\n * Tuple variants emit a raw `schema: { type: 'array', prefixItems: [...] }`\n * with one `$ref` per slot, and call `ApiExtraModels(...)` so `@nestjs/swagger`\n * registers each tuple-slot DTO in `components.schemas`. `applyZodNest` then\n * replaces the placeholder bodies with the real Zod-derived schemas.\n */\nexport const applySwaggerResponseDecorator = (\n variant: ResponseVariant,\n effectiveStatus: number | ResponseStatusWildcard,\n effectiveContentType: string,\n target: object,\n propertyKey: string | symbol,\n descriptor: TypedPropertyDescriptor<unknown>,\n): void => {\n const base = { status: effectiveStatus, ...extractDescriptionFields(variant.description) };\n\n if (effectiveContentType !== DEFAULT_CONTENT_TYPE) {\n applyCustomContentResponse(\n variant,\n base,\n effectiveContentType,\n target,\n propertyKey,\n descriptor,\n );\n return;\n }\n\n if (variant.kind === 'single') {\n const dto = variant.dto as ZodDto;\n ApiResponse(buildApiResponseOptions(base, { type: asDtoFunction(dto) }))(\n target,\n propertyKey,\n descriptor,\n );\n return;\n }\n\n if (variant.kind === 'array') {\n const dtos = variant.dto as readonly ZodDto[];\n // `buildArrayKind` guarantees `dtos.length === 1` for `array` kind.\n const dto = dtos[0]!;\n ApiResponse(buildApiResponseOptions(base, { type: asDtoFunction(dto), isArray: true }))(\n target,\n propertyKey,\n descriptor,\n );\n return;\n }\n\n // tuple\n const dtos = variant.dto as readonly ZodDto[];\n ApiExtraModels(...dtos.map(asDtoFunction))(target, propertyKey, descriptor);\n ApiResponse(buildApiResponseOptions(base, { schema: buildTupleSchema(dtos) }))(\n target,\n propertyKey,\n descriptor,\n );\n};\n","import { z } from 'zod';\n\nimport type { ZodDto } from '../dto/dto.types.js';\nimport type {\n ResponseStatusWildcard,\n ResponseVariant,\n ResponseVariantKind,\n ZodResponseDescription,\n} from '../response/metadata.js';\n\nimport { resolveEffectiveStatus } from '../response/default-status.js';\nimport { appendResponseVariant } from '../response/metadata.js';\nimport { toResponseDto } from '../response/normalize-type.js';\nimport { DEFAULT_STREAM_MATCHER, resolveContentType } from '../response/stream.js';\nimport { applySwaggerResponseDecorator } from './zod-response.swagger-bridge.js';\n\n/**\n * One entry in `@ZodResponse({ type })` — either a zod-nest DTO or a raw Zod\n * schema. A raw schema is normalised internally to `createZodDto(schema).Output`\n * (output IO, since a response body is output-only), so schemas that can't be\n * wrapped with `createZodDto` — `z.discriminatedUnion` / `z.union` /\n * `z.intersection`, whose `z.infer` is a union and so trip TS2509 in an\n * `extends` clause — can be passed straight to a response. See `toResponseDto`.\n */\nexport type ZodResponseEntry = ZodDto | z.ZodType;\n\n/**\n * Accepted shapes for `@ZodResponse({ type })`. Each slot is a `ZodResponseEntry`\n * (DTO or raw schema), and the two may be mixed within an array:\n * - `Dto` / `Schema` → validates as the entry's schema (single response).\n * - `[Entry]` (length 1) → validates as `z.array(entry.schema)`; matches Nest's\n * `@ApiResponse({ isArray: true })` convention without minting a separate\n * `*sDto` id.\n * - `[A, B, ...]` (length ≥ 2) → validates as `z.tuple([A.schema, B.schema, ...])`;\n * surfaces as an OpenAPI 3.1 `prefixItems` tuple via `applyZodNest`.\n *\n * Empty arrays and entries that are neither a DTO nor a schema throw `TypeError`\n * at decoration time so typos surface at module load, not the first request.\n */\nexport type ZodResponseType = ZodResponseEntry | readonly [ZodResponseEntry, ...ZodResponseEntry[]];\n\n/**\n * Accepted shapes for `@ZodResponse({ status })`:\n * - `number` — exact match against `response.statusCode` (most common case).\n * - `'1XX'` / `'2XX'` / `'3XX'` / `'4XX'` / `'5XX'` — OpenAPI 3.1 range key;\n * `'2XX'` matches 200–299, etc. Considered only after no exact numeric\n * variant matches the observed status.\n * - `'default'` — sugar for the handler's method default status. Collapsed\n * to `undefined` when the variant is built, so `resolveEffectiveStatus`\n * walks the same `@HttpCode → method-default` chain as an omitted `status`.\n * This deliberately does NOT implement a catch-all-fallback semantic; it\n * names the canonical-success card explicitly, matching what consumers\n * already write in `@ApiResponse({ status: 'default' })`.\n */\nexport type ResponseStatusInput = number | ResponseStatusWildcard | 'default';\n\nexport interface ZodResponseOptions {\n status?: ResponseStatusInput;\n type: ZodResponseType;\n description?: ZodResponseDescription;\n passthroughOnError?: boolean;\n /**\n * Response content type, used as the OpenAPI media-type key (`@ApiResponse`\n * `content`). Defaults to `'application/json'`. Set a stream type\n * (`'text/event-stream'`, `'application/x-ndjson'`, …) to document a streamed\n * body; combined with `stream` it also turns off response validation.\n */\n contentType?: string;\n /**\n * When `true`, the response is written directly to the buffer and\n * `ZodSerializerInterceptor` skips validation. When unset, it is inferred:\n * a stream-typed `contentType` (or a stream-typed `@Header('Content-Type', …)`)\n * implies `true`. See `DEFAULT_STREAM_CONTENT_TYPES`.\n */\n stream?: boolean;\n}\n\ninterface BuiltKind {\n kind: ResponseVariantKind;\n dto: ZodDto | readonly ZodDto[];\n validationSchema: z.ZodType;\n}\n\ntype NonEmptyEntryArray = readonly [ZodResponseEntry, ...ZodResponseEntry[]];\n\nconst buildArrayKind = (entries: NonEmptyEntryArray): BuiltKind => {\n // Destructure the entry tuple first (so `head` stays non-optional), then\n // normalise each through `toResponseDto` — which rejects non-DTO / non-schema\n // entries with a `TypeError` carrying the offending index.\n const [headEntry, ...restEntries] = entries;\n const head = toResponseDto(headEntry, 0);\n const rest = restEntries.map((entry, index) => toResponseDto(entry, index + 1));\n if (rest.length === 0) {\n return { kind: 'array', dto: [head], validationSchema: z.array(head.schema) };\n }\n const tupleSchemas: [z.ZodType, ...z.ZodType[]] = [head.schema, ...rest.map((d) => d.schema)];\n return { kind: 'tuple', dto: [head, ...rest], validationSchema: z.tuple(tupleSchemas) };\n};\n\nconst buildKind = (type: ZodResponseType): BuiltKind => {\n if (Array.isArray(type)) {\n if (type.length === 0) {\n throw new TypeError(\n '[zod-nest] @ZodResponse({ type: [] }) is invalid — provide at least one DTO or schema.',\n );\n }\n // After the length check, `type` is guaranteed non-empty; the static\n // `readonly [ZodResponseEntry, ...ZodResponseEntry[]]` annotation reflects\n // this so the destructure in `buildArrayKind` doesn't need a runtime guard.\n return buildArrayKind(type as NonEmptyEntryArray);\n }\n const dto = toResponseDto(type);\n return { kind: 'single', dto, validationSchema: dto.schema };\n};\n\n/**\n * Normalise the user-facing `status` input into the variant-internal shape:\n * `'default'` collapses to `undefined` so the matcher treats it the same as\n * an omitted status (resolve to `defaultStatusFor(handler)` at request time).\n * Numbers and `'NXX'` wildcards pass through untouched.\n */\nconst normaliseStatus = (\n status: ResponseStatusInput | undefined,\n): number | ResponseStatusWildcard | undefined => {\n if (status === 'default') {\n return undefined;\n }\n return status;\n};\n\n/**\n * Method-only decorator. Declares a typed response variant for the handler\n * AND applies the equivalent `@ApiResponse(...)` from `@nestjs/swagger` so\n * the OpenAPI document carries the response shape — no need for consumers\n * to hand-write `@ApiResponse` alongside `@ZodResponse`.\n *\n * Stack multiple decorations to declare per-status types; runtime lookup\n * is by `ZodSerializerInterceptor`'s two-pass matcher (exact numeric, then\n * `'NXX'` wildcard). The wrapped Zod schema (array / tuple) is built once\n * at decoration time — no per-request schema construction.\n *\n * **Decorator-ordering note.** TypeScript decorators apply bottom-up, so\n * `@ZodResponse` (typically written above `@Get` / `@HttpCode` /\n * `@Header(...)`) runs *before* those siblings have written their\n * `HTTP_CODE_METADATA` / `METHOD_METADATA` / `HEADERS_METADATA`. The\n * `@ApiResponse(...)` call is therefore always deferred via `queueMicrotask`,\n * so by the time it reads sibling metadata — the effective status *and* the\n * effective content type (including `@Header('Content-Type', …)` inference) —\n * everything has settled. The document is built much later\n * (`SwaggerModule.createDocument`), so the deferral is invisible to output.\n * See `docs/responses.md → \"Decorator ordering & the microtask trick\"`.\n */\nexport const ZodResponse = (opts: ZodResponseOptions): MethodDecorator => {\n const built = buildKind(opts.type);\n const status = normaliseStatus(opts.status);\n return (target, propertyKey, descriptor) => {\n const handler = descriptor.value;\n if (typeof handler !== 'function') {\n throw new TypeError('[zod-nest] @ZodResponse can only be applied to methods.');\n }\n const variant: ResponseVariant = {\n status,\n kind: built.kind,\n dto: built.dto,\n validationSchema: built.validationSchema,\n description: opts.description,\n passthroughOnError: opts.passthroughOnError ?? false,\n contentType: opts.contentType,\n stream: opts.stream,\n };\n appendResponseVariant(handler, variant);\n\n // `TypedPropertyDescriptor<unknown>` matches what the swagger bridge\n // expects; `MethodDecorator`'s descriptor parameter is `TypedPropertyDescriptor<T>`\n // for the inferred return type, structurally compatible at runtime.\n const swaggerDescriptor = descriptor as TypedPropertyDescriptor<unknown>;\n // Always defer: sibling `@HttpCode` / route method / `@Header` metadata is\n // not yet written when this decorator applies. The default stream matcher\n // is used here — module options (`streamContentTypes`) don't exist at\n // decoration time; they extend only the interceptor's runtime check.\n queueMicrotask(() => {\n const effectiveStatus = resolveEffectiveStatus(variant, handler);\n const contentType = resolveContentType(variant, handler, DEFAULT_STREAM_MATCHER);\n applySwaggerResponseDecorator(\n variant,\n effectiveStatus,\n contentType,\n target,\n propertyKey,\n swaggerDescriptor,\n );\n });\n };\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 { ApiBody } from '@nestjs/swagger';\nimport { z } from 'zod';\n\nimport type { ZodNestRegistry } from '../schema/registry.js';\n\nimport { defaultRegistry } from '../schema/registry.js';\nimport { flattenObjectIntersection } from './internal/flatten-intersection.js';\nimport { resolveSchemaRef } from './internal/zod-schema-ref.js';\n\ntype BodySchema = { readonly $ref: string } | Record<string, unknown>;\n\nexport interface ZodBodyOptions {\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 /** 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 * Merge an intersection of `z.object` arms into a single flat object body\n * emitted inline (no `$ref`, no `components.schemas` entry). Use when\n * Swagger UI's `multipart/form-data` `try-it-out` form needs to render the\n * body — the UI doesn't follow `$ref` or unwrap `allOf`. Throws\n * `ZodNestError` if the schema isn't an object or an intersection of\n * objects. No-op for a bare `z.object`. Defaults to `false`.\n */\n readonly flatten?: boolean;\n}\n\n/**\n * Method-level decorator that wires the OpenAPI `requestBody` for a handler\n * whose body schema doesn't fit a `createZodDto` class — typically a\n * `z.intersection` that contains a `z.union`, a `z.discriminatedUnion`, or\n * any schema whose `z.infer<>` is a TypeScript union (which TS refuses as a\n * class base with TS2509).\n *\n * Pair with `@Body(new ZodValidationPipe(schema))` at the parameter to keep\n * the handler arg precisely typed as `z.infer<typeof schema>`:\n *\n * ```ts\n * @Post()\n * @ZodBody(IntersectionWithUnion)\n * async post(\n * @Body(new ZodValidationPipe(IntersectionWithUnion))\n * body: z.infer<typeof IntersectionWithUnion>,\n * ) {}\n * ```\n *\n * The schema is registered in the registry when it has an id (via\n * `.meta({ id })` or `options.id`) so its body is emitted into\n * `components.schemas`. Anonymous schemas are inlined into the operation.\n */\nexport const ZodBody = (schema: z.ZodType, options?: ZodBodyOptions): MethodDecorator => {\n const apiBodySchema = resolveBodySchema(schema, options);\n return ApiBody({\n schema: apiBodySchema,\n ...(options?.description !== undefined ? { description: options.description } : {}),\n required: options?.required ?? true,\n });\n};\n\nconst resolveBodySchema = (schema: z.ZodType, options: ZodBodyOptions | undefined): BodySchema => {\n if (options?.flatten === true) {\n return flattenObjectIntersection(schema, options.registry ?? defaultRegistry, '@ZodBody');\n }\n // `deferAnonInline: true` always resolves to a `$ref` (named → its id,\n // anonymous → a synthetic id inlined later by `applyZodNest`), so the\n // overload narrows the result to a `ref`.\n return resolveSchemaRef(schema, {\n id: options?.id,\n registry: options?.registry,\n deferAnonInline: true,\n }).ref;\n};\n","/**\n * `@nestjs/swagger`'s metadata key for explicit operation parameters — the\n * array `@ApiQuery` / `@ApiParam` / etc. append to. Hardcoded because the\n * `DECORATORS` constant that owns it (`DECORATORS.API_PARAMETERS`) is not\n * re-exported from the package's public barrel. The end-to-end smoke test\n * (`test/decorators/zod-decorators.swagger-smoke.spec.ts`) guards the contract.\n */\nconst API_PARAMETERS_METADATA_KEY = 'swagger/apiParameters';\n\n/**\n * Append a single zod-nest query marker to a handler's swagger parameter\n * metadata — the same `{ __zodNestDto, dtoId, io, in }` placeholder shape that\n * `createZodDto`'s `_OPENAPI_METADATA_FACTORY` produces for `@Query() dto`, so\n * `expandParamMarkers` resolves it through one code path. Deferring (rather\n * than expanding at decoration time) is what lets `@ZodQuery`'s ref decision\n * follow `applyZodNest`'s `queryParamStyle` preference, which isn't known until\n * the document is built.\n *\n * `type` is intentionally omitted: `@nestjs/swagger`'s `SchemaObjectFactory`\n * returns a typeless query parameter untouched, so the marker (and its custom\n * keys) survives `SwaggerModule.createDocument` verbatim for `expandParamMarkers`\n * to read. `name` is set to `dtoId` purely to give the placeholder a stable\n * identity before expansion replaces it.\n *\n * @param dtoId Registered component id of the query DTO schema.\n * @param ref Per-marker override of `queryParamStyle`; omitted from the marker\n * when `undefined` so the global preference applies.\n */\nexport const appendQueryMarker =\n (dtoId: string, ref: boolean | undefined): MethodDecorator =>\n (_target, _propertyKey, descriptor) => {\n const method = descriptor.value;\n if (typeof method !== 'function') {\n return descriptor;\n }\n const marker: Record<string, unknown> = {\n name: dtoId,\n in: 'query',\n __zodNestDto: true,\n dtoId,\n io: 'input',\n };\n if (ref !== undefined) {\n marker.ref = ref;\n }\n const existing: unknown = Reflect.getMetadata(API_PARAMETERS_METADATA_KEY, method);\n const params: unknown[] = Array.isArray(existing) ? existing : [];\n Reflect.defineMetadata(API_PARAMETERS_METADATA_KEY, [...params, marker], method);\n return descriptor;\n };\n","import { applyDecorators } from '@nestjs/common';\nimport { ApiQuery } from '@nestjs/swagger';\nimport { z } from 'zod';\n\nimport type { ZodNestRegistry } from '../schema/registry.js';\n\nimport { ZodNestError } from '../schema/errors.js';\nimport { defaultRegistry, registerSchema } from '../schema/registry.js';\nimport { appendQueryMarker } from './internal/query-marker.js';\nimport { expandObjectSchema, isZodObject, paramSchemaBody } from './internal/zod-param-expand.js';\n\nexport interface ZodQueryOptions {\n /** Forces this id on the root schema, overriding any `.meta({ id })`. */\n readonly id?: string;\n /** Registry to register into. Defaults to `defaultRegistry`. */\n readonly registry?: ZodNestRegistry;\n /**\n * Override how this query DTO is represented in the OpenAPI doc, taking\n * precedence over `applyZodNest`'s `queryParamStyle`:\n *\n * - `true` — one single schema-based query parameter that `$ref`s the DTO's\n * `components.schemas` entry (`style: 'form'`, `explode: true`).\n * - `false` — one parameter per top-level property.\n * - unset — follow the global `queryParamStyle` preference (default `'expand'`).\n *\n * Ref mode needs a named schema to reference: `ref: true` on an anonymous\n * schema (no `.meta({ id })` and no `id` option) throws `ZodNestError`.\n */\n readonly ref?: boolean;\n}\n\n/**\n * Method-level decorator describing a `@Query()` object schema as OpenAPI\n * query parameters.\n *\n * When the schema is named (`.meta({ id })` or the `id` option), the decorator\n * registers it and emits a single deferred marker, leaving the expand-vs-`$ref`\n * decision to `applyZodNest` — so an unset `ref` follows the global\n * `queryParamStyle` preference, `ref: true` collapses to one `$ref` query\n * parameter, and `ref: false` expands per property. This mirrors the\n * `@Query() dto` (`createZodDto`) path, which flows through the same marker.\n *\n * When the schema is anonymous, there is no component to reference, so the\n * decorator expands one `@ApiQuery` per property immediately (and rejects\n * `ref: true`).\n *\n * The user remains responsible for binding the actual query values to the\n * handler, typically via `@Query(new ZodValidationPipe(schema)) q: z.infer<typeof schema>`.\n */\nexport const ZodQuery = (schema: z.ZodType, options?: ZodQueryOptions): MethodDecorator => {\n if (!isZodObject(schema)) {\n throw new ZodNestError(\n `@ZodQuery 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 const id = registerSchema(schema, registry, { id: options?.id });\n if (id !== undefined) {\n return appendQueryMarker(id, options?.ref);\n }\n if (options?.ref === true) {\n throw new ZodNestError(\n `@ZodQuery({ ref: true }) requires a named schema — there is no component to \\`$ref\\`. ` +\n `Name the schema via \\`.meta({ id: 'Foo' })\\` or pass the \\`id\\` option, or drop \\`ref\\` to expand per property.`,\n );\n }\n const expanded = expandObjectSchema(schema, {\n id: options?.id,\n registry,\n decoratorName: '@ZodQuery',\n });\n return applyDecorators(\n ...expanded.map(({ name, required, resolution }) =>\n ApiQuery({ name, schema: paramSchemaBody(resolution), required }),\n ),\n );\n};\n","/**\n * `@nestjs/swagger`'s method-level parameters metadata key. Mirrored verbatim\n * from `@nestjs/swagger/dist/constants.js`'s `DECORATORS.API_PARAMETERS` —\n * inlined as a string literal so we don't reach into the package's deep\n * import paths (it isn't part of the package's public `exports` map).\n */\nexport const API_PARAMETERS_KEY = 'swagger/apiParameters';\n","import { z } from 'zod';\n\nimport { type ZodNestRegistry } from '../schema/registry.js';\nimport { API_PARAMETERS_KEY } from './internal/constants.js';\nimport { expandObjectSchema, paramSchemaBody } from './internal/zod-param-expand.js';\n\nexport interface ZodHeadersOptions {\n /** Forces this id on the root schema, overriding any `.meta({ id })`. */\n readonly id?: string;\n /** Registry to register into. Defaults to `defaultRegistry`. */\n readonly registry?: ZodNestRegistry;\n}\n\ninterface HeaderParameter {\n readonly name: string;\n readonly in: 'header';\n readonly required: boolean;\n readonly schema: { readonly $ref: string } | Record<string, unknown>;\n}\n\n/**\n * Method-level decorator that expands a `z.object` schema into one\n * header-parameter entry per property. Required-ness derives from each\n * property's Zod optionality.\n *\n * Writes directly to the `swagger/apiParameters` metadata key the explorer\n * reads. We bypass `@ApiHeader` because it injects a default `type: 'string'`\n * onto the schema (`api-header.decorator.js`), which pollutes our `$ref`\n * objects and inline JSON Schemas. The raw-metadata path keeps our schema\n * bodies intact.\n */\nexport const ZodHeaders = (schema: z.ZodType, options?: ZodHeadersOptions): MethodDecorator => {\n const expanded = expandObjectSchema(schema, {\n id: options?.id,\n registry: options?.registry,\n decoratorName: '@ZodHeaders',\n });\n const newEntries: HeaderParameter[] = expanded.map(({ name, required, resolution }) => ({\n name,\n in: 'header',\n required,\n schema: paramSchemaBody(resolution),\n }));\n return (_target, _propertyKey, descriptor) => {\n const handler = descriptor.value;\n if (typeof handler !== 'function') {\n throw new TypeError('[zod-nest] @ZodHeaders can only be applied to methods.');\n }\n const existing: unknown[] = Reflect.getMetadata(API_PARAMETERS_KEY, handler) ?? [];\n Reflect.defineMetadata(API_PARAMETERS_KEY, [...existing, ...newEntries], handler);\n };\n};\n","import { z } from 'zod';\n\nimport { type ZodNestRegistry } from '../schema/registry.js';\nimport { API_PARAMETERS_KEY } from './internal/constants.js';\nimport { expandObjectSchema, paramSchemaBody } from './internal/zod-param-expand.js';\n\nexport interface ZodCookiesOptions {\n /** Forces this id on the root schema, overriding any `.meta({ id })`. */\n readonly id?: string;\n /** Registry to register into. Defaults to `defaultRegistry`. */\n readonly registry?: ZodNestRegistry;\n}\n\ninterface CookieParameter {\n readonly name: string;\n readonly in: 'cookie';\n readonly required: boolean;\n readonly schema: { readonly $ref: string } | Record<string, unknown>;\n}\n\n/**\n * Method-level decorator that expands a `z.object` schema into one\n * cookie-parameter entry per property in the OpenAPI operation. There is no\n * `@ApiCookie` decorator in `@nestjs/swagger`, so we write directly to the\n * `swagger/apiParameters` metadata key the explorer reads — the same key\n * `@ApiQuery` / `@ApiParam` / `@ApiHeader` populate via their helper.\n */\nexport const ZodCookies = (schema: z.ZodType, options?: ZodCookiesOptions): MethodDecorator => {\n const expanded = expandObjectSchema(schema, {\n id: options?.id,\n registry: options?.registry,\n decoratorName: '@ZodCookies',\n });\n const newEntries: CookieParameter[] = expanded.map(({ name, required, resolution }) => ({\n name,\n in: 'cookie',\n required,\n schema: paramSchemaBody(resolution),\n }));\n return (_target, _propertyKey, descriptor) => {\n const handler = descriptor.value;\n if (typeof handler !== 'function') {\n throw new TypeError('[zod-nest] @ZodCookies can only be applied to methods.');\n }\n const existing: unknown[] = Reflect.getMetadata(API_PARAMETERS_KEY, handler) ?? [];\n Reflect.defineMetadata(API_PARAMETERS_KEY, [...existing, ...newEntries], handler);\n };\n};\n","import { Inject, Injectable, Optional } from '@nestjs/common';\nimport { Reflector } from '@nestjs/core';\nimport { from } from 'rxjs';\nimport { mergeMap } from 'rxjs/operators';\n\nimport type { CallHandler, ExecutionContext, NestInterceptor } from '@nestjs/common';\nimport type { Observable } from 'rxjs';\nimport type { ZodDto } from '../dto/dto.types.js';\nimport type { LogValidationFailure } from '../logging/validation-logger.js';\nimport type { CreateSerializationException, NormalizedZodNestOptions } from '../module/options.js';\nimport type { ResponseStatusWildcard, ResponseVariant } from '../response/metadata.js';\nimport type { StreamContentTypeMatcher } from '../response/stream.js';\n\nimport { ZodSerializationException } from '../exceptions/serialization.exception.js';\nimport { noopLogValidationFailure } from '../logging/validation-logger.js';\nimport { ZOD_NEST_OPTIONS } from '../module/options.js';\nimport { resolveEffectiveStatus } from '../response/default-status.js';\nimport { ZOD_RESPONSES_METADATA_KEY } from '../response/metadata.js';\nimport { DEFAULT_STREAM_MATCHER, isStreamResponse } from '../response/stream.js';\n\nconst defaultSerializationFactory: CreateSerializationException = (err, ctx) =>\n new ZodSerializationException(err, ctx);\n\n// Label by `.id` (the OpenAPI component name) rather than `.name` (the class\n// name): a DTO synthesised from a raw schema is an anonymous output sibling\n// whose class name is the unhelpful `\"SiblingClass\"`, while its `.id` is the\n// meaningful component id (from `.meta({ id })` or the anonymous fallback).\nconst formatDtoLabel = (variant: ResponseVariant): string => {\n if (variant.kind === 'single') {\n return (variant.dto as ZodDto).id;\n }\n const dtos = variant.dto as readonly ZodDto[];\n return `[${dtos.map((d) => d.id).join(', ')}]`;\n};\n\nconst formatHandlerLabel = (context: ExecutionContext): string =>\n `${context.getClass().name}.${context.getHandler().name}`;\n\n// '1XX' → 1, '2XX' → 2, etc. `charCodeAt(0) - 48` is the leading digit;\n// `Math.floor(status / 100)` is the response's hundreds bucket.\nconst matchesWildcard = (wildcard: ResponseStatusWildcard, status: number): boolean =>\n wildcard.charCodeAt(0) - 48 === Math.floor(status / 100);\n\n/**\n * Two-pass variant selection: exact numeric match wins outright, then the\n * `'NXX'` wildcard variants get a chance. Source order breaks ties within\n * each pass — first match wins, mirroring author intent (decorators apply\n * bottom-up but `appendResponseVariant` prepends, so the runtime array is\n * already in source order).\n */\nconst selectVariant = (\n variants: readonly ResponseVariant[],\n status: number,\n handler: object,\n): ResponseVariant | undefined => {\n for (const variant of variants) {\n const effective = resolveEffectiveStatus(variant, handler);\n if (typeof effective === 'number' && effective === status) {\n return variant;\n }\n }\n for (const variant of variants) {\n const effective = resolveEffectiveStatus(variant, handler);\n if (typeof effective === 'string' && matchesWildcard(effective, status)) {\n return variant;\n }\n }\n return undefined;\n};\n\n@Injectable()\nexport class ZodSerializerInterceptor implements NestInterceptor {\n private readonly logOutputFailure: LogValidationFailure;\n private readonly createSerializationException: CreateSerializationException;\n private readonly streamMatcher: StreamContentTypeMatcher;\n\n constructor(\n private readonly reflector: Reflector,\n @Optional() @Inject(ZOD_NEST_OPTIONS) options?: NormalizedZodNestOptions,\n ) {\n this.logOutputFailure = options?.logOutputFailure ?? noopLogValidationFailure;\n this.createSerializationException =\n options?.createSerializationException ?? defaultSerializationFactory;\n // Falls back to built-in defaults when the module isn't configured\n // (`ZodSerializerInterceptor` used standalone, without `ZodNestModule`).\n this.streamMatcher = options?.streamMatcher ?? DEFAULT_STREAM_MATCHER;\n }\n\n intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {\n if (context.getType() !== 'http') {\n return next.handle();\n }\n const handler = context.getHandler();\n const variants = this.reflector.get<readonly ResponseVariant[] | undefined>(\n ZOD_RESPONSES_METADATA_KEY,\n handler,\n );\n if (variants === undefined || variants.length === 0) {\n return next.handle();\n }\n return next\n .handle()\n .pipe(mergeMap((value) => from(this.transform(value, variants, context, handler))));\n }\n\n private async transform(\n value: unknown,\n variants: readonly ResponseVariant[],\n context: ExecutionContext,\n handler: object,\n ): Promise<unknown> {\n const response = context.switchToHttp().getResponse<{ statusCode?: number }>();\n const status = response.statusCode;\n if (status === undefined) {\n return value;\n }\n const variant = selectVariant(variants, status, handler);\n if (variant === undefined) {\n return value;\n }\n // Streams (SSE / NDJSON / binary) are written straight to the response\n // buffer — there's no single body to validate, so pass it through as-is.\n if (isStreamResponse(variant, handler, this.streamMatcher)) {\n return value;\n }\n const result = await variant.validationSchema.safeParseAsync(value);\n if (result.success) {\n return result.data;\n }\n const isSoft = variant.passthroughOnError;\n this.logOutputFailure(result.error, value, {\n side: 'output',\n severity: isSoft ? 'warn' : 'error',\n dto: formatDtoLabel(variant),\n status,\n handler: formatHandlerLabel(context),\n });\n if (isSoft) {\n return value;\n }\n throw this.createSerializationException(result.error, context);\n }\n}\n","import { APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';\n\nimport type { DynamicModule } from '@nestjs/common';\nimport type { ZodNestModuleOptions } from './options.js';\n\nimport { ZodSerializerInterceptor } from '../interceptors/serializer.interceptor.js';\nimport { ZodValidationPipe } from '../pipes/validation.pipe.js';\nimport { normalizeZodNestOptions, ZOD_NEST_OPTIONS } from './options.js';\n\n/**\n * Central wiring for the zod-nest pipe + interceptor. Call\n * `ZodNestModule.forRoot(options?)` from your root `AppModule` to register\n * `APP_PIPE` (`ZodValidationPipe`) and `APP_INTERCEPTOR`\n * (`ZodSerializerInterceptor`) globally, with shared options for\n * validation logging, redaction, and exception factories.\n *\n * `forRoot()` is optional — the pipe and interceptor also work as\n * regular `APP_PIPE` / `APP_INTERCEPTOR` providers if you prefer to\n * wire them manually; `@Optional()` injection of `ZOD_NEST_OPTIONS`\n * falls through to safe defaults.\n *\n * Marked `global` so the `ZOD_NEST_OPTIONS` token is injectable from\n * feature modules (e.g. a custom pipe that wants the same logger /\n * redact list as the module-wired one).\n */\nexport class ZodNestModule {\n static forRoot(options?: ZodNestModuleOptions): DynamicModule {\n const normalized = normalizeZodNestOptions(options);\n return {\n module: ZodNestModule,\n global: true,\n providers: [\n { provide: ZOD_NEST_OPTIONS, useValue: normalized },\n { provide: APP_PIPE, useClass: ZodValidationPipe },\n { provide: APP_INTERCEPTOR, useClass: ZodSerializerInterceptor },\n ],\n exports: [ZOD_NEST_OPTIONS],\n };\n }\n}\n","import { z } from 'zod';\n\nimport type { Override } from '../schema/override.js';\nimport type { ZodNestRegistry } from '../schema/registry.js';\n\nimport { buildToJsonSchemaOptions } from '../schema/engine.js';\n\nexport interface BulkEmitOptions {\n registry: ZodNestRegistry;\n override?: Override;\n /** When `true` (default), unrepresentable Zod constructs throw `ZodNestUnrepresentableError`. */\n strict?: boolean;\n}\n\nexport interface BulkEmitResult {\n /** Schemas emitted with `io: 'input'`. Filtered to zod-nest-known ids only. */\n inputSchemas: Map<string, unknown>;\n /** Schemas emitted with `io: 'output'`. Filtered to zod-nest-known ids only. */\n outputSchemas: Map<string, unknown>;\n}\n\nconst URI = (id: string): string => `#/components/schemas/${id}`;\n\n/**\n * Two-pass bulk emission against the registry's underlying `z.globalRegistry`.\n * Returns one map per io. Result is filtered to the ids zod-nest itself\n * registered (via `registry.ids()`) — `z.globalRegistry` may hold third-party\n * entries we don't own.\n *\n * Uses `buildToJsonSchemaOptions` so emission semantics (override chain,\n * cycles, unrepresentable detection, metadata) match the single-schema\n * `toOpenApi` path. The `uri` callback shapes every registered-schema\n * `$ref` directly to `#/components/schemas/<id>` — doc-level refs need no\n * rewrite at emission time. `reused: 'inline'` keeps Zod\n * from extracting anonymous reused sub-schemas into a virtual `__shared`\n * defs table whose refs would dangle against `components.schemas`.\n */\nexport const bulkEmit = (opts: BulkEmitOptions): BulkEmitResult => {\n const knownIds = new Set(opts.registry.ids());\n return {\n inputSchemas: runPass(opts, 'input', knownIds),\n outputSchemas: runPass(opts, 'output', knownIds),\n };\n};\n\nconst runPass = (\n opts: BulkEmitOptions,\n io: 'input' | 'output',\n knownIds: ReadonlySet<string>,\n): Map<string, unknown> => {\n const built = buildToJsonSchemaOptions({\n registry: opts.registry,\n io,\n override: opts.override,\n strict: opts.strict,\n reused: 'inline',\n uri: URI,\n });\n // Zod v4's bulk-mode emission always returns `{ schemas: Record<...> }` —\n // even for an empty registry the `schemas` key is present with `{}`.\n const raw = z.toJSONSchema(opts.registry.zodRegistry, built.options) as {\n schemas: Record<string, unknown>;\n };\n built.consumeUnrepresentable();\n\n // Iterate Zod's emission (the source of truth for what was actually\n // emitted) and keep only the ids we registered. Inverts the older\n // `for (knownIds) { if (raw.schemas has id) ... }` shape so the filter\n // branches are naturally covered by the existing \"filter outside ids\"\n // test instead of a defensive guard that was never exercised.\n const filtered = new Map<string, unknown>();\n for (const [id, schema] of Object.entries(raw.schemas)) {\n if (knownIds.has(id)) {\n filtered.set(id, schema);\n }\n }\n return filtered;\n};\n","import type { OpenAPIObject } from '@nestjs/swagger';\n\n/** OpenAPI 3.1 operation methods, in spec order. */\nexport const HTTP_METHODS: readonly string[] = [\n 'get',\n 'put',\n 'post',\n 'delete',\n 'options',\n 'head',\n 'patch',\n 'trace',\n];\n\n/**\n * Visits every `(pathItem, op)` pair in the doc, narrowed to plain records.\n * Centralises the defensive `paths → pathItem → op` walk that several\n * post-process passes need; callers that mutate `op` (e.g. swap\n * `op.parameters`) can do so in place.\n */\nexport const forEachOperation = (\n doc: OpenAPIObject,\n fn: (op: Record<string, unknown>) => void,\n): void => {\n const paths = doc.paths;\n if (paths === null || typeof paths !== 'object') {\n return;\n }\n for (const pathItem of Object.values(paths)) {\n if (pathItem === null || typeof pathItem !== 'object') {\n continue;\n }\n const pathRecord = pathItem as Record<string, unknown>;\n for (const method of HTTP_METHODS) {\n const op = pathRecord[method];\n if (op === null || typeof op !== 'object') {\n continue;\n }\n fn(op as Record<string, unknown>);\n }\n }\n};\n","/**\n * Visitor invoked for every `{ $ref: string }` node encountered during\n * `walkRefs`. Return a new string to mutate the ref in place; return\n * `undefined` to leave it untouched.\n */\nexport type RefVisitor = (ref: string) => string | undefined;\n\n/**\n * Deeply walks an OpenAPI sub-tree, invoking `visit` on every `$ref` string\n * value. Mutates the tree in place when the visitor returns a replacement.\n */\nexport const walkRefs = (node: unknown, visit: RefVisitor): void => {\n if (node === null || typeof node !== 'object') {\n return;\n }\n if (Array.isArray(node)) {\n for (const item of node) {\n walkRefs(item, visit);\n }\n return;\n }\n const obj = node as Record<string, unknown>;\n for (const key of Object.keys(obj)) {\n const value = obj[key];\n if (key === '$ref' && typeof value === 'string') {\n const next = visit(value);\n if (next !== undefined) {\n obj[key] = next;\n }\n continue;\n }\n walkRefs(value, visit);\n }\n};\n","import type { OpenAPIObject } from '@nestjs/swagger';\nimport type { ZodNestRegistry } from '../schema/registry.js';\n\nimport { isZodDtoMarker } from '../dto/marker.js';\nimport { COMPONENTS_SCHEMAS_PREFIX, ZOD_NEST_DTO_EXTENSION } from '../schema/constants.js';\nimport { HTTP_METHODS } from './http-methods.js';\nimport { walkRefs } from './walk-refs.js';\n\nexport interface CollectedUsage {\n /** dtoIds referenced as input via requestBody / parameters `$ref`s in the doc. */\n inputExposedIds: ReadonlySet<string>;\n /** dtoIds referenced as output via `@ZodResponse` on any controller handler. */\n outputExposedIds: ReadonlySet<string>;\n /** Map of `components.schemas` key (NestJS class name) → dtoId from the marker. */\n classToDtoId: ReadonlyMap<string, string>;\n}\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n\n/**\n * Pre-pass over an `applyZodNest` input. Walks the already-built OpenAPI doc\n * for both input-side ids (`requestBody` / `parameters` `$ref`s, plus query /\n * param marker placeholders) and output-side ids (`responses.*.content.*`\n * `$ref`s — `@ZodResponse`'s swagger bridge emits these via `@ApiResponse`, so\n * the document is the source of truth). Walking the document keeps exposure\n * scoped to the endpoints in *this* document — important when several Swagger\n * documents share one registry.\n */\nexport const collectUsage = (doc: OpenAPIObject, registry: ZodNestRegistry): CollectedUsage => {\n const classToDtoId = buildClassToDtoIdMap(doc);\n const knownIds = new Set(registry.ids());\n const inputExposedIds = collectInputExposedIds(doc, classToDtoId, knownIds);\n const outputExposedIds = collectOutputExposedIds(doc, classToDtoId, knownIds);\n return { inputExposedIds, outputExposedIds, classToDtoId };\n};\n\nconst buildClassToDtoIdMap = (doc: OpenAPIObject): Map<string, string> => {\n const map = new Map<string, string>();\n const schemas = doc.components?.schemas ?? {};\n for (const [className, schema] of Object.entries(schemas)) {\n const marker = readMarker(schema);\n if (marker === undefined) {\n continue;\n }\n map.set(className, marker.dtoId);\n }\n return map;\n};\n\nconst readMarker = (schema: unknown): { dtoId: string } | undefined => {\n if (!isPlainRecord(schema)) {\n return undefined;\n }\n if (!isPlainRecord(schema.properties)) {\n return undefined;\n }\n const marker = schema.properties[ZOD_NEST_DTO_EXTENSION];\n if (!isZodDtoMarker(marker)) {\n return undefined;\n }\n return { dtoId: marker.dtoId };\n};\n\nconst collectInputExposedIds = (\n doc: OpenAPIObject,\n classToDtoId: ReadonlyMap<string, string>,\n knownIds: ReadonlySet<string>,\n): Set<string> => {\n const ids = new Set<string>();\n const paths = doc.paths ?? {};\n for (const pathItem of Object.values(paths)) {\n if (!isPlainRecord(pathItem)) {\n continue;\n }\n for (const operation of operationsOf(pathItem)) {\n collectRefsFromOperation(operation, classToDtoId, knownIds, ids);\n }\n }\n return ids;\n};\n\nconst operationsOf = (pathItem: Record<string, unknown>): Record<string, unknown>[] => {\n const out: Record<string, unknown>[] = [];\n for (const method of HTTP_METHODS) {\n const op = pathItem[method];\n if (isPlainRecord(op)) {\n out.push(op);\n }\n }\n return out;\n};\n\nconst collectRefsFromOperation = (\n operation: Record<string, unknown>,\n classToDtoId: ReadonlyMap<string, string>,\n knownIds: ReadonlySet<string>,\n ids: Set<string>,\n): void => {\n // requestBody.content.*.schema.$ref\n if (isPlainRecord(operation.requestBody)) {\n collectRefsFromContent(operation.requestBody.content, classToDtoId, knownIds, ids);\n }\n // parameters[*].schema.$ref AND parameters[*] marker placeholders\n const parameters = operation.parameters;\n if (Array.isArray(parameters)) {\n for (const param of parameters) {\n if (!isPlainRecord(param)) {\n continue;\n }\n collectRefFromSchema(param.schema, classToDtoId, knownIds, ids);\n collectIdFromMarkerParam(param, ids);\n }\n }\n};\n\nconst collectIdFromMarkerParam = (param: Record<string, unknown>, ids: Set<string>): void => {\n if (param.__zodNestDto !== true) {\n return;\n }\n const dtoId = param.dtoId;\n if (typeof dtoId !== 'string' || dtoId === '') {\n return;\n }\n ids.add(dtoId);\n};\n\nconst collectRefsFromContent = (\n content: unknown,\n classToDtoId: ReadonlyMap<string, string>,\n knownIds: ReadonlySet<string>,\n ids: Set<string>,\n): void => {\n if (!isPlainRecord(content)) {\n return;\n }\n for (const mediaType of Object.values(content)) {\n if (!isPlainRecord(mediaType)) {\n continue;\n }\n collectRefFromSchema(mediaType.schema, classToDtoId, knownIds, ids);\n }\n};\n\nconst collectRefFromSchema = (\n schema: unknown,\n classToDtoId: ReadonlyMap<string, string>,\n knownIds: ReadonlySet<string>,\n ids: Set<string>,\n): void => {\n if (!isPlainRecord(schema)) {\n return;\n }\n // Deep-walk so refs nested inside an inline body (e.g. `@ZodBody` with\n // `flatten: true` emits `{ type: 'object', properties: { p: { $ref } } }`)\n // are seeded too — the closure pass `extendExposureViaRefs` only walks\n // emitted bodies, not inline operation bodies, so it can't pick up\n // nested refs that never lived in `inputSchemas` / `outputSchemas`.\n walkRefs(schema, (ref) => {\n if (!ref.startsWith(COMPONENTS_SCHEMAS_PREFIX)) {\n return undefined;\n }\n const className = ref.slice(COMPONENTS_SCHEMAS_PREFIX.length);\n // Class-DTO refs go through the rename map (NestJS materializes\n // `components.schemas[ClassName]` and the marker says the real dtoId is X).\n // Decorator-emitted refs (`@ZodBody` / `@ZodQuery` / ...) target the id\n // directly with no marker hop — match it against the registry's known ids.\n // Refs to anything else (third-party `@ApiResponse({ schema: { $ref } })`)\n // are left untouched.\n const renamed = classToDtoId.get(className);\n if (renamed !== undefined) {\n ids.add(renamed);\n } else if (knownIds.has(className)) {\n ids.add(className);\n }\n return undefined;\n });\n};\n\nconst collectOutputExposedIds = (\n doc: OpenAPIObject,\n classToDtoId: ReadonlyMap<string, string>,\n knownIds: ReadonlySet<string>,\n): Set<string> => {\n const ids = new Set<string>();\n const paths = doc.paths ?? {};\n for (const pathItem of Object.values(paths)) {\n if (!isPlainRecord(pathItem)) {\n continue;\n }\n for (const operation of operationsOf(pathItem)) {\n collectRefsFromResponses(operation.responses, classToDtoId, knownIds, ids);\n }\n }\n return ids;\n};\n\nconst collectRefsFromResponses = (\n responses: unknown,\n classToDtoId: ReadonlyMap<string, string>,\n knownIds: ReadonlySet<string>,\n ids: Set<string>,\n): void => {\n if (!isPlainRecord(responses)) {\n return;\n }\n for (const response of Object.values(responses)) {\n if (!isPlainRecord(response)) {\n continue;\n }\n collectRefsFromContent(response.content, classToDtoId, knownIds, ids);\n }\n};\n","import { ZodNestError } from '../schema/errors.js';\n\nexport type ZodNestDocumentErrorCode =\n | 'AMBIGUOUS_RENAME'\n | 'DANGLING_REF'\n | 'UNEXPANDABLE_PARAM_DTO';\n\n/**\n * Thrown by `applyZodNest` when the doc cannot be processed cleanly. Surfaces\n * at doc-build time so typos / mis-registrations fail in CI, not at runtime.\n *\n * `AMBIGUOUS_RENAME`: two distinct DTO classes target the same registry id\n * with differing bodies — the rename pass can't write `components.schemas[id]`\n * unambiguously.\n *\n * `DANGLING_REF`: a `$ref` in the doc points at a `components.schemas` key\n * that no longer exists after `applyZodNest`. Usually means a marker was\n * stripped but its rename target wasn't populated, or a user-supplied pre-pass\n * left a stale ref.\n *\n * `UNEXPANDABLE_PARAM_DTO`: a `@Query()` / `@Param()` / `@Headers()` /\n * `@Cookie()` handler argument resolved to a `createZodDto` whose schema is\n * not an object — the marker parameter can't be expanded into individual\n * parameters because there's no top-level `properties` record to iterate.\n */\nexport class ZodNestDocumentError extends ZodNestError {\n readonly code: ZodNestDocumentErrorCode;\n readonly details: Readonly<Record<string, unknown>>;\n\n constructor(\n code: ZodNestDocumentErrorCode,\n message: string,\n details: Record<string, unknown> = {},\n ) {\n super(`[zod-nest] ${code}: ${message}`);\n this.name = 'ZodNestDocumentError';\n this.code = code;\n this.details = details;\n }\n}\n","import type { OpenAPIObject } from '@nestjs/swagger';\nimport type { CollectedUsage } from './collect-usage.js';\n\nimport { COMPONENTS_SCHEMAS_PREFIX } from '../schema/constants.js';\nimport { ZodNestDocumentError } from './errors.js';\nimport { walkRefs } from './walk-refs.js';\n\nexport interface AssertNoDanglingRefsParams {\n doc: OpenAPIObject;\n collected: CollectedUsage;\n}\n\n/**\n * Final assertion pass over the doc. Walks every `$ref` and confirms that\n * any `#/components/schemas/<id>` target exists in `components.schemas`.\n * Throws `ZodNestDocumentError({ code: 'DANGLING_REF' })` listing all\n * offending refs with a per-ref hint inferred from `collected` — whether\n * the id was seen in input/output usage (suggests a registry mismatch) or\n * is otherwise unknown (likely a `meta.id` typo or unregistered DTO).\n *\n * Scoped to `#/components/schemas/` refs only — refs into other component\n * namespaces (`#/components/parameters/...`, `#/components/responses/...`)\n * are user-managed and not validated here.\n */\nexport const assertNoDanglingRefs = (params: AssertNoDanglingRefsParams): void => {\n const { doc, collected } = params;\n const schemas = (doc.components?.schemas ?? {}) as Record<string, unknown>;\n const dangling: string[] = [];\n walkRefs(doc, (ref) => {\n if (!ref.startsWith(COMPONENTS_SCHEMAS_PREFIX)) {\n return undefined;\n }\n const target = ref.slice(COMPONENTS_SCHEMAS_PREFIX.length);\n if (!(target in schemas)) {\n dangling.push(ref);\n }\n return undefined;\n });\n if (dangling.length === 0) {\n return;\n }\n const lines = dangling.map((ref) => ` - ${ref} — ${hintFor(ref, collected)}`);\n throw new ZodNestDocumentError(\n 'DANGLING_REF',\n `Found ${dangling.length} \\`$ref\\` target(s) that don't resolve to a ` +\n 'schema in `components.schemas`. The most common cause is a `meta.id` ' +\n 'typo on a DTO, a DTO used without `createZodDto`, or a `$ref` left ' +\n `behind by a pre-pass that mutated the doc before \\`applyZodNest\\`.\\n${lines.join('\\n')}`,\n { dangling },\n );\n};\n\nconst hintFor = (ref: string, collected: CollectedUsage): string => {\n const id = ref.slice(COMPONENTS_SCHEMAS_PREFIX.length);\n const usedInput = collected.inputExposedIds.has(id);\n const usedOutput = collected.outputExposedIds.has(id);\n if (usedInput && usedOutput) {\n return 'used as input and output but body missing — DTO is registered under a different id';\n }\n if (usedInput) {\n return 'used as input but body missing — DTO is registered under a different id';\n }\n if (usedOutput) {\n return 'used as output but body missing — DTO is registered under a different id';\n }\n return 'no DTO with this id was registered — check for a meta.id typo or a DTO used without createZodDto';\n};\n","import type { OpenAPIObject } from '@nestjs/swagger';\n\nimport { COMPONENTS_SCHEMAS_PREFIX } from '../schema/constants.js';\nimport { ZodNestDocumentError } from './errors.js';\nimport { forEachOperation } from './http-methods.js';\nimport { walkRefs } from './walk-refs.js';\n\n/**\n * How a named `@Query()` / `@ZodQuery` DTO is represented in the OpenAPI doc:\n *\n * - `'expand'` (default) — one parameter per top-level property of the DTO\n * schema, each inlined or `$ref`'d independently.\n * - `'ref'` — a single schema-based query parameter that references the DTO's\n * `components.schemas` entry (`style: 'form'`, `explode: true`,\n * `schema: { $ref }`). The wire format is identical to `'expand'`; only the\n * document representation collapses to the shared component.\n *\n * Query-only: path / header / cookie markers always expand regardless of this\n * setting, since the form-exploded-object pattern is a query serialization.\n */\nexport type QueryParamStyle = 'expand' | 'ref';\n\nexport interface ExpandParamMarkersParams {\n /** OpenAPI doc whose `paths.*.<op>.parameters[]` will be mutated in place. */\n doc: OpenAPIObject;\n /** Bulk-emitted input-side schemas keyed by `dtoId`. Source of truth for `io: 'input'` markers. */\n inputSchemas: ReadonlyMap<string, unknown>;\n /** Bulk-emitted output-side schemas keyed by `dtoId`. Source for the (rare) `io: 'output'` parameter marker. */\n outputSchemas: ReadonlyMap<string, unknown>;\n /**\n * Global preference for how `in: 'query'` DTO markers are represented.\n * Defaults to `'expand'`. A per-marker `ref` override (set by `@ZodQuery`)\n * wins over this when present.\n */\n queryParamStyle?: QueryParamStyle;\n}\n\ninterface MarkerParam extends Record<string, unknown> {\n in: string;\n dtoId: string;\n io: 'input' | 'output';\n /**\n * Per-marker override of `queryParamStyle`. `true` forces the single-`$ref`\n * query parameter, `false` forces per-property expansion, `undefined` falls\n * back to the global preference. Only `@ZodQuery({ ref })` sets it; the\n * `@Query() dto` marker omits it (follows the global preference).\n */\n ref?: boolean;\n}\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n\n/**\n * Replaces every `@Query()` / `@Param()` / `@Headers()` / `@Cookie()` marker\n * parameter — the `__zodNestDto: true` placeholder produced by\n * `createZodDto`'s `_OPENAPI_METADATA_FACTORY` when the DTO class is bound to\n * a non-body decorator — with one parameter per top-level property of the\n * DTO schema.\n *\n * A `'query'` marker is instead collapsed to a single schema-based parameter\n * (`style: 'form'`, `explode: true`, `schema: { $ref }`) when ref mode applies\n * — either the per-marker `ref` override (from `@ZodQuery`) or the global\n * `queryParamStyle: 'ref'` preference. Ref mode is query-only; path / header /\n * cookie markers always expand. See `QueryParamStyle`.\n *\n * Runs after `mergeSchemas` (so the real schema body lives in the\n * `inputSchemas` map, and the DTO's component is in `doc.components.schemas`\n * for ref mode) and before `rewriteRefs` (so any `$ref` inside a property\n * schema gets rewritten in the subsequent pass).\n *\n * After expansion, if `components.schemas.Object` (the synthetic placeholder\n * `@nestjs/swagger` materialises from the marker's `type: () => Object`) has\n * no remaining referrers, the entry is pruned. This matches the cleaner\n * output the predecessor library (`nestjs-zod`) emitted and keeps the doc\n * free of dead schemas.\n *\n * Throws `ZodNestDocumentError('UNEXPANDABLE_PARAM_DTO')` when a marker\n * parameter resolves to a non-object schema (array, union, primitive, …) —\n * those shapes have no `properties` record to iterate, so the only sensible\n * action is to fail loudly at doc-build time.\n */\nexport const expandParamMarkers = (params: ExpandParamMarkersParams): void => {\n const { doc, inputSchemas, outputSchemas } = params;\n const queryParamStyle = params.queryParamStyle ?? 'expand';\n const schemas = doc.components?.schemas;\n const componentIds =\n schemas !== null && typeof schemas === 'object'\n ? new Set(Object.keys(schemas))\n : new Set<string>();\n let expandedAny = false;\n forEachOperation(doc, (op) => {\n const parameters = op.parameters;\n if (!Array.isArray(parameters)) {\n return;\n }\n const next = expandParameterList(parameters, {\n inputSchemas,\n outputSchemas,\n queryParamStyle,\n componentIds,\n });\n if (next !== parameters) {\n op.parameters = next;\n expandedAny = true;\n }\n });\n // The synthetic `components.schemas.Object` only appears when at least one\n // marker parameter was processed by @nestjs/swagger — skip the full-doc\n // ref walk on the common no-marker path.\n if (expandedAny) {\n pruneOrphanObjectSchema(doc);\n }\n};\n\ninterface ExpandContext {\n readonly inputSchemas: ReadonlyMap<string, unknown>;\n readonly outputSchemas: ReadonlyMap<string, unknown>;\n readonly queryParamStyle: QueryParamStyle;\n readonly componentIds: ReadonlySet<string>;\n}\n\nconst expandParameterList = (\n parameters: readonly unknown[],\n context: ExpandContext,\n): readonly unknown[] => {\n let result: unknown[] | undefined;\n for (let i = 0; i < parameters.length; i++) {\n const param = parameters[i];\n const marker = readMarker(param);\n if (marker === undefined) {\n result?.push(param);\n continue;\n }\n if (result === undefined) {\n result = parameters.slice(0, i);\n }\n const map = marker.io === 'output' ? context.outputSchemas : context.inputSchemas;\n const body = map.get(marker.dtoId);\n result.push(...resolveMarker(marker, body, context));\n }\n return result ?? parameters;\n};\n\n/**\n * Decide whether a `'query'` marker collapses to a single schema-based\n * parameter (`ref`) or expands per-property. The per-marker `ref` override\n * wins; otherwise the global `queryParamStyle` decides. Ref mode is query-only\n * and needs the DTO's component to exist in the doc — `collectUsage` adds the\n * marker's dtoId to `inputExposedIds` so `mergeSchemas` emits it. If it somehow\n * still isn't present, fall back to expansion so the contract ships rather than\n * dangling.\n */\nconst resolveMarker = (marker: MarkerParam, body: unknown, context: ExpandContext): unknown[] => {\n const useRef = marker.ref ?? context.queryParamStyle === 'ref';\n if (marker.in === 'query' && useRef && context.componentIds.has(marker.dtoId)) {\n return [buildRefQueryParam(marker, body)];\n }\n return expandOne(marker, body);\n};\n\n/**\n * Build the single schema-based query parameter for `ref` mode. References the\n * DTO's `components.schemas` entry via `$ref`, with `style: 'form'` +\n * `explode: true` so the wire format matches the per-property expansion\n * (`?a=1&b=2`). The parameter is marked `required` when the schema has at\n * least one required field; per-field requiredness stays in the referenced\n * component's `required` array.\n */\nconst buildRefQueryParam = (marker: MarkerParam, body: unknown): Record<string, unknown> => {\n const required = isPlainRecord(body) && Array.isArray(body.required) && body.required.length > 0;\n return {\n name: marker.dtoId,\n in: 'query',\n required,\n style: 'form',\n explode: true,\n schema: { $ref: `${COMPONENTS_SCHEMAS_PREFIX}${marker.dtoId}` },\n };\n};\n\nconst readMarker = (value: unknown): MarkerParam | undefined => {\n if (!isPlainRecord(value)) {\n return undefined;\n }\n if (value.__zodNestDto !== true) {\n return undefined;\n }\n if (typeof value.dtoId !== 'string' || value.dtoId === '') {\n return undefined;\n }\n if (value.io !== 'input' && value.io !== 'output') {\n return undefined;\n }\n if (typeof value.in !== 'string' || value.in === '') {\n return undefined;\n }\n if (value.ref !== undefined && typeof value.ref !== 'boolean') {\n return undefined;\n }\n return value as MarkerParam;\n};\n\nconst expandOne = (marker: MarkerParam, body: unknown): unknown[] => {\n if (!isPlainRecord(body) || !isPlainRecord(body.properties)) {\n throw new ZodNestDocumentError(\n 'UNEXPANDABLE_PARAM_DTO',\n `Cannot expand \\`@${capitalize(marker.in)}() x: ${marker.dtoId}\\` — the DTO's schema is not an object with \\`properties\\`. ` +\n `Non-body parameter DTOs must be object schemas; arrays, unions, primitives, etc. cannot be split into individual ` +\n `parameters. Use \\`@Body()\\` for non-object DTOs, or restructure the schema as an object whose fields become the params.`,\n { dtoId: marker.dtoId, in: marker.in, io: marker.io },\n );\n }\n const properties = body.properties;\n const requiredSet = collectRequired(body.required);\n const out: unknown[] = [];\n for (const [propName, propSchemaRaw] of Object.entries(properties)) {\n if (!isPlainRecord(propSchemaRaw)) {\n continue;\n }\n out.push(buildParameter(marker, propName, propSchemaRaw, requiredSet.has(propName)));\n }\n return out;\n};\n\nconst collectRequired = (value: unknown): Set<string> => {\n if (!Array.isArray(value)) {\n return new Set();\n }\n const out = new Set<string>();\n for (const item of value) {\n if (typeof item === 'string') {\n out.add(item);\n }\n }\n return out;\n};\n\nconst buildParameter = (\n marker: MarkerParam,\n name: string,\n schema: Record<string, unknown>,\n required: boolean,\n): Record<string, unknown> => {\n let effectiveRequired = required;\n if (marker.in === 'path' && !effectiveRequired) {\n // eslint-disable-next-line no-console\n console.warn(\n `[zod-nest] Path parameter \\`${name}\\` on DTO \\`${marker.dtoId}\\` is marked optional ` +\n `in the Zod schema; OpenAPI 3.1 requires path parameters to be required. ` +\n `Coercing \\`required: true\\` so the emitted document is spec-valid. ` +\n `Fix by removing \\`.optional()\\` / \\`.nullish()\\` from the field, or by switching ` +\n `the decorator to @Query() / @Headers() if the field is genuinely optional.`,\n );\n effectiveRequired = true;\n }\n return {\n name,\n in: marker.in,\n required: effectiveRequired,\n schema,\n };\n};\n\nconst capitalize = (value: string): string => value.charAt(0).toUpperCase() + value.slice(1);\n\nconst pruneOrphanObjectSchema = (doc: OpenAPIObject): void => {\n const schemas = doc.components?.schemas as Record<string, unknown> | undefined;\n if (schemas === undefined || !Object.prototype.hasOwnProperty.call(schemas, 'Object')) {\n return;\n }\n let referenced = false;\n const targetRef = `${COMPONENTS_SCHEMAS_PREFIX}Object`;\n walkRefs(doc, (ref) => {\n if (ref === targetRef) {\n referenced = true;\n }\n return undefined;\n });\n if (!referenced) {\n delete schemas.Object;\n }\n};\n","import type { CollectedUsage } from './collect-usage.js';\n\nimport { COMPONENTS_SCHEMAS_PREFIX } from '../schema/constants.js';\nimport { walkRefs } from './walk-refs.js';\n\n/**\n * Closes the input/output exposure sets over `$ref`s. A nested `.meta({ id })`\n * schema declared without `createZodDto` is registered transitively (see\n * `registry.register`) and emitted by `bulkEmit`, but `collectUsage` won't\n * see it directly — it walks request/response bodies and `@ZodResponse`\n * metadata, not nested refs. Without this closure, `mergeSchemas` would\n * skip the nested body, leaving a dangling `$ref` in the final document.\n */\nexport const extendExposureViaRefs = (\n collected: CollectedUsage,\n inputSchemas: ReadonlyMap<string, unknown>,\n outputSchemas: ReadonlyMap<string, unknown>,\n): CollectedUsage => ({\n ...collected,\n inputExposedIds: closeOverRefs(collected.inputExposedIds, inputSchemas),\n outputExposedIds: closeOverRefs(collected.outputExposedIds, outputSchemas),\n});\n\n/**\n * BFS over `$ref`s starting from `seed`. For each `#/components/schemas/<id>`\n * encountered in a body, the target id joins the result and its own body is\n * scanned. Refs into other component buckets (`parameters`, `responses`, …)\n * are ignored — exposure closure only governs the schemas bucket. Ids that\n * appear in `seed` but not in `bodies` are kept (they may exist on the\n * other I/O side); they just don't contribute further reachable ids.\n */\nexport const closeOverRefs = (\n seed: ReadonlySet<string>,\n bodies: ReadonlyMap<string, unknown>,\n): Set<string> => {\n const out = new Set(seed);\n const queue = [...seed];\n while (queue.length > 0) {\n const id = queue.shift() as string;\n const body = bodies.get(id);\n if (body === undefined) {\n continue;\n }\n walkRefs(body, (ref) => {\n if (!ref.startsWith(COMPONENTS_SCHEMAS_PREFIX)) {\n return undefined;\n }\n const target = ref.slice(COMPONENTS_SCHEMAS_PREFIX.length);\n if (out.has(target)) {\n return undefined;\n }\n out.add(target);\n queue.push(target);\n return undefined;\n });\n }\n return out;\n};\n","/**\n * Suffix appended to a dtoId when its input and output emissions diverge —\n * input keeps the canonical id, output lifts to `<id>Output`.\n */\nexport const OUTPUT_SUFFIX = 'Output';\n","import type { OpenAPIObject } from '@nestjs/swagger';\nimport type { ZodNestRegistry } from '../schema/registry.js';\n\nimport { COMPONENTS_SCHEMAS_PREFIX } from '../schema/constants.js';\nimport { OUTPUT_SUFFIX } from './constants.js';\n\nexport interface InlineAnonymousBodiesParams {\n /** OpenAPI doc whose anonymous `$ref`s will be inlined in place. */\n doc: OpenAPIObject;\n /** Registry whose `anonymousIds()` identify the synthetic placeholder ids. */\n registry: ZodNestRegistry;\n}\n\n/**\n * Inlines every anonymous schema's body at its `$ref` site(s) and prunes the\n * synthetic component. An anonymous id is the placeholder minted for a schema\n * passed inline to `@ZodResponse` / `@ZodBody` with no resolvable id; it exists\n * only to carry the body through `bulkEmit` (so the body honors the document's\n * `strict` / `override`). By the time this runs the body has been written to\n * `components.schemas[id]` and cleaned by `stripMarkers`, so we clone it into\n * each referrer and drop the component.\n *\n * Runs after `mergeSchemas` + `rewriteRefs` + `stripMarkers`, before\n * `assertNoDanglingRefs`. The inlined body's nested member `$ref`s point at\n * real, exposed components (closed over by `extendExposureViaRefs`), so the\n * dangling-ref assertion still passes.\n *\n * A reused anonymous instance (same schema across N referrers) has its body\n * duplicated at each site — the author adds `.meta({ id })` to share it as a\n * named component instead. Both the canonical id and its divergent\n * `<id>Output` sibling (if input/output diverged) are inlined and pruned.\n */\nexport const inlineAnonymousBodies = ({ doc, registry }: InlineAnonymousBodiesParams): void => {\n const anonIds = registry.anonymousIds();\n if (anonIds.length === 0) {\n return;\n }\n const schemas = doc.components?.schemas;\n if (schemas === undefined) {\n return;\n }\n\n // Map each anonymous `$ref` string to the body it should be replaced with.\n // Include the `<id>Output` sibling so a schema used on both the input and\n // output side (and split by the I/O truth table) is inlined on both.\n const bodyByRef = new Map<string, Record<string, unknown>>();\n for (const anonId of anonIds) {\n for (const key of [anonId, `${anonId}${OUTPUT_SUFFIX}`]) {\n const body = schemas[key];\n if (isPlainRecord(body)) {\n bodyByRef.set(`${COMPONENTS_SCHEMAS_PREFIX}${key}`, body);\n }\n }\n }\n if (bodyByRef.size === 0) {\n return;\n }\n\n // Inline only within `paths` — anonymous ids are top-level body/response\n // placeholders, never referenced from another component schema.\n inlineRefs(doc.paths, bodyByRef);\n\n for (const ref of bodyByRef.keys()) {\n delete schemas[ref.slice(COMPONENTS_SCHEMAS_PREFIX.length)];\n }\n};\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n\n/**\n * Replaces every `{ $ref }` node whose target is in `bodyByRef` with a deep\n * clone of the body, in place. Does not recurse into a freshly-inlined body —\n * its refs are real member refs that must stay as `$ref`s.\n */\nconst inlineRefs = (\n node: unknown,\n bodyByRef: ReadonlyMap<string, Record<string, unknown>>,\n): void => {\n if (Array.isArray(node)) {\n for (const item of node) {\n inlineRefs(item, bodyByRef);\n }\n return;\n }\n if (!isPlainRecord(node)) {\n return;\n }\n const ref = node.$ref;\n if (typeof ref === 'string') {\n const body = bodyByRef.get(ref);\n if (body !== undefined) {\n for (const key of Object.keys(node)) {\n delete node[key];\n }\n Object.assign(node, structuredClone(body));\n return;\n }\n }\n for (const value of Object.values(node)) {\n inlineRefs(value, bodyByRef);\n }\n};\n","import stringify from 'fast-json-stable-stringify';\n\nimport type { OpenAPIObject } from '@nestjs/swagger';\nimport type { CollectedUsage } from './collect-usage.js';\n\nimport { isZodDtoMarker } from '../dto/marker.js';\nimport {\n ZOD_NEST_DTO_EXTENSION,\n ZOD_NEST_ERROR_DUPLICATE_ID,\n ZOD_NEST_ERROR_EXTENSION,\n} from '../schema/constants.js';\nimport { OUTPUT_SUFFIX } from './constants.js';\nimport { ZodNestDocumentError } from './errors.js';\n\nexport interface MergeSchemasParams {\n /** OpenAPI doc whose `components.schemas` will be mutated in place. */\n doc: OpenAPIObject;\n inputSchemas: ReadonlyMap<string, unknown>;\n outputSchemas: ReadonlyMap<string, unknown>;\n collected: CollectedUsage;\n /** Result of `registry.getCollisions()` — ids registered with two or more Zod schemas. */\n collisions: ReadonlyMap<string, ReadonlySet<unknown>>;\n}\n\nexport interface MergeSchemasResult {\n /** dtoIds whose input and output schemas diverged — output landed at `<id>Output`. */\n divergentOutputIds: ReadonlySet<string>;\n /** `className → dtoId` map for renames where they differ. */\n renames: ReadonlyMap<string, string>;\n}\n\n/**\n * Applies the I/O suffix truth table and class-name → dtoId rename pass to\n * the doc's `components.schemas`. Mutates the doc in place.\n *\n * Truth table per id (in `inputExposedIds ∪ outputExposedIds`):\n * - input-only → `components.schemas[id] = inputSchemas[id]`\n * - output-only → `components.schemas[id] = outputSchemas[id]`\n * - both & byte-equal → write either as `components.schemas[id]`\n * - both & differ → input as `id`, output as `<id>Output`\n *\n * Rename pass: for every `className → dtoId` mapping from the markers, if\n * `className !== dtoId` and the `className` key still exists in\n * `components.schemas`, delete it. The rename targets (`dtoId`) have already\n * been written by the truth-table step.\n *\n * Collision pass (parity with `engine.ts:62`): for every id in `collisions`,\n * replace its body in `components.schemas` with the duplicate-id error marker\n * so the broken contract is visible in Swagger UI.\n */\nexport const mergeSchemas = (params: MergeSchemasParams): MergeSchemasResult => {\n const { doc, inputSchemas, outputSchemas, collected, collisions } = params;\n const schemas = ensureComponentsSchemas(doc);\n const renames = new Map<string, string>();\n const divergentOutputIds = new Set<string>();\n\n const exposedIds = new Set([...collected.inputExposedIds, ...collected.outputExposedIds]);\n\n for (const id of exposedIds) {\n applyTruthTable(\n schemas,\n id,\n collected.inputExposedIds.has(id),\n collected.outputExposedIds.has(id),\n inputSchemas.get(id),\n outputSchemas.get(id),\n divergentOutputIds,\n );\n }\n\n for (const [className, dtoId] of collected.classToDtoId) {\n if (className === dtoId) {\n continue;\n }\n renames.set(className, dtoId);\n delete schemas[className];\n }\n\n applyCollisionDecoration(schemas, collisions, divergentOutputIds);\n\n return { divergentOutputIds, renames };\n};\n\nconst ensureComponentsSchemas = (doc: OpenAPIObject): Record<string, unknown> => {\n const components = (doc.components ?? {}) as Record<string, unknown>;\n doc.components = components as OpenAPIObject['components'];\n const schemas = (components.schemas ?? {}) as Record<string, unknown>;\n components.schemas = schemas;\n return schemas;\n};\n\nconst applyTruthTable = (\n schemas: Record<string, unknown>,\n id: string,\n inputExposed: boolean,\n outputExposed: boolean,\n inputBody: unknown,\n outputBody: unknown,\n divergentOutputIds: Set<string>,\n): void => {\n if (inputExposed && !outputExposed) {\n writeOrThrowAmbiguous(schemas, id, inputBody);\n return;\n }\n if (!inputExposed && outputExposed) {\n writeOrThrowAmbiguous(schemas, id, outputBody);\n return;\n }\n // Both exposed.\n if (canonicalEqual(inputBody, outputBody)) {\n writeOrThrowAmbiguous(schemas, id, inputBody);\n return;\n }\n writeOrThrowAmbiguous(schemas, id, inputBody);\n writeOrThrowAmbiguous(schemas, `${id}${OUTPUT_SUFFIX}`, outputBody);\n divergentOutputIds.add(id);\n};\n\nconst writeOrThrowAmbiguous = (\n schemas: Record<string, unknown>,\n key: string,\n body: unknown,\n): void => {\n if (body === undefined) {\n return;\n }\n const existing = schemas[key];\n if (existing === undefined || isMarkerPlaceholder(existing) || canonicalEqual(existing, body)) {\n schemas[key] = body;\n return;\n }\n throw new ZodNestDocumentError(\n 'AMBIGUOUS_RENAME',\n `Two distinct schemas target \\`components.schemas[${key}]\\` with differing bodies — ` +\n 'multiple createZodDto classes likely share the same dtoId. Set distinct `options.id` ' +\n 'values, or align the class names so renames are unambiguous.',\n { key },\n );\n};\n\nconst isMarkerPlaceholder = (value: unknown): boolean => {\n if (value === null || typeof value !== 'object') {\n return false;\n }\n const properties = (value as { properties?: unknown }).properties;\n if (properties === null || typeof properties !== 'object') {\n return false;\n }\n const marker = (properties as Record<string, unknown>)[ZOD_NEST_DTO_EXTENSION];\n return isZodDtoMarker(marker);\n};\n\nconst canonicalEqual = (a: unknown, b: unknown): boolean => {\n if (a === b) {\n return true;\n }\n if (a === undefined || b === undefined) {\n return false;\n }\n return stringify(a) === stringify(b);\n};\n\nconst applyCollisionDecoration = (\n schemas: Record<string, unknown>,\n collisions: ReadonlyMap<string, ReadonlySet<unknown>>,\n divergentOutputIds: ReadonlySet<string>,\n): void => {\n for (const [id] of collisions) {\n decorateIfPresent(schemas, id);\n if (divergentOutputIds.has(id)) {\n decorateIfPresent(schemas, `${id}${OUTPUT_SUFFIX}`);\n }\n }\n};\n\nconst decorateIfPresent = (schemas: Record<string, unknown>, key: string): void => {\n if (!(key in schemas)) {\n return;\n }\n schemas[key] = {\n description: `ERROR: duplicate zod-nest id <${key.replace(/Output$/, '')}>`,\n [ZOD_NEST_ERROR_EXTENSION]: ZOD_NEST_ERROR_DUPLICATE_ID,\n };\n};\n","import type { OpenAPIObject } from '@nestjs/swagger';\n\nimport { COMPONENTS_SCHEMAS_PREFIX } from '../schema/constants.js';\n\n/**\n * Copies each named component's `title` onto every `$ref` that targets it, as a\n * sibling property: `{ $ref: '#/components/schemas/Foo', title: 'Foo' }`.\n *\n * OpenAPI 3.1 (unlike 3.0) permits sibling keywords next to `$ref`. Swagger\n * UI's 3.1 renderer inlines referenced schemas without surfacing their\n * component name (swagger-api/swagger-ui#9540); carrying the target's `title`\n * onto the reference gives the renderer — and other 3.1-aware tooling — a name\n * to display for the reference.\n *\n * Only components that actually declare a `title` (via `.meta({ title })`)\n * contribute one; refs to untitled components are left untouched, and a `$ref`\n * that already carries its own `title` is never overwritten. The annotation is\n * semantically inert (a `title` is an annotation keyword, no validation\n * effect).\n *\n * Runs last — after every ref has been rewritten to its final dtoId and\n * anonymous bodies have been inlined — so titles also land on the member refs\n * inside an inlined anonymous body.\n */\nexport const applyRefTitles = (doc: OpenAPIObject): void => {\n const schemas = doc.components?.schemas;\n if (schemas === undefined) {\n return;\n }\n const titleById = new Map<string, string>();\n for (const [id, body] of Object.entries(schemas)) {\n if (isPlainRecord(body) && typeof body.title === 'string' && body.title !== '') {\n titleById.set(id, body.title);\n }\n }\n if (titleById.size === 0) {\n return;\n }\n addRefTitles(doc.paths, titleById);\n addRefTitles(schemas, titleById);\n};\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n\nconst addRefTitles = (node: unknown, titleById: ReadonlyMap<string, string>): void => {\n if (Array.isArray(node)) {\n for (const item of node) {\n addRefTitles(item, titleById);\n }\n return;\n }\n if (!isPlainRecord(node)) {\n return;\n }\n const ref = node.$ref;\n if (\n typeof ref === 'string' &&\n ref.startsWith(COMPONENTS_SCHEMAS_PREFIX) &&\n node.title === undefined\n ) {\n const title = titleById.get(ref.slice(COMPONENTS_SCHEMAS_PREFIX.length));\n if (title !== undefined) {\n node.title = title;\n }\n }\n for (const value of Object.values(node)) {\n addRefTitles(value, titleById);\n }\n};\n","import type { OpenAPIObject } from '@nestjs/swagger';\n\nimport { COMPONENTS_SCHEMAS_PREFIX } from '../schema/constants.js';\nimport { OUTPUT_SUFFIX } from './constants.js';\nimport { HTTP_METHODS } from './http-methods.js';\nimport { walkRefs } from './walk-refs.js';\n\nexport interface RewriteRefsParams {\n doc: OpenAPIObject;\n /** className → dtoId map from `mergeSchemas`. */\n renames: ReadonlyMap<string, string>;\n /** dtoIds whose output emission landed at `<id>Output`. */\n divergentOutputIds: ReadonlySet<string>;\n}\n\n/**\n * Single rewrite pass over the doc:\n *\n * 1. **Rename pass (whole doc)** — any `$ref` whose target id is in\n * `renames` gets rewritten from `#/components/schemas/<className>` to\n * `#/components/schemas/<dtoId>`. This applies in operations, parameters,\n * requestBody, responses, nested schemas, anywhere.\n * 2. **Output-suffix pass (responses only)** — within\n * `paths.*.{op}.responses.*`, any `$ref` whose (post-rename) target id\n * is in `divergentOutputIds` gets rewritten to\n * `#/components/schemas/<id>Output`. Scoped to response sub-trees so\n * input-side refs to the same id keep pointing at the canonical id.\n *\n * Ordering is significant: pass 1 runs first so pass 2 sees already-renamed\n * (dtoId-keyed) refs and only matches against `divergentOutputIds`.\n */\nexport const rewriteRefs = (params: RewriteRefsParams): void => {\n const { doc, renames, divergentOutputIds } = params;\n\n if (renames.size > 0) {\n walkRefs(doc, (ref) => {\n if (!ref.startsWith(COMPONENTS_SCHEMAS_PREFIX)) {\n return undefined;\n }\n const target = ref.slice(COMPONENTS_SCHEMAS_PREFIX.length);\n const renamed = renames.get(target);\n if (renamed === undefined) {\n return undefined;\n }\n return `${COMPONENTS_SCHEMAS_PREFIX}${renamed}`;\n });\n }\n\n if (divergentOutputIds.size === 0) {\n return;\n }\n\n const paths = doc.paths ?? {};\n for (const pathItem of Object.values(paths)) {\n if (pathItem === null || typeof pathItem !== 'object') {\n continue;\n }\n rewriteResponseSubtree(pathItem as Record<string, unknown>, divergentOutputIds);\n }\n};\n\nconst rewriteResponseSubtree = (\n pathItem: Record<string, unknown>,\n divergentOutputIds: ReadonlySet<string>,\n): void => {\n for (const method of HTTP_METHODS) {\n const op = pathItem[method];\n if (op === null || typeof op !== 'object') {\n continue;\n }\n const responses = (op as { responses?: unknown }).responses;\n if (responses === null || typeof responses !== 'object') {\n continue;\n }\n walkRefs(responses, (ref) => {\n if (!ref.startsWith(COMPONENTS_SCHEMAS_PREFIX)) {\n return undefined;\n }\n const target = ref.slice(COMPONENTS_SCHEMAS_PREFIX.length);\n if (!divergentOutputIds.has(target)) {\n return undefined;\n }\n return `${COMPONENTS_SCHEMAS_PREFIX}${target}${OUTPUT_SUFFIX}`;\n });\n }\n};\n","import type { OpenAPIObject } from '@nestjs/swagger';\n\nimport { isZodDtoMarker } from '../dto/marker.js';\nimport { ZOD_NEST_DTO_EXTENSION } from '../schema/constants.js';\nimport { forEachOperation } from './http-methods.js';\n\n/**\n * Removes `x-zod-nest-dto` placeholder entries from every\n * `components.schemas[K].properties` block, drops the JSON Schema 2020-12\n * metadata (`$schema`, `$id`) that Zod's bulk emission leaks onto every\n * component body, and removes any stray marker parameter that\n * `expandParamMarkers` left behind. Used as the final cleanup pass after\n * `mergeSchemas` + `expandParamMarkers` + `rewriteRefs`.\n *\n * In practice the schema marker has already been overwritten or its key\n * dropped by `mergeSchemas` whenever the DTO is exposed. The straggler case\n * is a registered DTO whose `dtoId === className` AND who was never exposed\n * (no `@Body` reference, no `@ZodResponse`) — `mergeSchemas` leaves the\n * marker in place, this pass strips it.\n *\n * The parameter strip is belt-and-braces — `expandParamMarkers` already\n * removes the marker placeholders by replacing them with expanded entries.\n * This pass catches anything that somehow slipped through (e.g. a future\n * caller that bypasses `applyZodNest`'s pipeline).\n *\n * The `$schema` / `$id` strip exists because Zod v4's bulk `toJSONSchema`\n * writes `$schema: \"https://json-schema.org/draft/2020-12/schema\"` and a\n * relative-URI-fragment `$id` (`#/components/schemas/<Id>`) onto every\n * emitted body. Swagger UI's strict ref resolver chokes on the `$id`\n * fragment — it re-anchors lookups against the leaf schema and then fails\n * to find `components` at the new root. The fields are redundant inside\n * OpenAPI anyway: the schema's identity comes from its `components.schemas`\n * key. We delete both.\n *\n * When the marker is the only property, the empty `properties` block is\n * dropped too. The `x-zod-nest-error` extension (engine collision policy)\n * is intentionally preserved so the broken contract stays visible in\n * Swagger UI.\n */\nexport const stripMarkers = (doc: OpenAPIObject): void => {\n const schemas = doc.components?.schemas;\n if (schemas !== undefined) {\n for (const schema of Object.values(schemas)) {\n stripMarkerFromSchema(schema);\n dropJsonSchemaMetadata(schema);\n }\n }\n stripMarkerParameters(doc);\n};\n\nconst dropJsonSchemaMetadata = (schema: unknown): void => {\n if (schema === null || typeof schema !== 'object') {\n return;\n }\n const body = schema as { $schema?: unknown; $id?: unknown };\n delete body.$schema;\n delete body.$id;\n};\n\nconst stripMarkerParameters = (doc: OpenAPIObject): void => {\n forEachOperation(doc, (op) => {\n const parameters = op.parameters;\n if (!Array.isArray(parameters)) {\n return;\n }\n op.parameters = parameters.filter((param) => !isZodDtoMarker(param));\n });\n};\n\nconst stripMarkerFromSchema = (schema: unknown): void => {\n if (schema === null || typeof schema !== 'object') {\n return;\n }\n const properties = (schema as { properties?: unknown }).properties;\n if (properties === null || typeof properties !== 'object') {\n return;\n }\n const props = properties as Record<string, unknown>;\n if (!(ZOD_NEST_DTO_EXTENSION in props)) {\n return;\n }\n delete props[ZOD_NEST_DTO_EXTENSION];\n if (Object.keys(props).length === 0) {\n delete (schema as { properties?: unknown }).properties;\n }\n};\n","import type { OpenAPIObject } from '@nestjs/swagger';\nimport type { Override } from '../schema/override.js';\nimport type { ZodNestRegistry } from '../schema/registry.js';\nimport type { CollectedUsage } from './collect-usage.js';\nimport type { QueryParamStyle } from './expand-param-markers.js';\n\nimport { defaultRegistry } from '../schema/registry.js';\nimport { bulkEmit } from './bulk-emit.js';\nimport { collectUsage } from './collect-usage.js';\nimport { assertNoDanglingRefs } from './dangling-refs.js';\nimport { expandParamMarkers } from './expand-param-markers.js';\nimport { extendExposureViaRefs } from './expose-closure.js';\nimport { inlineAnonymousBodies } from './inline-anon.js';\nimport { mergeSchemas } from './merge-schemas.js';\nimport { applyRefTitles } from './ref-titles.js';\nimport { rewriteRefs } from './rewrite-refs.js';\nimport { stripMarkers } from './strip-markers.js';\n\nconst withForcedExposure = (\n collected: CollectedUsage,\n registry: ZodNestRegistry,\n): CollectedUsage => {\n // Exposure is reachability-scoped: only ids actually referenced by this\n // document's endpoints (and their transitive `$ref` deps) are emitted.\n // `{ expose: true }` is the author's explicit opt-in to document a schema\n // that no endpoint references — seed those onto the input side (the default\n // documentation side) so the closure pass pulls in their deps too.\n const forced = registry.forceExposedIds();\n if (forced.length === 0) {\n return collected;\n }\n return {\n inputExposedIds: new Set([...collected.inputExposedIds, ...forced]),\n outputExposedIds: collected.outputExposedIds,\n classToDtoId: collected.classToDtoId,\n };\n};\n\nconst OPENAPI_VERSION = '3.1.0';\n\nexport interface ApplyZodNestOptions {\n /**\n * `ZodNestRegistry` instance that holds the zod-nest DTOs. Defaults to\n * `defaultRegistry` (the process-wide singleton populated by `createZodDto`).\n * Pass an explicit registry for multi-app isolation.\n */\n registry?: ZodNestRegistry;\n /** User override pipe applied on top of the built-in override during emission. */\n override?: Override;\n /**\n * Strict mode (default `true`) throws `ZodNestUnrepresentableError` on\n * unrepresentable Zod constructs (bigint / date / symbol / transform / ...).\n * Set to `false` to emit `{}` for those instead.\n */\n strict?: boolean;\n /**\n * How named `@Query()` / `@ZodQuery` DTOs are represented in the document\n * (default `'expand'`):\n *\n * - `'expand'` — one query parameter per top-level property of the DTO.\n * - `'ref'` — a single schema-based query parameter referencing the DTO's\n * `components.schemas` entry (`style: 'form'`, `explode: true`). The wire\n * format is unchanged; only the spec representation collapses to the\n * shared component. Note: Swagger UI renders the two forms differently.\n *\n * Query-only — path / header / cookie DTOs always expand. A per-handler\n * `@ZodQuery({ ref })` override takes precedence over this preference.\n */\n queryParamStyle?: QueryParamStyle;\n /**\n * Copy each named component's `title` (when set via `.meta({ title })`) onto\n * every `$ref` that targets it, as a sibling: `{ $ref, title }` (default\n * `true`).\n *\n * OpenAPI 3.1 allows siblings next to `$ref`, and Swagger UI's 3.1 renderer\n * inlines referenced schemas without showing their component name\n * (swagger-api/swagger-ui#9540); the sibling `title` gives the renderer (and\n * other 3.1-aware tools) a name to display. The annotation is semantically\n * inert. Set `false` to emit bare `$ref`s.\n */\n refTitles?: boolean;\n}\n\n/**\n * Post-processor over the OpenAPI document emitted by\n * `SwaggerModule.createDocument`. Mutates the doc in place AND returns it for\n * compositional convenience. After this runs:\n *\n * - Every `components.schemas[<DtoClassName>]` placeholder with an\n * `x-zod-nest-dto` marker is replaced by the Zod-derived JSON Schema body,\n * keyed by the marker's `dtoId` (renaming as needed).\n * - Every `@Query()` / `@Param()` / `@Headers()` / `@Cookie()` marker\n * parameter is expanded into one parameter per top-level property of the\n * DTO's schema (`expandParamMarkers`) — except `@Query()` DTOs under\n * `queryParamStyle: 'ref'` (or a `@ZodQuery({ ref: true })` override), which\n * collapse to a single `$ref` schema-based query parameter. The synthetic\n * `components.schemas.Object` that `@nestjs/swagger` materialises for the\n * marker placeholder is pruned when it has no remaining referrers.\n * - The I/O suffix truth table is applied — equal input/output bodies collapse\n * to one `components.schemas[id]`; divergent bodies split as\n * `id` (input) + `idOutput` (output), with response-side refs rewritten.\n * - Anonymous body/response schemas (no `.meta({ id })`) are inlined at their\n * `$ref` sites and their synthetic components pruned (`inlineAnonymousBodies`).\n * - Only schemas reachable from this document's endpoints (plus their\n * transitive `$ref` deps, plus any `{ expose: true }` opt-ins) are kept —\n * unreferenced registered schemas are pruned. Exposure is document-scoped, so\n * several documents sharing one registry each carry only what they use.\n * - Each named component's `title` is copied onto every `$ref` that targets it\n * as a `{ $ref, title }` sibling (`applyRefTitles`, unless `refTitles: false`)\n * so Swagger UI's 3.1 renderer surfaces the component name. Inert annotation.\n * - Every `$ref` whose target is missing throws `ZodNestDocumentError(DANGLING_REF)`.\n * - `doc.openapi` is set to `'3.1.0'` — zod-nest emits OpenAPI 3.1 only; this\n * guarantees the version string matches the emitted body regardless of the\n * `DocumentBuilder` configuration on the caller side.\n *\n * Composable with other doc-transform passes — apply other mutations before\n * or after this function.\n */\nexport const applyZodNest = (doc: OpenAPIObject, opts: ApplyZodNestOptions = {}): OpenAPIObject => {\n const registry = opts.registry ?? defaultRegistry;\n\n const collected = collectUsage(doc, registry);\n // Reachability-scoped exposure: `collectUsage` seeds what the document's\n // endpoints actually reference; `{ expose: true }` opt-ins are added on top.\n const exposed = withForcedExposure(collected, registry);\n const { inputSchemas, outputSchemas } = bulkEmit({\n registry,\n override: opts.override,\n strict: opts.strict,\n });\n const extended = extendExposureViaRefs(exposed, inputSchemas, outputSchemas);\n const { divergentOutputIds, renames } = mergeSchemas({\n doc,\n inputSchemas,\n outputSchemas,\n collected: extended,\n collisions: registry.getCollisions(),\n });\n expandParamMarkers({ doc, inputSchemas, outputSchemas, queryParamStyle: opts.queryParamStyle });\n rewriteRefs({ doc, renames, divergentOutputIds });\n stripMarkers(doc);\n inlineAnonymousBodies({ doc, registry });\n if (opts.refTitles !== false) {\n applyRefTitles(doc);\n }\n assertNoDanglingRefs({ doc, collected: extended });\n doc.openapi = OPENAPI_VERSION;\n\n return doc;\n};\n"]}
|