zod-nest 0.1.5 → 0.3.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 CHANGED
@@ -1,5 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { JSONSchema, $ZodTypes } from 'zod/v4/core';
3
+ import { BadRequestException, ArgumentMetadata, PipeTransform } from '@nestjs/common';
3
4
 
4
5
  /** OpenAPI 3.1 `$ref` prefix for entries in `components.schemas`. */
5
6
  declare const COMPONENTS_SCHEMAS_PREFIX = "#/components/schemas/";
@@ -7,6 +8,13 @@ declare const COMPONENTS_SCHEMAS_PREFIX = "#/components/schemas/";
7
8
  declare const ZOD_NEST_ERROR_EXTENSION = "x-zod-nest-error";
8
9
  /** Value of `x-zod-nest-error` when a registry id is claimed by more than one schema. */
9
10
  declare const ZOD_NEST_ERROR_DUPLICATE_ID = "duplicate-id";
11
+ /**
12
+ * OpenAPI extension key used by `createZodDto` to mark a class for Phase 2e's
13
+ * doc-merger. The marker carries `{ __zodNestDto: true, dtoId, io }` so the
14
+ * merger can locate every zod-nest DTO in the @nestjs/swagger document and
15
+ * inject the real Zod-derived schema.
16
+ */
17
+ declare const ZOD_NEST_DTO_EXTENSION = "x-zod-nest-dto";
10
18
 
11
19
  type SchemaObject = JSONSchema.BaseSchema;
12
20
 
@@ -24,6 +32,13 @@ interface ZodNestRegistry {
24
32
  getCollisions(): ReadonlyMap<string, ReadonlySet<z.ZodType>>;
25
33
  }
26
34
  declare const createRegistry: () => ZodNestRegistry;
35
+ /**
36
+ * Process-wide default registry. `createZodDto` registers schemas here unless
37
+ * the caller passes `options.registry`. Phase 2e's doc merger reads from the
38
+ * same instance for bulk emission. Multi-app WeakMap isolation is deferred
39
+ * to v0.2.
40
+ */
41
+ declare const defaultRegistry: ZodNestRegistry;
27
42
 
