@cerios/openapi-to-zod 0.5.3 → 1.0.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,3 +1,6 @@
1
+ import { O as OpenApiGeneratorOptions } from './types-BjoP91vk.mjs';
2
+ export { C as CommonSchemaOptions, a as ConfigFile, E as ExecutionMode, b as OpenAPISchema, c as OpenAPISpec, d as OperationFilters, R as RequestOptions, e as ResponseOptions, f as defineConfig } from './types-BjoP91vk.mjs';
3
+
1
4
  /**
2
5
  * Custom error classes for better error handling and debugging
3
6
  */
@@ -50,356 +53,14 @@ declare class CliOptionsError extends GeneratorError {
50
53
  constructor(message: string, context?: Record<string, unknown>);
51
54
  }
52
55
 
53
- /**
54
- * Type generation mode
55
- * - 'inferred': Generate Zod schemas with z.infer<typeof schema> types (default)
56
- * - 'native': Generate native TypeScript types without Zod schemas
57
- */
58
- type TypeMode = "inferred" | "native";
59
- /**
60
- * Native enum generation type (used when typeMode is 'native')
61
- * - 'union': Generate union types like 'a' | 'b' | 'c' (default)
62
- * - 'enum': Generate TypeScript enums like enum StatusEnum { A = 'a', B = 'b' }
63
- */
64
- type NativeEnumType = "union" | "enum";
65
- /**
66
- * Common options shared by both request and response contexts
67
- */
68
- interface CommonSchemaOptions {
69
- /**
70
- * Object validation mode
71
- * - 'strict': Uses z.strictObject() - no additional properties allowed
72
- * - 'normal': Uses z.object() - additional properties allowed
73
- * - 'loose': Uses z.looseObject() - explicitly allows additional properties
74
- */
75
- mode?: "strict" | "normal" | "loose";
76
- /**
77
- * Enum generation type
78
- * - 'zod': Uses z.enum() with inferred types (default)
79
- * - 'typescript': Uses TypeScript enums with z.enum() referencing them
80
- */
81
- enumType?: "zod" | "typescript";
82
- /**
83
- * Whether to add .describe() calls for better error messages
84
- * @default false
85
- */
86
- useDescribe?: boolean;
87
- /**
88
- * Whether to include descriptions as JSDoc comments
89
- */
90
- includeDescriptions?: boolean;
91
- }
92
- /**
93
- * Request-specific options that can override root-level options
94
- * Requests support native TypeScript type generation as an alternative to Zod schemas
95
- */
96
- interface RequestOptions extends CommonSchemaOptions {
97
- /**
98
- * Type generation mode
99
- * - 'inferred': Generate Zod schemas with z.infer types (default)
100
- * - 'native': Generate native TypeScript types without Zod validation
101
- */
102
- typeMode?: TypeMode;
103
- /**
104
- * Native enum generation type (when typeMode is 'native')
105
- * - 'union': Generate union types (default)
106
- * - 'enum': Generate TypeScript enums
107
- */
108
- nativeEnumType?: NativeEnumType;
109
- }
110
- /**
111
- * Response-specific options that can override root-level options
112
- * Responses always use Zod schemas for runtime validation
113
- */
114
- interface ResponseOptions extends CommonSchemaOptions {
115
- }
116
- interface OpenApiGeneratorOptions {
117
- /**
118
- * Object validation mode
119
- * - 'strict': Uses z.strictObject() - no additional properties allowed
120
- * - 'normal': Uses z.object() - additional properties allowed
121
- * - 'loose': Uses z.looseObject() - explicitly allows additional properties
122
- */
123
- mode?: "strict" | "normal" | "loose";
124
- /**
125
- * Input OpenAPI YAML file path
126
- */
127
- input: string;
128
- /**
129
- * Output TypeScript file path
130
- * Optional when using string generation methods (generateString)
131
- * Required when calling generate() to write to a file
132
- */
133
- output?: string;
134
- /**
135
- * Whether to include descriptions as JSDoc comments
136
- */
137
- includeDescriptions?: boolean;
138
- /**
139
- * Enum generation type
140
- * - 'zod': Uses z.enum() with inferred types (default)
141
- * - 'typescript': Uses TypeScript enums with z.enum() referencing them
142
- */
143
- enumType?: "zod" | "typescript";
144
- /**
145
- * Whether to add .describe() calls for better error messages
146
- * @default false
147
- */
148
- useDescribe?: boolean;
149
- /**
150
- * Schema filtering mode
151
- * - 'all': Generate all schemas (default)
152
- * - 'request': Only include schemas suitable for requests (excludes readOnly)
153
- * - 'response': Only include schemas suitable for responses (excludes writeOnly)
154
- */
155
- schemaType?: "all" | "request" | "response";
156
- /**
157
- * Prefix to add to all generated schema names
158
- * @example "api" -> "apiUserSchema"
159
- */
160
- prefix?: string;
161
- /**
162
- * Suffix to add before "Schema" in generated names
163
- * @example "dto" -> "userDtoSchema"
164
- */
165
- suffix?: string;
166
- /**
167
- * Whether to include generation statistics in output file
168
- * @default true
169
- */
170
- showStats?: boolean;
171
- /**
172
- * Native enum generation type (when typeMode is 'native')
173
- * - 'union': Generate union types (default)
174
- * - 'enum': Generate TypeScript enums with 'Enum' suffix
175
- * @default 'union'
176
- */
177
- nativeEnumType?: NativeEnumType;
178
- /**
179
- * Request-specific options that override root-level options
180
- * Applied when schemas are used in request contexts
181
- * Supports native TypeScript type generation
182
- */
183
- request?: RequestOptions;
184
- /**
185
- * Response-specific options that override root-level options
186
- * Applied when schemas are used in response contexts
187
- * Always generates Zod schemas for runtime validation
188
- */
189
- response?: ResponseOptions;
190
- /**
191
- * Filter which operations to include/exclude from generation
192
- * Useful for generating separate schemas for different API subsets
193
- *
194
- * Filtering logic:
195
- * 1. If no filters specified, all operations are included
196
- * 2. Empty arrays are treated as "no constraint" (not as "exclude all")
197
- * 3. Include filters are applied first (allowlist)
198
- * 4. Exclude filters are applied second (blocklist)
199
- * 5. Exclude rules always win over include rules
200
- *
201
- * Supports glob patterns for paths and operationIds (e.g., "/api/v1/**", "get*")
202
- *
203
- * @example
204
- * // Only generate schemas for user-related endpoints
205
- * operationFilters: {
206
- * includeTags: ["users"]
207
- * }
208
- *
209
- * @example
210
- * // Generate only GET endpoints, excluding deprecated ones
211
- * operationFilters: {
212
- * includeMethods: ["get"],
213
- * excludeDeprecated: true
214
- * }
215
- *
216
- * @example
217
- * // Generate only v1 API endpoints
218
- * operationFilters: {
219
- * includePaths: ["/api/v1/**"]
220
- * }
221
- */
222
- operationFilters?: OperationFilters;
223
- }
224
- /**
225
- * Operation filtering options
226
- * Controls which operations from the OpenAPI spec are included in generation
227
- */
228
- interface OperationFilters {
229
- /**
230
- * Include only operations with these tags
231
- * If specified, only operations with at least one matching tag are included
232
- * Empty array = no constraint
233
- */
234
- includeTags?: string[];
235
- /**
236
- * Exclude operations with these tags
237
- * Operations with any matching tag are excluded
238
- * Empty array = no constraint
239
- */
240
- excludeTags?: string[];
241
- /**
242
- * Include only operations matching these path patterns
243
- * Supports glob patterns (e.g., "/users/**", "/api/v1/*")
244
- * Empty array = no constraint
245
- */
246
- includePaths?: string[];
247
- /**
248
- * Exclude operations matching these path patterns
249
- * Supports glob patterns (e.g., "/internal/**", "/admin/*")
250
- * Empty array = no constraint
251
- */
252
- excludePaths?: string[];
253
- /**
254
- * Include only these HTTP methods
255
- * Valid values: "get", "post", "put", "patch", "delete", "head", "options"
256
- * Empty array = no constraint
257
- */
258
- includeMethods?: string[];
259
- /**
260
- * Exclude these HTTP methods
261
- * Valid values: "get", "post", "put", "patch", "delete", "head", "options"
262
- * Empty array = no constraint
263
- */
264
- excludeMethods?: string[];
265
- /**
266
- * Include only operations matching these operationId patterns
267
- * Supports glob patterns (e.g., "getUser*", "*Admin")
268
- * Empty array = no constraint
269
- */
270
- includeOperationIds?: string[];
271
- /**
272
- * Exclude operations matching these operationId patterns
273
- * Supports glob patterns (e.g., "deleteUser*", "*Internal")
274
- * Empty array = no constraint
275
- */
276
- excludeOperationIds?: string[];
277
- /**
278
- * Whether to exclude deprecated operations
279
- * @default false
280
- */
281
- excludeDeprecated?: boolean;
282
- }
283
- interface OpenAPISchema {
284
- type?: string | string[];
285
- format?: string;
286
- enum?: (string | number)[];
287
- const?: string | number | boolean | null;
288
- properties?: Record<string, OpenAPISchema>;
289
- required?: string[];
290
- items?: OpenAPISchema;
291
- prefixItems?: OpenAPISchema[];
292
- allOf?: OpenAPISchema[];
293
- oneOf?: OpenAPISchema[];
294
- anyOf?: OpenAPISchema[];
295
- $ref?: string;
296
- nullable?: boolean;
297
- minLength?: number;
298
- maxLength?: number;
299
- minimum?: number;
300
- maximum?: number;
301
- exclusiveMinimum?: boolean | number;
302
- exclusiveMaximum?: boolean | number;
303
- multipleOf?: number;
304
- pattern?: string;
305
- description?: string;
306
- title?: string;
307
- example?: any;
308
- examples?: any[];
309
- additionalProperties?: boolean | OpenAPISchema;
310
- minProperties?: number;
311
- maxProperties?: number;
312
- minItems?: number;
313
- maxItems?: number;
314
- uniqueItems?: boolean;
315
- contains?: OpenAPISchema;
316
- minContains?: number;
317
- maxContains?: number;
318
- discriminator?: {
319
- propertyName: string;
320
- mapping?: Record<string, string>;
321
- };
322
- readOnly?: boolean;
323
- writeOnly?: boolean;
324
- deprecated?: boolean;
325
- dependentRequired?: Record<string, string[]>;
326
- dependencies?: Record<string, string[] | OpenAPISchema>;
327
- patternProperties?: Record<string, OpenAPISchema>;
328
- propertyNames?: OpenAPISchema;
329
- contentMediaType?: string;
330
- contentEncoding?: string;
331
- not?: OpenAPISchema;
332
- if?: OpenAPISchema;
333
- then?: OpenAPISchema;
334
- else?: OpenAPISchema;
335
- unevaluatedProperties?: boolean | OpenAPISchema;
336
- unevaluatedItems?: boolean | OpenAPISchema;
337
- }
338
- interface OpenAPISpec {
339
- components?: {
340
- schemas?: Record<string, OpenAPISchema>;
341
- };
342
- paths?: Record<string, any>;
343
- }
344
- /**
345
- * Execution mode for batch processing
346
- * - 'parallel': Process all specs concurrently (default, faster)
347
- * - 'sequential': Process specs one at a time (safer for resource constraints)
348
- */
349
- type ExecutionMode = "parallel" | "sequential";
350
- /**
351
- * Root configuration file structure
352
- */
353
- interface ConfigFile {
354
- /**
355
- * Global default options applied to all specs
356
- * Can be overridden by individual spec configurations
357
- */
358
- defaults?: Partial<Omit<OpenApiGeneratorOptions, "input" | "output">>;
359
- /**
360
- * Array of OpenAPI specifications to process
361
- * Each spec must have input and output paths
362
- */
363
- specs: OpenApiGeneratorOptions[];
364
- /**
365
- * Execution mode for batch processing
366
- * @default "parallel"
367
- */
368
- executionMode?: ExecutionMode;
369
- }
370
- /**
371
- * Helper function for type-safe config file creation
372
- * Provides IDE autocomplete and type checking for config files
373
- *
374
- * @example
375
- * ```typescript
376
- * import { defineConfig } from '@cerios/openapi-to-zod';
377
- *
378
- * export default defineConfig({
379
- * defaults: {
380
- * mode: 'strict',
381
- * includeDescriptions: true
382
- * },
383
- * specs: [
384
- * { input: 'api-v1.yaml', output: 'schemas/v1.ts' },
385
- * { input: 'api-v2.yaml', output: 'schemas/v2.ts', mode: 'normal' }
386
- * ]
387
- * });
388
- * ```
389
- */
390
- declare function defineConfig(config: ConfigFile): ConfigFile;
391
-
392
56
  declare class OpenApiGenerator {
393
57
  private schemas;
394
58
  private types;
395
- private enums;
396
- private nativeEnums;
397
59
  private schemaDependencies;
398
60
  private options;
399
61
  private spec;
400
62
  private propertyGenerator;
401
63
  private schemaUsageMap;
402
- private schemaTypeModeMap;
403
64
  private requestOptions;
404
65
  private responseOptions;
405
66
  private needsZodImport;
@@ -421,7 +82,6 @@ declare class OpenApiGenerator {
421
82
  /**
422
83
  * Resolve options for a specific context (request or response)
423
84
  * Nested options silently override root-level options
424
- * Response schemas always use 'inferred' mode (Zod schemas)
425
85
  */
426
86
  private resolveOptionsForContext;
427
87
  /**
@@ -449,11 +109,6 @@ declare class OpenApiGenerator {
449
109
  * Detect circular references and mark them as "both" context for safety
450
110
  */
451
111
  private detectCircularReferences;
452
- /**
453
- * Determine the typeMode for each schema based on its usage context
454
- * Response schemas always use 'inferred' mode
455
- */
456
- private determineSchemaTypeModes;
457
112
  /**
458
113
  * Validate the OpenAPI specification
459
114
  */
@@ -470,6 +125,11 @@ declare class OpenApiGenerator {
470
125
  * Generate query parameter schemas for each operation
471
126
  */
472
127
  private generateQueryParameterSchemas;
128
+ /**
129
+ * Check if a header should be ignored based on filter patterns
130
+ * @internal
131
+ */
132
+ private shouldIgnoreHeader;
473
133
  /**
474
134
  * Generate header parameter schemas for each operation
475
135
  * Header parameters are always string type (HTTP header semantics)
@@ -479,26 +139,6 @@ declare class OpenApiGenerator {
479
139
  * Generate Zod type for a query parameter schema
480
140
  */
481
141
  private generateQueryParamType;
482
- /**
483
- * Generate native TypeScript enum
484
- */
485
- private generateNativeEnum;
486
- /**
487
- * Convert string to valid enum key
488
- */
489
- private toEnumKey;
490
- /**
491
- * Add constraint annotations to JSDoc for native types
492
- */
493
- private addConstraintsToJSDoc;
494
- /**
495
- * Generate native TypeScript type definition from OpenAPI schema
496
- */
497
- private generateNativeTypeDefinition;
498
- /**
499
- * Generate TypeScript object type definition
500
- */
501
- private generateObjectType;
502
142
  /**
503
143
  * Topological sort for schema dependencies
504
144
  * Returns schemas in the order they should be declared
@@ -510,55 +150,4 @@ declare class OpenApiGenerator {
510
150
  private generateStats;
511
151
  }
512
152
 
513
- /**
514
- * Filter statistics to track which operations were included/excluded
515
- */
516
- interface FilterStatistics {
517
- totalOperations: number;
518
- includedOperations: number;
519
- filteredByTags: number;
520
- filteredByPaths: number;
521
- filteredByMethods: number;
522
- filteredByOperationIds: number;
523
- filteredByDeprecated: number;
524
- }
525
- /**
526
- * Create a new filter statistics object with all counters initialized to zero
527
- */
528
- declare function createFilterStatistics(): FilterStatistics;
529
- /**
530
- * Determine if an operation should be included based on filter criteria
531
- *
532
- * Filter logic:
533
- * 1. If no filters specified, include all operations
534
- * 2. Empty arrays are treated as "no constraint" (not as "exclude all")
535
- * 3. Include filters are applied first (allowlist)
536
- * 4. Exclude filters are applied second (blocklist)
537
- * 5. Exclude rules always win over include rules
538
- *
539
- * @param operation - The OpenAPI operation object
540
- * @param path - The operation path (e.g., "/users/{id}")
541
- * @param method - The HTTP method (e.g., "get", "post")
542
- * @param filters - Optional filter configuration
543
- * @param stats - Optional statistics object to track filtering reasons
544
- * @returns true if the operation should be included, false otherwise
545
- */
546
- declare function shouldIncludeOperation(operation: any, path: string, method: string, filters?: OperationFilters, stats?: FilterStatistics): boolean;
547
- /**
548
- * Validate filter statistics and emit warnings for filters that matched nothing
549
- * Helps users debug filter configurations that might be too restrictive or contain typos
550
- *
551
- * @param stats - Filter statistics object
552
- * @param filters - The filter configuration to validate
553
- */
554
- declare function validateFilters(stats: FilterStatistics, filters?: OperationFilters): void;
555
- /**
556
- * Format filter statistics for display in generated output
557
- * Returns a formatted string suitable for inclusion in comments
558
- *
559
- * @param stats - Filter statistics object
560
- * @returns Formatted statistics string
561
- */
562
- declare function formatFilterStatistics(stats: FilterStatistics): string;
563
-
564
- export { CircularReferenceError, CliOptionsError, type CommonSchemaOptions, type ConfigFile, ConfigValidationError, type ExecutionMode, FileOperationError, type FilterStatistics, GeneratorError, type NativeEnumType, type OpenAPISchema, type OpenAPISpec, OpenApiGenerator, type OpenApiGeneratorOptions, type OperationFilters, type RequestOptions, type ResponseOptions, SchemaGenerationError, SpecValidationError, type TypeMode, createFilterStatistics, defineConfig, formatFilterStatistics, shouldIncludeOperation, validateFilters };
153
+ export { CircularReferenceError, CliOptionsError, ConfigValidationError, FileOperationError, GeneratorError, OpenApiGenerator, OpenApiGeneratorOptions, SchemaGenerationError, SpecValidationError };