28
43
  interface ToOpenApiOptions {
29
44
  io: 'input' | 'output';
@@ -46,4 +61,118 @@ declare class ZodNestUnrepresentableError extends ZodNestError {
46
61
  constructor(path: ReadonlyArray<string | number>, zodType: string);
47
62
  }
48
63
 
49
- export { COMPONENTS_SCHEMAS_PREFIX, type Override, type OverrideContext, type SchemaObject, type ToOpenApiOptions, type ToOpenApiResult, ZOD_NEST_ERROR_DUPLICATE_ID, ZOD_NEST_ERROR_EXTENSION, ZodNestError, type ZodNestRegistry, ZodNestUnrepresentableError, createRegistry, toOpenApi };
64
+ /**
65
+ * Runtime detection marker placed on every class returned by `createZodDto`.
66
+ * Used by the validation pipe (Phase 2c), serializer (2d), and doc merger (2e)
67
+ * to discriminate zod-nest DTO classes from regular constructors.
68
+ */
69
+ declare const ZOD_DTO_SYMBOL: unique symbol;
70
+
71
+ type Io = 'input' | 'output';
72
+ interface CreateZodDtoOptions {
73
+ /** Explicit id override. Highest precedence in id resolution. */
74
+ id?: string;
75
+ /** Registry to register this DTO's schema into. Defaults to `defaultRegistry`. */
76
+ registry?: ZodNestRegistry;
77
+ }
78
+ /**
79
+ * The class type returned by `createZodDto`. Instance type infers to the
80
+ * Zod output type so handler args typed as the DTO get the inferred shape.
81
+ */
82
+ interface ZodDto<TSchema extends z.ZodType = z.ZodType> {
83
+ new (): z.infer<TSchema>;
84
+ readonly schema: TSchema;
85
+ readonly id: string;
86
+ readonly io: Io;
87
+ readonly Output: ZodDto<TSchema>;
88
+ parse(input: unknown): z.infer<TSchema>;
89
+ safeParse(input: unknown): z.ZodSafeParseResult<z.infer<TSchema>>;
90
+ _OPENAPI_METADATA_FACTORY(): Record<string, unknown>;
91
+ readonly [ZOD_DTO_SYMBOL]: true;
92
+ }
93
+
94
+ declare const createZodDto: <TSchema extends z.ZodType>(schema: TSchema, options?: CreateZodDtoOptions) => ZodDto<TSchema>;
95
+
96
+ /**
97
+ * Payload of the `x-zod-nest-dto` placeholder property that
98
+ * `_OPENAPI_METADATA_FACTORY` returns. Phase 2e's doc merger reads this off
99
+ * each `components.schemas.<DtoName>.properties[x-zod-nest-dto]` entry,
100
+ * uses `dtoId` to look up the schema in the registry, and replaces the
101
+ * synthetic schema body with the real Zod-derived schema.
102
+ *
103
+ * `type` and `required` are benign filler that satisfy @nestjs/swagger's
104
+ * property-type guard (without them, the explorer throws "A circular
105
+ * dependency has been detected"). They have no semantic meaning and are
106
+ * stripped along with the rest of the marker by Phase 2e.
107
+ */
108
+ interface ZodDtoMarker {
109
+ readonly type: () => typeof Object;
110
+ readonly required: false;
111
+ readonly __zodNestDto: true;
112
+ readonly dtoId: string;
113
+ readonly io: Io;
114
+ }
115
+ declare const makeZodDtoMarker: (dtoId: string, io: Io) => ZodDtoMarker;
116
+ /** Phase 2e (and tests) use this to discriminate a marker from a real schema. */
117
+ declare const isZodDtoMarker: (value: unknown) => value is ZodDtoMarker;
118
+
119
+ /**
120
+ * Runtime guard: is `value` a class returned by `createZodDto`?
121
+ *
122
+ * Used by the validation pipe (Phase 2c), the serializer interceptor (2d),
123
+ * and the doc merger (2e) to discriminate zod-nest DTOs from plain
124
+ * constructors, class-validator DTOs, primitives, and any other metatypes
125
+ * NestJS exposes via `ArgumentMetadata`.
126
+ */
127
+ declare const isZodDto: (value: unknown) => value is ZodDto;
128
+
129
+ /**
130
+ * Default exception thrown by `ZodValidationPipe` when input fails to parse.
131
+ *
132
+ * Body shape (returned by `getResponse()`):
133
+ * ```
134
+ * {
135
+ * statusCode: 400,
136
+ * message: 'Validation failed',
137
+ * errors: z.treeifyError(zodError),
138
+ * }
139
+ * ```
140
+ *
141
+ * Carries `zodError` and `argMetadata` so custom exception filters can
142
+ * introspect the original validation failure.
143
+ */
144
+ declare class ZodValidationException extends BadRequestException {
145
+ readonly zodError: z.ZodError;
146
+ readonly argMetadata?: ArgumentMetadata;
147
+ constructor(zodError: z.ZodError, argMetadata?: ArgumentMetadata);
148
+ }
149
+
150
+ /**
151
+ * Build the exception thrown by `ZodValidationPipe` on validation failure.
152
+ * Receives Zod's error and the NestJS argument metadata; returns anything
153
+ * `throw`-able (typically a NestJS `HttpException` subclass).
154
+ */
155
+ type CreateValidationException = (zodError: z.ZodError, argMetadata: ArgumentMetadata) => unknown;
156
+ interface ZodValidationPipeOptions {
157
+ schema?: z.ZodType | ZodDto;
158
+ createValidationException?: CreateValidationException;
159
+ }
160
+ /**
161
+ * Constructor input for `ZodValidationPipe`. Discriminated at runtime:
162
+ * - `undefined` → metatype-driven (read DTO from handler arg's metatype)
163
+ * - a class with `[ZOD_DTO_SYMBOL]` → explicit DTO
164
+ * - a Zod schema (has `_zod` internals) → raw schema
165
+ * - anything else → options object
166
+ */
167
+ type ZodValidationPipeArg = z.ZodType | ZodDto | ZodValidationPipeOptions;
168
+
169
+ declare class ZodValidationPipe implements PipeTransform {
170
+ private readonly explicitSchema;
171
+ private readonly createValidationException;
172
+ constructor(arg?: ZodValidationPipeArg);
173
+ transform(value: unknown, metadata: ArgumentMetadata): Promise<unknown>;
174
+ private resolveSchema;
175
+ private static parseArg;
176
+ }
177
+
178
+ export { COMPONENTS_SCHEMAS_PREFIX, type CreateValidationException, type CreateZodDtoOptions, type Io, type Override, type OverrideContext, type SchemaObject, type ToOpenApiOptions, type ToOpenApiResult, ZOD_DTO_SYMBOL, ZOD_NEST_DTO_EXTENSION, ZOD_NEST_ERROR_DUPLICATE_ID, ZOD_NEST_ERROR_EXTENSION, type ZodDto, type ZodDtoMarker, ZodNestError, type ZodNestRegistry, ZodNestUnrepresentableError, ZodValidationException, ZodValidationPipe, type ZodValidationPipeArg, type ZodValidationPipeOptions, createRegistry, createZodDto, defaultRegistry, isZodDto, isZodDtoMarker, makeZodDtoMarker, toOpenApi };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { JSONSchema, $ZodTypes } from 'zod/v4/core';
3
+ import { BadRequestException, ArgumentMetadata, PipeTransform } from '@nestjs/common';
3
4
 
4
5
  /** OpenAPI 3.1 `$ref` prefix for entries in `components.schemas`. */
5
6
  declare const COMPONENTS_SCHEMAS_PREFIX = "#/components/schemas/";
@@ -7,6 +8,13 @@ declare const COMPONENTS_SCHEMAS_PREFIX = "#/components/schemas/";
7
8
  declare const ZOD_NEST_ERROR_EXTENSION = "x-zod-nest-error";
8
9
  /** Value of `x-zod-nest-error` when a registry id is claimed by more than one schema. */
9
10
  declare const ZOD_NEST_ERROR_DUPLICATE_ID = "duplicate-id";
11
+ /**
12
+ * OpenAPI extension key used by `createZodDto` to mark a class for Phase 2e's
13
+ * doc-merger. The marker carries `{ __zodNestDto: true, dtoId, io }` so the
14
+ * merger can locate every zod-nest DTO in the @nestjs/swagger document and
15
+ * inject the real Zod-derived schema.
16
+ */
17
+ declare const ZOD_NEST_DTO_EXTENSION = "x-zod-nest-dto";
10
18
 
11
19
  type SchemaObject = JSONSchema.BaseSchema;
12
20
 
@@ -24,6 +32,13 @@ interface ZodNestRegistry {
24
32
  getCollisions(): ReadonlyMap<string, ReadonlySet<z.ZodType>>;
25
33
  }
26
34
  declare const createRegistry: () => ZodNestRegistry;
35
+ /**
36
+ * Process-wide default registry. `createZodDto` registers schemas here unless
37
+ * the caller passes `options.registry`. Phase 2e's doc merger reads from the
38
+ * same instance for bulk emission. Multi-app WeakMap isolation is deferred
39
+ * to v0.2.
40
+ */
41
+ declare const defaultRegistry: ZodNestRegistry;
27
42
 
28
43
  interface ToOpenApiOptions {
29
44
  io: 'input' | 'output';
@@ -46,4 +61,118 @@ declare class ZodNestUnrepresentableError extends ZodNestError {
46
61
  constructor(path: ReadonlyArray<string | number>, zodType: string);
47
62
  }
48
63
 
49
- export { COMPONENTS_SCHEMAS_PREFIX, type Override, type OverrideContext, type SchemaObject, type ToOpenApiOptions, type ToOpenApiResult, ZOD_NEST_ERROR_DUPLICATE_ID, ZOD_NEST_ERROR_EXTENSION, ZodNestError, type ZodNestRegistry, ZodNestUnrepresentableError, createRegistry, toOpenApi };
64
+ /**
65
+ * Runtime detection marker placed on every class returned by `createZodDto`.
66
+ * Used by the validation pipe (Phase 2c), serializer (2d), and doc merger (2e)
67
+ * to discriminate zod-nest DTO classes from regular constructors.
68
+ */
69
+ declare const ZOD_DTO_SYMBOL: unique symbol;
70
+
71
+ type Io = 'input' | 'output';
72
+ interface CreateZodDtoOptions {
73
+ /** Explicit id override. Highest precedence in id resolution. */
74
+ id?: string;
75
+ /** Registry to register this DTO's schema into. Defaults to `defaultRegistry`. */
76
+ registry?: ZodNestRegistry;
77
+ }
78
+ /**
79
+ * The class type returned by `createZodDto`. Instance type infers to the
80
+ * Zod output type so handler args typed as the DTO get the inferred shape.
81
+ */
82
+ interface ZodDto<TSchema extends z.ZodType = z.ZodType> {
83
+ new (): z.infer<TSchema>;
84
+ readonly schema: TSchema;
85
+ readonly id: string;
86
+ readonly io: Io;
87
+ readonly Output: ZodDto<TSchema>;
88
+ parse(input: unknown): z.infer<TSchema>;
89
+ safeParse(input: unknown): z.ZodSafeParseResult<z.infer<TSchema>>;
90
+ _OPENAPI_METADATA_FACTORY(): Record<string, unknown>;
91
+ readonly [ZOD_DTO_SYMBOL]: true;
92
+ }
93
+
94
+ declare const createZodDto: <TSchema extends z.ZodType>(schema: TSchema, options?: CreateZodDtoOptions) => ZodDto<TSchema>;
95
+
96
+ /**
97
+ * Payload of the `x-zod-nest-dto` placeholder property that
98
+ * `_OPENAPI_METADATA_FACTORY` returns. Phase 2e's doc merger reads this off
99
+ * each `components.schemas.<DtoName>.properties[x-zod-nest-dto]` entry,
100
+ * uses `dtoId` to look up the schema in the registry, and replaces the
101
+ * synthetic schema body with the real Zod-derived schema.
102
+ *
103
+ * `type` and `required` are benign filler that satisfy @nestjs/swagger's
104
+ * property-type guard (without them, the explorer throws "A circular
105
+ * dependency has been detected"). They have no semantic meaning and are
106
+ * stripped along with the rest of the marker by Phase 2e.
107
+ */
108
+ interface ZodDtoMarker {
109
+ readonly type: () => typeof Object;
110
+ readonly required: false;
111
+ readonly __zodNestDto: true;
112
+ readonly dtoId: string;
113
+ readonly io: Io;
114
+ }
115
+ declare const makeZodDtoMarker: (dtoId: string, io: Io) => ZodDtoMarker;
116
+ /** Phase 2e (and tests) use this to discriminate a marker from a real schema. */
117
+ declare const isZodDtoMarker: (value: unknown) => value is ZodDtoMarker;
118
+
119
+ /**
120
+ * Runtime guard: is `value` a class returned by `createZodDto`?
121
+ *
122
+ * Used by the validation pipe (Phase 2c), the serializer interceptor (2d),
123
+ * and the doc merger (2e) to discriminate zod-nest DTOs from plain
124
+ * constructors, class-validator DTOs, primitives, and any other metatypes
125
+ * NestJS exposes via `ArgumentMetadata`.
126
+ */
127
+ declare const isZodDto: (value: unknown) => value is ZodDto;
128
+
129
+ /**
130
+ * Default exception thrown by `ZodValidationPipe` when input fails to parse.
131
+ *
132
+ * Body shape (returned by `getResponse()`):
133
+ * ```
134
+ * {
135
+ * statusCode: 400,
136
+ * message: 'Validation failed',
137
+ * errors: z.treeifyError(zodError),
138
+ * }
139
+ * ```
140
+ *
141
+ * Carries `zodError` and `argMetadata` so custom exception filters can
142
+ * introspect the original validation failure.
143
+ */
144
+ declare class ZodValidationException extends BadRequestException {
145
+ readonly zodError: z.ZodError;
146
+ readonly argMetadata?: ArgumentMetadata;
147
+ constructor(zodError: z.ZodError, argMetadata?: ArgumentMetadata);
148
+ }
149
+
150
+ /**
151
+ * Build the exception thrown by `ZodValidationPipe` on validation failure.
152
+ * Receives Zod's error and the NestJS argument metadata; returns anything
153
+ * `throw`-able (typically a NestJS `HttpException` subclass).
154
+ */
155
+ type CreateValidationException = (zodError: z.ZodError, argMetadata: ArgumentMetadata) => unknown;
156
+ interface ZodValidationPipeOptions {
157
+ schema?: z.ZodType | ZodDto;
158
+ createValidationException?: CreateValidationException;
159
+ }
160
+ /**
161
+ * Constructor input for `ZodValidationPipe`. Discriminated at runtime:
162
+ * - `undefined` → metatype-driven (read DTO from handler arg's metatype)
163
+ * - a class with `[ZOD_DTO_SYMBOL]` → explicit DTO
164
+ * - a Zod schema (has `_zod` internals) → raw schema
165
+ * - anything else → options object
166
+ */
167
+ type ZodValidationPipeArg = z.ZodType | ZodDto | ZodValidationPipeOptions;
168
+
169
+ declare class ZodValidationPipe implements PipeTransform {
170
+ private readonly explicitSchema;
171
+ private readonly createValidationException;
172
+ constructor(arg?: ZodValidationPipeArg);
173
+ transform(value: unknown, metadata: ArgumentMetadata): Promise<unknown>;
174
+ private resolveSchema;
175
+ private static parseArg;
176
+ }
177
+
178
+ export { COMPONENTS_SCHEMAS_PREFIX, type CreateValidationException, type CreateZodDtoOptions, type Io, type Override, type OverrideContext, type SchemaObject, type ToOpenApiOptions, type ToOpenApiResult, ZOD_DTO_SYMBOL, ZOD_NEST_DTO_EXTENSION, ZOD_NEST_ERROR_DUPLICATE_ID, ZOD_NEST_ERROR_EXTENSION, type ZodDto, type ZodDtoMarker, ZodNestError, type ZodNestRegistry, ZodNestUnrepresentableError, ZodValidationException, ZodValidationPipe, type ZodValidationPipeArg, type ZodValidationPipeOptions, createRegistry, createZodDto, defaultRegistry, isZodDto, isZodDtoMarker, makeZodDtoMarker, toOpenApi };
package/dist/index.js CHANGED
@@ -1,11 +1,23 @@
1
1
  'use strict';
2
2
 
3
3
  var zod = require('zod');
4
+ var common = require('@nestjs/common');
5
+
6
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
+ var __decorateClass = (decorators, target, key, kind) => {
8
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
9
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
10
+ if (decorator = decorators[i])
11
+ result = (decorator(result)) || result;
12
+ return result;
13
+ };
14
+ var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
4
15
 
5
16
  // src/schema/constants.ts
6
17
  var COMPONENTS_SCHEMAS_PREFIX = "#/components/schemas/";
7
18
  var ZOD_NEST_ERROR_EXTENSION = "x-zod-nest-error";
8
19
  var ZOD_NEST_ERROR_DUPLICATE_ID = "duplicate-id";
20
+ var ZOD_NEST_DTO_EXTENSION = "x-zod-nest-dto";
9
21
 
10
22
  // src/schema/errors.ts
11
23
  var ZodNestError = class extends Error {
@@ -192,13 +204,207 @@ var createRegistry = () => {
192
204
  }
193
205
  };
194
206
  };
207
+ var defaultRegistry = createRegistry();
208
+
209
+ // src/dto/marker.ts
210
+ var makeZodDtoMarker = (dtoId, io) => ({
211
+ type: () => Object,
212
+ required: false,
213
+ __zodNestDto: true,
214
+ dtoId,
215
+ io
216
+ });
217
+ var isZodDtoMarker = (value) => {
218
+ if (value === null || typeof value !== "object") {
219
+ return false;
220
+ }
221
+ return value.__zodNestDto === true;
222
+ };
223
+
224
+ // src/dto/symbols.ts
225
+ var ZOD_DTO_SYMBOL = /* @__PURE__ */ Symbol.for("zod-nest.dto");
226
+
227
+ // src/dto/output-dto.ts
228
+ var outputCache = /* @__PURE__ */ new WeakMap();
229
+ var buildSiblingClass = (parent, schema) => {
230
+ const SiblingClass = class {
231
+ static schema = schema;
232
+ static io = "output";
233
+ static [ZOD_DTO_SYMBOL] = true;
234
+ static get id() {
235
+ return parent.id;
236
+ }
237
+ static get Output() {
238
+ return this;
239
+ }
240
+ static parse(input) {
241
+ return schema.parse(input);
242
+ }
243
+ static safeParse(input) {
244
+ return schema.safeParse(input);
245
+ }
246
+ static _OPENAPI_METADATA_FACTORY() {
247
+ return { [ZOD_NEST_DTO_EXTENSION]: makeZodDtoMarker(parent.id, "output") };
248
+ }
249
+ };
250
+ return SiblingClass;
251
+ };
252
+ var resolveOutput = (parent, schema) => {
253
+ const cached = outputCache.get(parent);
254
+ if (cached !== void 0) {
255
+ return cached;
256
+ }
257
+ const sibling = buildSiblingClass(parent, schema);
258
+ outputCache.set(parent, sibling);
259
+ return sibling;
260
+ };
261
+
262
+ // src/dto/create-zod-dto.ts
263
+ var anonCounter = 0;
264
+ var warnedOnAnonymous = false;
265
+ var resolveId = (registry, schema, providedId, className) => {
266
+ if (providedId !== void 0 && providedId !== "") {
267
+ return providedId;
268
+ }
269
+ const meta = registry.zodRegistry.get(schema);
270
+ if (meta && typeof meta.id === "string" && meta.id !== "") {
271
+ return meta.id;
272
+ }
273
+ if (className !== "" && className.length > 1) {
274
+ return className;
275
+ }
276
+ anonCounter += 1;
277
+ const fallback = `_AnonZodDto_${anonCounter}`;
278
+ if (!warnedOnAnonymous) {
279
+ warnedOnAnonymous = true;
280
+ console.warn(
281
+ `[zod-nest] Could not resolve a DTO id from class name (got "${className}"). Using "${fallback}". Pass \`createZodDto(schema, { id: 'Foo' })\` to set a stable name \u2014 important under minification, where class names become single mangled characters.`
282
+ );
283
+ }
284
+ return fallback;
285
+ };
286
+ var createZodDto = (schema, options) => {
287
+ const registry = options?.registry ?? defaultRegistry;
288
+ const io = "input";
289
+ let cachedId;
290
+ const ensureRegistered = (className) => {
291
+ if (cachedId !== void 0) {
292
+ return cachedId;
293
+ }
294
+ cachedId = resolveId(registry, schema, options?.id, className);
295
+ registry.register(schema, cachedId);
296
+ return cachedId;
297
+ };
298
+ const ZodDtoBase = class {
299
+ static schema = schema;
300
+ static io = io;
301
+ static [ZOD_DTO_SYMBOL] = true;
302
+ static get id() {
303
+ return ensureRegistered(this.name);
304
+ }
305
+ static get Output() {
306
+ return resolveOutput(this, schema);
307
+ }
308
+ static parse(input) {
309
+ return schema.parse(input);
310
+ }
311
+ static safeParse(input) {
312
+ return schema.safeParse(input);
313
+ }
314
+ static _OPENAPI_METADATA_FACTORY() {
315
+ return { [ZOD_NEST_DTO_EXTENSION]: makeZodDtoMarker(ensureRegistered(this.name), io) };
316
+ }
317
+ };
318
+ return ZodDtoBase;
319
+ };
320
+
321
+ // src/dto/predicates.ts
322
+ var isZodDto = (value) => typeof value === "function" && value[ZOD_DTO_SYMBOL] === true;
323
+ var ZodValidationException = class extends common.BadRequestException {
324
+ zodError;
325
+ argMetadata;
326
+ constructor(zodError, argMetadata) {
327
+ super({
328
+ statusCode: common.HttpStatus.BAD_REQUEST,
329
+ message: "Validation failed",
330
+ errors: zod.z.treeifyError(zodError)
331
+ });
332
+ this.zodError = zodError;
333
+ this.argMetadata = argMetadata;
334
+ }
335
+ };
336
+ var isZodSchema = (value) => value !== null && typeof value === "object" && "_zod" in value;
337
+ var isOptionsObject = (value) => value !== null && typeof value === "object" && !isZodSchema(value);
338
+ var defaultExceptionFactory = (zodError, argMetadata) => new ZodValidationException(zodError, argMetadata);
339
+ exports.ZodValidationPipe = class ZodValidationPipe {
340
+ explicitSchema;
341
+ createValidationException;
342
+ constructor(arg) {
343
+ const { schema, factory } = exports.ZodValidationPipe.parseArg(arg);
344
+ this.explicitSchema = schema;
345
+ this.createValidationException = factory;
346
+ }
347
+ async transform(value, metadata) {
348
+ const schema = this.resolveSchema(metadata);
349
+ if (schema === void 0) {
350
+ return value;
351
+ }
352
+ const result = await schema.safeParseAsync(value);
353
+ if (result.success) {
354
+ return result.data;
355
+ }
356
+ throw this.createValidationException(result.error, metadata);
357
+ }
358
+ resolveSchema(metadata) {
359
+ if (this.explicitSchema !== void 0) {
360
+ return this.explicitSchema;
361
+ }
362
+ const metatype = metadata.metatype;
363
+ if (!isZodDto(metatype)) {
364
+ return void 0;
365
+ }
366
+ return metatype.schema;
367
+ }
368
+ static parseArg(arg) {
369
+ if (arg === void 0) {
370
+ return { schema: void 0, factory: defaultExceptionFactory };
371
+ }
372
+ if (isZodDto(arg)) {
373
+ return { schema: arg.schema, factory: defaultExceptionFactory };
374
+ }
375
+ if (isZodSchema(arg)) {
376
+ return { schema: arg, factory: defaultExceptionFactory };
377
+ }
378
+ if (!isOptionsObject(arg)) {
379
+ return { schema: void 0, factory: defaultExceptionFactory };
380
+ }
381
+ const optionSchema = arg.schema;
382
+ const resolvedSchema = isZodDto(optionSchema) ? optionSchema.schema : optionSchema;
383
+ return {
384
+ schema: resolvedSchema,
385
+ factory: arg.createValidationException ?? defaultExceptionFactory
386
+ };
387
+ }
388
+ };
389
+ exports.ZodValidationPipe = __decorateClass([
390
+ common.Injectable(),
391
+ __decorateParam(0, common.Optional())
392
+ ], exports.ZodValidationPipe);
195
393
 
196
394
  exports.COMPONENTS_SCHEMAS_PREFIX = COMPONENTS_SCHEMAS_PREFIX;
395
+ exports.ZOD_DTO_SYMBOL = ZOD_DTO_SYMBOL;
396
+ exports.ZOD_NEST_DTO_EXTENSION = ZOD_NEST_DTO_EXTENSION;
197
397
  exports.ZOD_NEST_ERROR_DUPLICATE_ID = ZOD_NEST_ERROR_DUPLICATE_ID;
198
398
  exports.ZOD_NEST_ERROR_EXTENSION = ZOD_NEST_ERROR_EXTENSION;
199
399
  exports.ZodNestError = ZodNestError;
200
400
  exports.ZodNestUnrepresentableError = ZodNestUnrepresentableError;
401
+ exports.ZodValidationException = ZodValidationException;
201
402
  exports.createRegistry = createRegistry;
403
+ exports.createZodDto = createZodDto;
404
+ exports.defaultRegistry = defaultRegistry;
405
+ exports.isZodDto = isZodDto;
406
+ exports.isZodDtoMarker = isZodDtoMarker;
407
+ exports.makeZodDtoMarker = makeZodDtoMarker;
202
408
  exports.toOpenApi = toOpenApi;
203
409
  //# sourceMappingURL=index.js.map
204
410
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/schema/constants.ts","../src/schema/errors.ts","../src/schema/override.ts","../src/schema/post-process.ts","../src/schema/engine.ts","../src/schema/registry.ts"],"names":["z"],"mappings":";;;;;AACO,IAAM,yBAAA,GAA4B;AAGlC,IAAM,wBAAA,GAA2B;AAGjC,IAAM,2BAAA,GAA8B;;;ACPpC,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA,EACtC,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,cAAA;AAAA,EACd;AACF;AAEO,IAAM,2BAAA,GAAN,cAA0C,YAAA,CAAa;AAAA,EACnD,IAAA;AAAA,EACA,OAAA;AAAA,EAET,WAAA,CAAY,MAAsC,OAAA,EAAiB;AACjE,IAAA,KAAA;AAAA,MACE,CAAA,6BAAA,EAAgC,OAAO,CAAA,MAAA,EAAS,UAAA,CAAW,IAAI,CAAC,CAAA,0IAAA;AAAA,KAGlE;AACA,IAA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;AAAA,EACH;AAEA,EAAA,OAAO,MAAA;AACT;AC/DO,IAAM,iBAAiB,MAAuB;AACnD,EAAA,MAAM,IAAA,uBAAW,GAAA,EAA4B;AAE7C,EAAA,OAAO;AAAA,IACL,aAAaA,KAAAA,CAAE,cAAA;AAAA,IACf,QAAA,EAAU,CAAC,MAAA,EAAQ,EAAA,KAAO;AACxB,MAAAA,MAAE,cAAA,CAAe,GAAA,CAAI,MAAA,EAAQ,EAAE,IAAI,CAAA;AACnC,MAAA,IAAI,GAAA,GAAM,IAAA,CAAK,GAAA,CAAI,EAAE,CAAA;AACrB,MAAA,IAAI,QAAQ,MAAA,EAAW;AACrB,QAAA,GAAA,uBAAU,GAAA,EAAe;AACzB,QAAA,IAAA,CAAK,GAAA,CAAI,IAAI,GAAG,CAAA;AAAA,MAClB;AACA,MAAA,GAAA,CAAI,IAAI,MAAM,CAAA;AAAA,IAChB,CAAA;AAAA,IACA,YAAA,EAAc,CAAC,EAAA,KAAO;AACpB,MAAA,MAAM,GAAA,GAAM,IAAA,CAAK,GAAA,CAAI,EAAE,CAAA;AACvB,MAAA,OAAO,GAAA,KAAQ,MAAA,IAAa,GAAA,CAAI,IAAA,GAAO,CAAA;AAAA,IACzC,CAAA;AAAA,IACA,eAAe,MAAM;AACnB,MAAA,MAAM,GAAA,uBAAU,GAAA,EAA4B;AAC5C,MAAA,KAAA,MAAW,CAAC,EAAA,EAAI,GAAG,CAAA,IAAK,IAAA,EAAM;AAC5B,QAAA,IAAI,GAAA,CAAI,QAAQ,CAAA,EAAG;AACjB,UAAA;AAAA,QACF;AACA,QAAA,GAAA,CAAI,GAAA,CAAI,IAAI,GAAG,CAAA;AAAA,MACjB;AACA,MAAA,OAAO,GAAA;AAAA,IACT;AAAA,GACF;AACF","file":"index.js","sourcesContent":["/** OpenAPI 3.1 `$ref` prefix for entries in `components.schemas`. */\nexport const COMPONENTS_SCHEMAS_PREFIX = '#/components/schemas/';\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","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\nexport const builtInOverride: 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\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\nexport const isStrictlyUnrepresentable = (\n jsonSchema: SchemaObject,\n zodSchema: $ZodTypes,\n): 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 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 if (list.length === 0) {\n return () => undefined;\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 } from './constants.js';\n\nexport interface PostProcessResult {\n schema: SchemaObject;\n refs: Map<string, SchemaObject>;\n}\n\nconst DEFS_PREFIX = '#/$defs/';\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 { SchemaObject } from './openapi.types.js';\nimport type { Override } from './override.js';\nimport type { ZodNestRegistry } from './registry.js';\n\nimport { ZOD_NEST_ERROR_DUPLICATE_ID, ZOD_NEST_ERROR_EXTENSION } from './constants.js';\nimport { ZodNestUnrepresentableError } from './errors.js';\nimport { builtInOverride, combine, isStrictlyUnrepresentable } from './override.js';\nimport { postProcess } from './post-process.js';\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\nexport const toOpenApi = (schema: z.ZodType, opts: ToOpenApiOptions): ToOpenApiResult => {\n const strict = opts.strict ?? true;\n const merged = combine(builtInOverride, opts.override);\n const unrepresentableHits: UnrepresentableHit[] = [];\n\n const wrapped: Override = (ctx) => {\n merged(ctx);\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 });\n };\n\n const raw = z.toJSONSchema(schema, {\n target: 'draft-2020-12',\n io: opts.io,\n unrepresentable: 'any',\n metadata: opts.registry.zodRegistry,\n override: wrapped,\n cycles: 'ref',\n reused: 'inline',\n });\n\n const firstHit = unrepresentableHits[0];\n if (firstHit !== undefined) {\n throw new ZodNestUnrepresentableError(firstHit.path, firstHit.zodType);\n }\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 { z } from 'zod';\n\nexport interface ZodNestRegistry {\n readonly zodRegistry: typeof z.globalRegistry;\n register(schema: z.ZodType, id: string): void;\n hasCollision(id: string): boolean;\n getCollisions(): ReadonlyMap<string, ReadonlySet<z.ZodType>>;\n}\n\nexport const createRegistry = (): ZodNestRegistry => {\n const seen = new Map<string, Set<z.ZodType>>();\n\n return {\n zodRegistry: z.globalRegistry,\n register: (schema, id) => {\n z.globalRegistry.add(schema, { id });\n let set = seen.get(id);\n if (set === undefined) {\n set = new Set<z.ZodType>();\n seen.set(id, set);\n }\n set.add(schema);\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 };\n};\n"]}
1
+ {"version":3,"sources":["../src/schema/constants.ts","../src/schema/errors.ts","../src/schema/override.ts","../src/schema/post-process.ts","../src/schema/engine.ts","../src/schema/registry.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/validation.exception.ts","../src/pipes/validation.pipe.ts"],"names":["z","BadRequestException","HttpStatus","ZodValidationPipe","Injectable","Optional"],"mappings":";;;;;;;;;;;;;;;;AACO,IAAM,yBAAA,GAA4B;AAGlC,IAAM,wBAAA,GAA2B;AAGjC,IAAM,2BAAA,GAA8B;AAQpC,IAAM,sBAAA,GAAyB;;;ACf/B,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA,EACtC,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,cAAA;AAAA,EACd;AACF;AAEO,IAAM,2BAAA,GAAN,cAA0C,YAAA,CAAa;AAAA,EACnD,IAAA;AAAA,EACA,OAAA;AAAA,EAET,WAAA,CAAY,MAAsC,OAAA,EAAiB;AACjE,IAAA,KAAA;AAAA,MACE,CAAA,6BAAA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,cAAA,GAAiB,QAAA,CAAS,YAAY,CAAA,GAAI,aAAa,MAAA,GAAS,YAAA;AACtE,IAAA,OAAO;AAAA,MACL,MAAA,EAAQ,cAAA;AAAA,MACR,OAAA,EAAS,IAAI,yBAAA,IAA6B;AAAA,KAC5C;AAAA,EACF;AACF;AAxDaA,yBAAA,GAAN,eAAA,CAAA;AAAA,EADNC,iBAAA,EAAW;AAAA,EAKG,eAAA,CAAA,CAAA,EAAAC,eAAA,EAAS;AAAA,CAAA,EAJXF,yBAAA,CAAA","file":"index.js","sourcesContent":["/** OpenAPI 3.1 `$ref` prefix for entries in `components.schemas`. */\nexport const COMPONENTS_SCHEMAS_PREFIX = '#/components/schemas/';\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 Phase 2e's\n * doc-merger. The marker carries `{ __zodNestDto: true, dtoId, io }` so the\n * merger can locate every zod-nest DTO in the @nestjs/swagger document and\n * inject the real Zod-derived schema.\n */\nexport const ZOD_NEST_DTO_EXTENSION = 'x-zod-nest-dto';\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\nexport const builtInOverride: 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\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\nexport const isStrictlyUnrepresentable = (\n jsonSchema: SchemaObject,\n zodSchema: $ZodTypes,\n): 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 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 if (list.length === 0) {\n return () => undefined;\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 } from './constants.js';\n\nexport interface PostProcessResult {\n schema: SchemaObject;\n refs: Map<string, SchemaObject>;\n}\n\nconst DEFS_PREFIX = '#/$defs/';\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 { SchemaObject } from './openapi.types.js';\nimport type { Override } from './override.js';\nimport type { ZodNestRegistry } from './registry.js';\n\nimport { ZOD_NEST_ERROR_DUPLICATE_ID, ZOD_NEST_ERROR_EXTENSION } from './constants.js';\nimport { ZodNestUnrepresentableError } from './errors.js';\nimport { builtInOverride, combine, isStrictlyUnrepresentable } from './override.js';\nimport { postProcess } from './post-process.js';\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\nexport const toOpenApi = (schema: z.ZodType, opts: ToOpenApiOptions): ToOpenApiResult => {\n const strict = opts.strict ?? true;\n const merged = combine(builtInOverride, opts.override);\n const unrepresentableHits: UnrepresentableHit[] = [];\n\n const wrapped: Override = (ctx) => {\n merged(ctx);\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 });\n };\n\n const raw = z.toJSONSchema(schema, {\n target: 'draft-2020-12',\n io: opts.io,\n unrepresentable: 'any',\n metadata: opts.registry.zodRegistry,\n override: wrapped,\n cycles: 'ref',\n reused: 'inline',\n });\n\n const firstHit = unrepresentableHits[0];\n if (firstHit !== undefined) {\n throw new ZodNestUnrepresentableError(firstHit.path, firstHit.zodType);\n }\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 { z } from 'zod';\n\nexport interface ZodNestRegistry {\n readonly zodRegistry: typeof z.globalRegistry;\n register(schema: z.ZodType, id: string): void;\n hasCollision(id: string): boolean;\n getCollisions(): ReadonlyMap<string, ReadonlySet<z.ZodType>>;\n}\n\nexport const createRegistry = (): ZodNestRegistry => {\n const seen = new Map<string, Set<z.ZodType>>();\n\n return {\n zodRegistry: z.globalRegistry,\n register: (schema, id) => {\n z.globalRegistry.add(schema, { id });\n let set = seen.get(id);\n if (set === undefined) {\n set = new Set<z.ZodType>();\n seen.set(id, set);\n }\n set.add(schema);\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 };\n};\n\n/**\n * Process-wide default registry. `createZodDto` registers schemas here unless\n * the caller passes `options.registry`. Phase 2e's doc merger reads from the\n * same instance for bulk emission. Multi-app WeakMap isolation is deferred\n * to v0.2.\n */\nexport const defaultRegistry: ZodNestRegistry = createRegistry();\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. Phase 2e's doc merger 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 Phase 2e.\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\n/** Phase 2e (and tests) use this to discriminate a marker from a real schema. */\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","/**\n * Runtime detection marker placed on every class returned by `createZodDto`.\n * Used by the validation pipe (Phase 2c), serializer (2d), and doc merger (2e)\n * to discriminate zod-nest DTO classes from regular constructors.\n */\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 * the Phase 2e doc-merger 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 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 } 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 resolveId = (\n registry: ZodNestRegistry,\n schema: z.ZodType,\n providedId: string | undefined,\n className: string,\n): string => {\n if (providedId !== undefined && providedId !== '') {\n return providedId;\n }\n const meta = registry.zodRegistry.get(schema) as { id?: string } | undefined;\n if (meta && typeof meta.id === 'string' && meta.id !== '') {\n return meta.id;\n }\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}\". Pass \\`createZodDto(schema, { id: 'Foo' })\\` to set a stable ` +\n `name — important under 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 cachedId = resolveId(registry, schema, options?.id, className);\n registry.register(schema, cachedId);\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 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 the validation pipe (Phase 2c), the serializer interceptor (2d),\n * and the doc merger (2e) 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","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 statusCode: HttpStatus.BAD_REQUEST,\n message: 'Validation failed',\n errors: z.treeifyError(zodError),\n });\n this.zodError = zodError;\n this.argMetadata = argMetadata;\n }\n}\n","import { Injectable, Optional } from '@nestjs/common';\n\nimport type { ArgumentMetadata, PipeTransform } from '@nestjs/common';\nimport type { z } from 'zod';\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';\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\n@Injectable()\nexport class ZodValidationPipe implements PipeTransform {\n private readonly explicitSchema: z.ZodType | undefined;\n private readonly createValidationException: CreateValidationException;\n\n constructor(@Optional() arg?: ZodValidationPipeArg) {\n const { schema, factory } = ZodValidationPipe.parseArg(arg);\n this.explicitSchema = schema;\n this.createValidationException = factory;\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 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 static parseArg(arg: ZodValidationPipeArg | undefined): {\n schema: z.ZodType | undefined;\n factory: CreateValidationException;\n } {\n if (arg === undefined) {\n return { schema: undefined, factory: defaultExceptionFactory };\n }\n if (isZodDto(arg)) {\n return { schema: arg.schema, factory: defaultExceptionFactory };\n }\n if (isZodSchema(arg)) {\n return { schema: arg, factory: defaultExceptionFactory };\n }\n if (!isOptionsObject(arg)) {\n return { schema: undefined, factory: defaultExceptionFactory };\n }\n const optionSchema = arg.schema;\n const resolvedSchema = isZodDto(optionSchema) ? optionSchema.schema : optionSchema;\n return {\n schema: resolvedSchema,\n factory: arg.createValidationException ?? defaultExceptionFactory,\n };\n }\n}\n"]}
package/dist/index.mjs CHANGED
@@ -1,9 +1,21 @@
1
1
  import { z } from 'zod';
2
+ import { Injectable, Optional, BadRequestException, HttpStatus } from '@nestjs/common';
3
+
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __decorateClass = (decorators, target, key, kind) => {
6
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
7
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
8
+ if (decorator = decorators[i])
9
+ result = (decorator(result)) || result;
10
+ return result;
11
+ };
12
+ var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
2
13
 
3
14
  // src/schema/constants.ts
4
15
  var COMPONENTS_SCHEMAS_PREFIX = "#/components/schemas/";
5
16
  var ZOD_NEST_ERROR_EXTENSION = "x-zod-nest-error";
6
17
  var ZOD_NEST_ERROR_DUPLICATE_ID = "duplicate-id";
18
+ var ZOD_NEST_DTO_EXTENSION = "x-zod-nest-dto";
7
19
 
8
20
  // src/schema/errors.ts
9
21
  var ZodNestError = class extends Error {
@@ -190,7 +202,193 @@ var createRegistry = () => {
190
202
  }
191
203
  };
192
204
  };
205
+ var defaultRegistry = createRegistry();
206
+
207
+ // src/dto/marker.ts
208
+ var makeZodDtoMarker = (dtoId, io) => ({
209
+ type: () => Object,
210
+ required: false,
211
+ __zodNestDto: true,
212
+ dtoId,
213
+ io
214
+ });
215
+ var isZodDtoMarker = (value) => {
216
+ if (value === null || typeof value !== "object") {
217
+ return false;
218
+ }
219
+ return value.__zodNestDto === true;
220
+ };
221
+
222
+ // src/dto/symbols.ts
223
+ var ZOD_DTO_SYMBOL = /* @__PURE__ */ Symbol.for("zod-nest.dto");
224
+
225
+ // src/dto/output-dto.ts
226
+ var outputCache = /* @__PURE__ */ new WeakMap();
227
+ var buildSiblingClass = (parent, schema) => {
228
+ const SiblingClass = class {
229
+ static schema = schema;
230
+ static io = "output";
231
+ static [ZOD_DTO_SYMBOL] = true;
232
+ static get id() {
233
+ return parent.id;
234
+ }
235
+ static get Output() {
236
+ return this;
237
+ }
238
+ static parse(input) {
239
+ return schema.parse(input);
240
+ }
241
+ static safeParse(input) {
242
+ return schema.safeParse(input);
243
+ }
244
+ static _OPENAPI_METADATA_FACTORY() {
245
+ return { [ZOD_NEST_DTO_EXTENSION]: makeZodDtoMarker(parent.id, "output") };
246
+ }
247
+ };
248
+ return SiblingClass;
249
+ };
250
+ var resolveOutput = (parent, schema) => {
251
+ const cached = outputCache.get(parent);
252
+ if (cached !== void 0) {
253
+ return cached;
254
+ }
255
+ const sibling = buildSiblingClass(parent, schema);
256
+ outputCache.set(parent, sibling);
257
+ return sibling;
258
+ };
259
+
260
+ // src/dto/create-zod-dto.ts
261
+ var anonCounter = 0;
262
+ var warnedOnAnonymous = false;
263
+ var resolveId = (registry, schema, providedId, className) => {
264
+ if (providedId !== void 0 && providedId !== "") {
265
+ return providedId;
266
+ }
267
+ const meta = registry.zodRegistry.get(schema);
268
+ if (meta && typeof meta.id === "string" && meta.id !== "") {
269
+ return meta.id;
270
+ }
271
+ if (className !== "" && className.length > 1) {
272
+ return className;
273
+ }
274
+ anonCounter += 1;
275
+ const fallback = `_AnonZodDto_${anonCounter}`;
276
+ if (!warnedOnAnonymous) {
277
+ warnedOnAnonymous = true;
278
+ console.warn(
279
+ `[zod-nest] Could not resolve a DTO id from class name (got "${className}"). Using "${fallback}". Pass \`createZodDto(schema, { id: 'Foo' })\` to set a stable name \u2014 important under minification, where class names become single mangled characters.`
280
+ );
281
+ }
282
+ return fallback;
283
+ };
284
+ var createZodDto = (schema, options) => {
285
+ const registry = options?.registry ?? defaultRegistry;
286
+ const io = "input";
287
+ let cachedId;
288
+ const ensureRegistered = (className) => {
289
+ if (cachedId !== void 0) {
290
+ return cachedId;
291
+ }
292
+ cachedId = resolveId(registry, schema, options?.id, className);
293
+ registry.register(schema, cachedId);
294
+ return cachedId;
295
+ };
296
+ const ZodDtoBase = class {
297
+ static schema = schema;
298
+ static io = io;
299
+ static [ZOD_DTO_SYMBOL] = true;
300
+ static get id() {
301
+ return ensureRegistered(this.name);
302
+ }
303
+ static get Output() {
304
+ return resolveOutput(this, schema);
305
+ }
306
+ static parse(input) {
307
+ return schema.parse(input);
308
+ }
309
+ static safeParse(input) {
310
+ return schema.safeParse(input);
311
+ }
312
+ static _OPENAPI_METADATA_FACTORY() {
313
+ return { [ZOD_NEST_DTO_EXTENSION]: makeZodDtoMarker(ensureRegistered(this.name), io) };
314
+ }
315
+ };
316
+ return ZodDtoBase;
317
+ };
318
+
319
+ // src/dto/predicates.ts
320
+ var isZodDto = (value) => typeof value === "function" && value[ZOD_DTO_SYMBOL] === true;
321
+ var ZodValidationException = class extends BadRequestException {
322
+ zodError;
323
+ argMetadata;
324
+ constructor(zodError, argMetadata) {
325
+ super({
326
+ statusCode: HttpStatus.BAD_REQUEST,
327
+ message: "Validation failed",
328
+ errors: z.treeifyError(zodError)
329
+ });
330
+ this.zodError = zodError;
331
+ this.argMetadata = argMetadata;
332
+ }
333
+ };
334
+ var isZodSchema = (value) => value !== null && typeof value === "object" && "_zod" in value;
335
+ var isOptionsObject = (value) => value !== null && typeof value === "object" && !isZodSchema(value);
336
+ var defaultExceptionFactory = (zodError, argMetadata) => new ZodValidationException(zodError, argMetadata);
337
+ var ZodValidationPipe = class {
338
+ explicitSchema;
339
+ createValidationException;
340
+ constructor(arg) {
341
+ const { schema, factory } = ZodValidationPipe.parseArg(arg);
342
+ this.explicitSchema = schema;
343
+ this.createValidationException = factory;
344
+ }
345
+ async transform(value, metadata) {
346
+ const schema = this.resolveSchema(metadata);
347
+ if (schema === void 0) {
348
+ return value;
349
+ }
350
+ const result = await schema.safeParseAsync(value);
351
+ if (result.success) {
352
+ return result.data;
353
+ }
354
+ throw this.createValidationException(result.error, metadata);
355
+ }
356
+ resolveSchema(metadata) {
357
+ if (this.explicitSchema !== void 0) {
358
+ return this.explicitSchema;
359
+ }
360
+ const metatype = metadata.metatype;
361
+ if (!isZodDto(metatype)) {
362
+ return void 0;
363
+ }
364
+ return metatype.schema;
365
+ }
366
+ static parseArg(arg) {
367
+ if (arg === void 0) {
368
+ return { schema: void 0, factory: defaultExceptionFactory };
369
+ }
370
+ if (isZodDto(arg)) {
371
+ return { schema: arg.schema, factory: defaultExceptionFactory };
372
+ }
373
+ if (isZodSchema(arg)) {
374
+ return { schema: arg, factory: defaultExceptionFactory };
375
+ }
376
+ if (!isOptionsObject(arg)) {
377
+ return { schema: void 0, factory: defaultExceptionFactory };
378
+ }
379
+ const optionSchema = arg.schema;
380
+ const resolvedSchema = isZodDto(optionSchema) ? optionSchema.schema : optionSchema;
381
+ return {
382
+ schema: resolvedSchema,
383
+ factory: arg.createValidationException ?? defaultExceptionFactory
384
+ };
385
+ }
386
+ };
387
+ ZodValidationPipe = __decorateClass([
388
+ Injectable(),
389
+ __decorateParam(0, Optional())
390
+ ], ZodValidationPipe);
193
391
 
194
- export { COMPONENTS_SCHEMAS_PREFIX, ZOD_NEST_ERROR_DUPLICATE_ID, ZOD_NEST_ERROR_EXTENSION, ZodNestError, ZodNestUnrepresentableError, createRegistry, toOpenApi };
392
+ export { COMPONENTS_SCHEMAS_PREFIX, ZOD_DTO_SYMBOL, ZOD_NEST_DTO_EXTENSION, ZOD_NEST_ERROR_DUPLICATE_ID, ZOD_NEST_ERROR_EXTENSION, ZodNestError, ZodNestUnrepresentableError, ZodValidationException, ZodValidationPipe, createRegistry, createZodDto, defaultRegistry, isZodDto, isZodDtoMarker, makeZodDtoMarker, toOpenApi };
195
393
  //# sourceMappingURL=index.mjs.map
196
394
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/schema/constants.ts","../src/schema/errors.ts","../src/schema/override.ts","../src/schema/post-process.ts","../src/schema/engine.ts","../src/schema/registry.ts"],"names":["z"],"mappings":";;;AACO,IAAM,yBAAA,GAA4B;AAGlC,IAAM,wBAAA,GAA2B;AAGjC,IAAM,2BAAA,GAA8B;;;ACPpC,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA,EACtC,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OA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QAAA,IAAI,GAAA,CAAI,QAAQ,CAAA,EAAG;AACjB,UAAA;AAAA,QACF;AACA,QAAA,GAAA,CAAI,GAAA,CAAI,IAAI,GAAG,CAAA;AAAA,MACjB;AACA,MAAA,OAAO,GAAA;AAAA,IACT;AAAA,GACF;AACF","file":"index.mjs","sourcesContent":["/** OpenAPI 3.1 `$ref` prefix for entries in `components.schemas`. */\nexport const COMPONENTS_SCHEMAS_PREFIX = '#/components/schemas/';\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","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\nexport const builtInOverride: 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\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\nexport const isStrictlyUnrepresentable = (\n jsonSchema: SchemaObject,\n zodSchema: $ZodTypes,\n): 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 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 if (list.length === 0) {\n return () => undefined;\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 } from './constants.js';\n\nexport interface PostProcessResult {\n schema: SchemaObject;\n refs: Map<string, SchemaObject>;\n}\n\nconst DEFS_PREFIX = '#/$defs/';\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 { SchemaObject } from './openapi.types.js';\nimport type { Override } from './override.js';\nimport type { ZodNestRegistry } from './registry.js';\n\nimport { ZOD_NEST_ERROR_DUPLICATE_ID, ZOD_NEST_ERROR_EXTENSION } from './constants.js';\nimport { ZodNestUnrepresentableError } from './errors.js';\nimport { builtInOverride, combine, isStrictlyUnrepresentable } from './override.js';\nimport { postProcess } from './post-process.js';\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\nexport const toOpenApi = (schema: z.ZodType, opts: ToOpenApiOptions): ToOpenApiResult => {\n const strict = opts.strict ?? true;\n const merged = combine(builtInOverride, opts.override);\n const unrepresentableHits: UnrepresentableHit[] = [];\n\n const wrapped: Override = (ctx) => {\n merged(ctx);\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 });\n };\n\n const raw = z.toJSONSchema(schema, {\n target: 'draft-2020-12',\n io: opts.io,\n unrepresentable: 'any',\n metadata: opts.registry.zodRegistry,\n override: wrapped,\n cycles: 'ref',\n reused: 'inline',\n });\n\n const firstHit = unrepresentableHits[0];\n if (firstHit !== undefined) {\n throw new ZodNestUnrepresentableError(firstHit.path, firstHit.zodType);\n }\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 { z } from 'zod';\n\nexport interface ZodNestRegistry {\n readonly zodRegistry: typeof z.globalRegistry;\n register(schema: z.ZodType, id: string): void;\n hasCollision(id: string): boolean;\n getCollisions(): ReadonlyMap<string, ReadonlySet<z.ZodType>>;\n}\n\nexport const createRegistry = (): ZodNestRegistry => {\n const seen = new Map<string, Set<z.ZodType>>();\n\n return {\n zodRegistry: z.globalRegistry,\n register: (schema, id) => {\n z.globalRegistry.add(schema, { id });\n let set = seen.get(id);\n if (set === undefined) {\n set = new Set<z.ZodType>();\n seen.set(id, set);\n }\n set.add(schema);\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 };\n};\n"]}
1
+ {"version":3,"sources":["../src/schema/constants.ts","../src/schema/errors.ts","../src/schema/override.ts","../src/schema/post-process.ts","../src/schema/engine.ts","../src/schema/registry.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/validation.exception.ts","../src/pipes/validation.pipe.ts"],"names":["z"],"mappings":";;;;;;;;;;;;;;AACO,IAAM,yBAAA,GAA4B;AAGlC,IAAM,wBAAA,GAA2B;AAGjC,IAAM,2BAAA,GAA8B;AAQpC,IAAM,sBAAA,GAAyB;;;ACf/B,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA,EAC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,EAAE,MAAA,EAAQ,GAAA,EAAK,OAAA,EAAS,uBAAA,EAAwB;AAAA,IACzD;AACA,IAAA,IAAI,CAAC,eAAA,CAAgB,GAAG,CAAA,EAAG;AACzB,MAAA,OAAO,EAAE,MAAA,EAAQ,MAAA,EAAW,OAAA,EAAS,uBAAA,EAAwB;AAAA,IAC/D;AACA,IAAA,MAAM,eAAe,GAAA,CAAI,MAAA;AACzB,IAAA,MAAM,cAAA,GAAiB,QAAA,CAAS,YAAY,CAAA,GAAI,aAAa,MAAA,GAAS,YAAA;AACtE,IAAA,OAAO;AAAA,MACL,MAAA,EAAQ,cAAA;AAAA,MACR,OAAA,EAAS,IAAI,yBAAA,IAA6B;AAAA,KAC5C;AAAA,EACF;AACF;AAxDa,iBAAA,GAAN,eAAA,CAAA;AAAA,EADN,UAAA,EAAW;AAAA,EAKG,eAAA,CAAA,CAAA,EAAA,QAAA,EAAS;AAAA,CAAA,EAJX,iBAAA,CAAA","file":"index.mjs","sourcesContent":["/** OpenAPI 3.1 `$ref` prefix for entries in `components.schemas`. */\nexport const COMPONENTS_SCHEMAS_PREFIX = '#/components/schemas/';\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 Phase 2e's\n * doc-merger. The marker carries `{ __zodNestDto: true, dtoId, io }` so the\n * merger can locate every zod-nest DTO in the @nestjs/swagger document and\n * inject the real Zod-derived schema.\n */\nexport const ZOD_NEST_DTO_EXTENSION = 'x-zod-nest-dto';\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\nexport const builtInOverride: 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\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\nexport const isStrictlyUnrepresentable = (\n jsonSchema: SchemaObject,\n zodSchema: $ZodTypes,\n): 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 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 if (list.length === 0) {\n return () => undefined;\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 } from './constants.js';\n\nexport interface PostProcessResult {\n schema: SchemaObject;\n refs: Map<string, SchemaObject>;\n}\n\nconst DEFS_PREFIX = '#/$defs/';\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 { SchemaObject } from './openapi.types.js';\nimport type { Override } from './override.js';\nimport type { ZodNestRegistry } from './registry.js';\n\nimport { ZOD_NEST_ERROR_DUPLICATE_ID, ZOD_NEST_ERROR_EXTENSION } from './constants.js';\nimport { ZodNestUnrepresentableError } from './errors.js';\nimport { builtInOverride, combine, isStrictlyUnrepresentable } from './override.js';\nimport { postProcess } from './post-process.js';\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\nexport const toOpenApi = (schema: z.ZodType, opts: ToOpenApiOptions): ToOpenApiResult => {\n const strict = opts.strict ?? true;\n const merged = combine(builtInOverride, opts.override);\n const unrepresentableHits: UnrepresentableHit[] = [];\n\n const wrapped: Override = (ctx) => {\n merged(ctx);\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 });\n };\n\n const raw = z.toJSONSchema(schema, {\n target: 'draft-2020-12',\n io: opts.io,\n unrepresentable: 'any',\n metadata: opts.registry.zodRegistry,\n override: wrapped,\n cycles: 'ref',\n reused: 'inline',\n });\n\n const firstHit = unrepresentableHits[0];\n if (firstHit !== undefined) {\n throw new ZodNestUnrepresentableError(firstHit.path, firstHit.zodType);\n }\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 { z } from 'zod';\n\nexport interface ZodNestRegistry {\n readonly zodRegistry: typeof z.globalRegistry;\n register(schema: z.ZodType, id: string): void;\n hasCollision(id: string): boolean;\n getCollisions(): ReadonlyMap<string, ReadonlySet<z.ZodType>>;\n}\n\nexport const createRegistry = (): ZodNestRegistry => {\n const seen = new Map<string, Set<z.ZodType>>();\n\n return {\n zodRegistry: z.globalRegistry,\n register: (schema, id) => {\n z.globalRegistry.add(schema, { id });\n let set = seen.get(id);\n if (set === undefined) {\n set = new Set<z.ZodType>();\n seen.set(id, set);\n }\n set.add(schema);\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 };\n};\n\n/**\n * Process-wide default registry. `createZodDto` registers schemas here unless\n * the caller passes `options.registry`. Phase 2e's doc merger reads from the\n * same instance for bulk emission. Multi-app WeakMap isolation is deferred\n * to v0.2.\n */\nexport const defaultRegistry: ZodNestRegistry = createRegistry();\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. Phase 2e's doc merger 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 Phase 2e.\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\n/** Phase 2e (and tests) use this to discriminate a marker from a real schema. */\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","/**\n * Runtime detection marker placed on every class returned by `createZodDto`.\n * Used by the validation pipe (Phase 2c), serializer (2d), and doc merger (2e)\n * to discriminate zod-nest DTO classes from regular constructors.\n */\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 * the Phase 2e doc-merger 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 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 } 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 resolveId = (\n registry: ZodNestRegistry,\n schema: z.ZodType,\n providedId: string | undefined,\n className: string,\n): string => {\n if (providedId !== undefined && providedId !== '') {\n return providedId;\n }\n const meta = registry.zodRegistry.get(schema) as { id?: string } | undefined;\n if (meta && typeof meta.id === 'string' && meta.id !== '') {\n return meta.id;\n }\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}\". Pass \\`createZodDto(schema, { id: 'Foo' })\\` to set a stable ` +\n `name — important under 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 cachedId = resolveId(registry, schema, options?.id, className);\n registry.register(schema, cachedId);\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 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 the validation pipe (Phase 2c), the serializer interceptor (2d),\n * and the doc merger (2e) 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","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 statusCode: HttpStatus.BAD_REQUEST,\n message: 'Validation failed',\n errors: z.treeifyError(zodError),\n });\n this.zodError = zodError;\n this.argMetadata = argMetadata;\n }\n}\n","import { Injectable, Optional } from '@nestjs/common';\n\nimport type { ArgumentMetadata, PipeTransform } from '@nestjs/common';\nimport type { z } from 'zod';\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';\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\n@Injectable()\nexport class ZodValidationPipe implements PipeTransform {\n private readonly explicitSchema: z.ZodType | undefined;\n private readonly createValidationException: CreateValidationException;\n\n constructor(@Optional() arg?: ZodValidationPipeArg) {\n const { schema, factory } = ZodValidationPipe.parseArg(arg);\n this.explicitSchema = schema;\n this.createValidationException = factory;\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 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 static parseArg(arg: ZodValidationPipeArg | undefined): {\n schema: z.ZodType | undefined;\n factory: CreateValidationException;\n } {\n if (arg === undefined) {\n return { schema: undefined, factory: defaultExceptionFactory };\n }\n if (isZodDto(arg)) {\n return { schema: arg.schema, factory: defaultExceptionFactory };\n }\n if (isZodSchema(arg)) {\n return { schema: arg, factory: defaultExceptionFactory };\n }\n if (!isOptionsObject(arg)) {\n return { schema: undefined, factory: defaultExceptionFactory };\n }\n const optionSchema = arg.schema;\n const resolvedSchema = isZodDto(optionSchema) ? optionSchema.schema : optionSchema;\n return {\n schema: resolvedSchema,\n factory: arg.createValidationException ?? defaultExceptionFactory,\n };\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zod-nest",
3
- "version": "0.1.5",
3
+ "version": "0.3.0",
4
4
  "description": "Modern Zod v4-only NestJS + OpenAPI 3.1 integration. Successor to nestjs-zod.",
5
5
  "license": "MIT",
6
6
  "author": "Rodrigo Azevedo",
@@ -70,6 +70,7 @@
70
70
  "@ianvs/prettier-plugin-sort-imports": "^4.4.0",
71
71
  "@nestjs/common": "^11.0.0",
72
72
  "@nestjs/core": "^11.0.0",
73
+ "@nestjs/platform-express": "^11.1.21",
73
74
  "@nestjs/swagger": "^11.0.0",
74
75
  "@semantic-release/changelog": "^6.0.3",
75
76
  "@semantic-release/exec": "^7.0.3",
@@ -78,6 +79,7 @@
78
79
  "@semantic-release/npm": "^12.0.0",
79
80
  "@types/jest": "^29.5.14",
80
81
  "@types/node": "^22.10.0",
82
+ "@types/supertest": "^7.2.0",
81
83
  "eslint": "^9.16.0",
82
84
  "eslint-config-prettier": "^9.1.0",
83
85
  "eslint-plugin-jest": "^28.10.0",
@@ -92,6 +94,7 @@
92
94
  "reflect-metadata": "^0.2.2",
93
95
  "rxjs": "^7.8.1",
94
96
  "semantic-release": "^24.2.0",
97
+ "supertest": "^7.2.2",
95
98
  "ts-jest": "^29.2.5",
96
99
  "tsup": "^8.3.5",
97
100
  "typescript": "^5.7.2",