-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-zod.ts
More file actions
989 lines (888 loc) · 30.9 KB
/
generate-zod.ts
File metadata and controls
989 lines (888 loc) · 30.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
import type { DevupApiTypeGeneratorOptions } from '@devup-api/core'
import type { OpenAPIV3_1 } from 'openapi-types'
import { convertCase } from './convert-case'
import {
CONTENT_TYPE_PRIORITY,
collectSchemaNames,
extractSchemaNameFromRef,
getPrimaryType,
isErrorStatusCode,
isNullableSchema,
normalizeServerName,
resolveRef,
} from './openapi-utils'
import { wrapInterfaceKeyGuard } from './wrap-interface-key-guard'
// =============================================================================
// OpenAPI to Zod Conversion
// =============================================================================
/**
* Convert OpenAPI schema to Zod schema code string
*/
function schemaToZod(
schema: OpenAPIV3_1.SchemaObject | OpenAPIV3_1.ReferenceObject,
document: OpenAPIV3_1.Document,
schemaRefs: Map<string, string>,
options?: { defaultNonNullable?: boolean },
): string {
const defaultNonNullable = options?.defaultNonNullable ?? false
// Handle $ref
if ('$ref' in schema) {
const schemaName = extractSchemaNameFromRef(schema.$ref)
if (schemaName && schemaRefs.has(schemaName)) {
// Return lazy reference for circular dependencies
return `z.lazy(() => ${schemaRefs.get(schemaName)})`
}
const resolved = resolveRef<OpenAPIV3_1.SchemaObject>(schema.$ref, document)
if (resolved) {
return schemaToZod(resolved, document, schemaRefs, options)
}
return 'z.unknown()'
}
const schemaObj = schema as OpenAPIV3_1.SchemaObject
const wrapNullable = (zodStr: string): string => {
if (isNullableSchema(schemaObj)) {
return `${zodStr}.nullable()`
}
return zodStr
}
const primaryType = getPrimaryType(schemaObj)
// Handle allOf (intersection)
if (schemaObj.allOf) {
const schemas = schemaObj.allOf.map((s) =>
schemaToZod(s, document, schemaRefs, options),
)
if (schemas.length === 0) return 'z.unknown()'
if (schemas.length === 1) return wrapNullable(schemas[0] as string)
return wrapNullable(`z.intersection(${schemas.join(', ')})`)
}
// Handle oneOf/anyOf (union)
if (schemaObj.oneOf || schemaObj.anyOf) {
const schemas = (schemaObj.oneOf || schemaObj.anyOf || []).map((s) =>
schemaToZod(s, document, schemaRefs, options),
)
if (schemas.length === 0) return 'z.unknown()'
if (schemas.length === 1) return wrapNullable(schemas[0] as string)
return wrapNullable(`z.union([${schemas.join(', ')}])`)
}
// Handle enum
if (schemaObj.enum) {
const enumValues = schemaObj.enum.map((v) => JSON.stringify(v))
if (enumValues.length === 1) {
return wrapNullable(`z.literal(${enumValues[0]})`)
}
return wrapNullable(`z.enum([${enumValues.join(', ')}])`)
}
// Handle primitive types
if (primaryType === 'string') {
// Handle binary format for file upload fields
if (schemaObj.format === 'binary') {
return wrapNullable('z.instanceof(File)')
}
// Zod 4.0: Use top-level format validators instead of z.string().format()
// Check format first to use top-level validators
if (schemaObj.format === 'email') {
let zodStr = 'z.email()'
if (schemaObj.minLength !== undefined) {
zodStr += `.min(${schemaObj.minLength})`
}
if (schemaObj.maxLength !== undefined) {
zodStr += `.max(${schemaObj.maxLength})`
}
return wrapNullable(zodStr)
}
if (schemaObj.format === 'uri' || schemaObj.format === 'url') {
let zodStr = 'z.url()'
if (schemaObj.minLength !== undefined) {
zodStr += `.min(${schemaObj.minLength})`
}
if (schemaObj.maxLength !== undefined) {
zodStr += `.max(${schemaObj.maxLength})`
}
return wrapNullable(zodStr)
}
if (schemaObj.format === 'uuid') {
return wrapNullable('z.uuid()')
}
if (schemaObj.format === 'date-time') {
return wrapNullable('z.iso.datetime()')
}
// For strings without special format, use z.string() with constraints
let zodStr = 'z.string()'
if (schemaObj.minLength !== undefined) {
zodStr += `.min(${schemaObj.minLength})`
}
if (schemaObj.maxLength !== undefined) {
zodStr += `.max(${schemaObj.maxLength})`
}
if (schemaObj.pattern) {
zodStr += `.regex(/${schemaObj.pattern}/)`
}
return wrapNullable(zodStr)
}
if (primaryType === 'number' || primaryType === 'integer') {
// Zod 4.0: Use z.int() for integers instead of z.number().int()
let zodStr = primaryType === 'integer' ? 'z.int()' : 'z.number()'
if (schemaObj.minimum !== undefined) {
zodStr += `.min(${schemaObj.minimum})`
}
if (schemaObj.maximum !== undefined) {
zodStr += `.max(${schemaObj.maximum})`
}
if (schemaObj.exclusiveMinimum !== undefined) {
zodStr += `.gt(${schemaObj.exclusiveMinimum})`
}
if (schemaObj.exclusiveMaximum !== undefined) {
zodStr += `.lt(${schemaObj.exclusiveMaximum})`
}
return wrapNullable(zodStr)
}
if (primaryType === 'boolean') {
return wrapNullable('z.boolean()')
}
// Handle array
if (primaryType === 'array') {
if ('items' in schemaObj && schemaObj.items) {
const itemSchema = schemaToZod(
schemaObj.items,
document,
schemaRefs,
options,
)
let zodStr = `z.array(${itemSchema})`
if (schemaObj.minItems !== undefined) {
zodStr += `.min(${schemaObj.minItems})`
}
if (schemaObj.maxItems !== undefined) {
zodStr += `.max(${schemaObj.maxItems})`
}
return wrapNullable(zodStr)
}
return wrapNullable('z.array(z.unknown())')
}
// Handle object
if (primaryType === 'object' || schemaObj.properties) {
const required = new Set(schemaObj.required || [])
const properties: string[] = []
if (schemaObj.properties) {
for (const [key, value] of Object.entries(schemaObj.properties)) {
const propSchema = schemaToZod(value, document, schemaRefs, options)
const isRequired = required.has(key)
// Check for default value
let hasDefault = false
if ('$ref' in value) {
const resolved = resolveRef<OpenAPIV3_1.SchemaObject>(
value.$ref,
document,
)
if (resolved) {
hasDefault = resolved.default !== undefined
}
} else {
hasDefault = (value as OpenAPIV3_1.SchemaObject).default !== undefined
}
let propStr = propSchema
if (!isRequired && !(defaultNonNullable && hasDefault)) {
propStr += '.optional()'
}
properties.push(`${wrapInterfaceKeyGuard(key)}: ${propStr}`)
}
}
let zodStr =
properties.length > 0
? `z.object({\n ${properties.join(',\n ')}\n })`
: 'z.object({})'
// Handle additionalProperties
if (schemaObj.additionalProperties === true) {
zodStr += '.passthrough()'
} else if (
typeof schemaObj.additionalProperties === 'object' &&
schemaObj.additionalProperties !== null
) {
// For typed additional properties, we can't perfectly represent this in Zod
// We use passthrough() as an approximation
zodStr += '.passthrough()'
}
return wrapNullable(zodStr)
}
return 'z.unknown()'
}
// =============================================================================
// OpenAPI to Zod Type Conversion (for TypeScript type declarations)
// =============================================================================
/**
* Convert OpenAPI schema to Zod TypeScript type string
* Unlike schemaToZod which generates runtime code like z.object({...}),
* this generates TypeScript types like z.ZodObject<{...}>
*/
function schemaToZodType(
schema: OpenAPIV3_1.SchemaObject | OpenAPIV3_1.ReferenceObject,
document: OpenAPIV3_1.Document,
options?: { defaultNonNullable?: boolean },
): string {
const defaultNonNullable = options?.defaultNonNullable ?? false
// Handle $ref
if ('$ref' in schema) {
const schemaName = extractSchemaNameFromRef(schema.$ref)
if (schemaName) {
// Return a lazy type reference
return `z.ZodLazy<z.ZodTypeAny>`
}
const resolved = resolveRef<OpenAPIV3_1.SchemaObject>(schema.$ref, document)
if (resolved) {
return schemaToZodType(resolved, document, options)
}
return 'z.ZodUnknown'
}
const schemaObj = schema as OpenAPIV3_1.SchemaObject
const wrapNullable = (zodType: string): string => {
if (isNullableSchema(schemaObj)) {
return `z.ZodNullable<${zodType}>`
}
return zodType
}
const primaryType = getPrimaryType(schemaObj)
// Handle allOf (intersection)
if (schemaObj.allOf) {
const types = schemaObj.allOf.map((s) =>
schemaToZodType(s, document, options),
)
if (types.length === 0) return 'z.ZodUnknown'
if (types.length === 1) return wrapNullable(types[0] as string)
// Zod intersection only takes 2 args, so we need to nest
let result = types[0] as string
for (let i = 1; i < types.length; i++) {
result = `z.ZodIntersection<${result}, ${types[i]}>`
}
return wrapNullable(result)
}
// Handle oneOf/anyOf (union)
if (schemaObj.oneOf || schemaObj.anyOf) {
const types = (schemaObj.oneOf || schemaObj.anyOf || []).map((s) =>
schemaToZodType(s, document, options),
)
if (types.length === 0) return 'z.ZodUnknown'
if (types.length === 1) return wrapNullable(types[0] as string)
return wrapNullable(`z.ZodUnion<[${types.join(', ')}]>`)
}
// Handle enum
if (schemaObj.enum) {
const enumValues = schemaObj.enum.map((v) => JSON.stringify(v))
if (enumValues.length === 1) {
return wrapNullable(`z.ZodLiteral<${enumValues[0]}>`)
}
return wrapNullable(`z.ZodEnum<[${enumValues.join(', ')}]>`)
}
// Handle primitive types
if (primaryType === 'string') {
if (schemaObj.format === 'binary') {
return wrapNullable('z.ZodType<File>')
}
return wrapNullable('z.ZodString')
}
if (primaryType === 'number' || primaryType === 'integer') {
return wrapNullable('z.ZodNumber')
}
if (primaryType === 'boolean') {
return wrapNullable('z.ZodBoolean')
}
// Handle array
if (primaryType === 'array') {
if ('items' in schemaObj && schemaObj.items) {
const itemType = schemaToZodType(schemaObj.items, document, options)
return wrapNullable(`z.ZodArray<${itemType}>`)
}
return wrapNullable('z.ZodArray<z.ZodUnknown>')
}
// Handle object
if (primaryType === 'object' || schemaObj.properties) {
const required = new Set(schemaObj.required || [])
const properties: string[] = []
if (schemaObj.properties) {
for (const [key, value] of Object.entries(schemaObj.properties)) {
const propType = schemaToZodType(value, document, options)
const isRequired = required.has(key)
// Check for default value
let hasDefault = false
if ('$ref' in value) {
const resolved = resolveRef<OpenAPIV3_1.SchemaObject>(
value.$ref,
document,
)
if (resolved) {
hasDefault = resolved.default !== undefined
}
} else {
hasDefault = (value as OpenAPIV3_1.SchemaObject).default !== undefined
}
let finalType = propType
if (!isRequired && !(defaultNonNullable && hasDefault)) {
finalType = `z.ZodOptional<${propType}>`
}
properties.push(`${wrapInterfaceKeyGuard(key)}: ${finalType}`)
}
}
const objectType =
properties.length > 0
? `z.ZodObject<{ ${properties.join('; ')} }>`
: 'z.ZodObject<Record<string, never>>'
return wrapNullable(objectType)
}
return 'z.ZodUnknown'
}
// =============================================================================
// Schema Collection
// =============================================================================
interface SchemaInfo {
code: string // Runtime Zod code
type: string // TypeScript Zod type
}
interface PathSchemaMapping {
schemaName: string | null
operationId: string | null
}
interface CollectedSchemas {
requestSchemas: Record<string, SchemaInfo>
responseSchemas: Record<string, SchemaInfo>
errorSchemas: Record<string, SchemaInfo>
/** Schemas referenced via $ref within category schemas but not themselves a category schema */
dependencySchemas: Record<string, SchemaInfo>
pathMappings: Record<
'get' | 'post' | 'put' | 'delete' | 'patch',
Record<string, PathSchemaMapping>
>
}
/**
* Collect schema names used in request, response, and error positions
* Also collects path to schema mappings for hookform integration
*/
function collectSchemaUsage(
schema: OpenAPIV3_1.Document,
options?: DevupApiTypeGeneratorOptions,
): {
requestSchemaNames: Set<string>
responseSchemaNames: Set<string>
errorSchemaNames: Set<string>
pathMappings: Record<
'get' | 'post' | 'put' | 'delete' | 'patch',
Record<string, PathSchemaMapping>
>
} {
const requestSchemaNames = new Set<string>()
const responseSchemaNames = new Set<string>()
const errorSchemaNames = new Set<string>()
const pathMappings: Record<
'get' | 'post' | 'put' | 'delete' | 'patch',
Record<string, PathSchemaMapping>
> = {
get: {},
post: {},
put: {},
delete: {},
patch: {},
}
const convertCaseType = options?.convertCase ?? 'camel'
// Helper to get direct schema name from request body
const getRequestBodySchemaName = (
requestBody: OpenAPIV3_1.RequestBodyObject | OpenAPIV3_1.ReferenceObject,
): string | null => {
if ('$ref' in requestBody) {
return extractSchemaNameFromRef(requestBody.$ref)
}
const content = requestBody.content
for (const ct of CONTENT_TYPE_PRIORITY) {
const bodyContent = content?.[ct]
if (bodyContent?.schema && '$ref' in bodyContent.schema) {
return extractSchemaNameFromRef(bodyContent.schema.$ref)
}
}
return null
}
if (schema.paths) {
for (const [path, pathItem] of Object.entries(schema.paths)) {
if (!pathItem) continue
const methods = ['get', 'post', 'put', 'delete', 'patch'] as const
for (const method of methods) {
const operation = pathItem[method]
if (!operation) continue
// Normalize path for case conversion
const normalizedPath = path.replace(/\{([^}]+)\}/g, (_, param) => {
return `{${convertCase(param, convertCaseType)}}`
})
// Get operationId if exists
const operationId = operation.operationId
? convertCase(operation.operationId, convertCaseType)
: null
// Collect request body schemas and path mappings
let requestSchemaName: string | null = null
if (operation.requestBody) {
requestSchemaName = getRequestBodySchemaName(operation.requestBody)
if ('$ref' in operation.requestBody) {
const schemaName = extractSchemaNameFromRef(
operation.requestBody.$ref,
)
if (schemaName) {
requestSchemaNames.add(schemaName)
}
} else {
const content = operation.requestBody.content
for (const ct of CONTENT_TYPE_PRIORITY) {
const bodyContent = content?.[ct]
if (bodyContent?.schema) {
collectSchemaNames(bodyContent.schema, requestSchemaNames)
break
}
}
}
}
// Store path mapping
const mapping: PathSchemaMapping = {
schemaName: requestSchemaName,
operationId,
}
pathMappings[method][normalizedPath] = mapping
if (operationId) {
pathMappings[method][operationId] = mapping
}
// Collect response and error schemas
if (operation.responses) {
for (const [statusCode, response] of Object.entries(
operation.responses,
)) {
const isError = isErrorStatusCode(statusCode)
if ('$ref' in response) {
const schemaName = extractSchemaNameFromRef(response.$ref)
if (schemaName) {
if (isError) {
errorSchemaNames.add(schemaName)
} else {
responseSchemaNames.add(schemaName)
}
}
} else if ('content' in response) {
const content = response.content
const jsonContent = content?.['application/json']
if (jsonContent?.schema) {
if (isError) {
collectSchemaNames(jsonContent.schema, errorSchemaNames)
} else {
collectSchemaNames(jsonContent.schema, responseSchemaNames)
}
}
}
}
}
}
}
}
return {
requestSchemaNames,
responseSchemaNames,
errorSchemaNames,
pathMappings,
}
}
/**
* Generate Zod schemas for a single OpenAPI document
*/
function generateSchemasForDocument(
schema: OpenAPIV3_1.Document,
_serverName: string,
options?: DevupApiTypeGeneratorOptions,
): CollectedSchemas {
const {
requestSchemaNames,
responseSchemaNames,
errorSchemaNames,
pathMappings,
} = collectSchemaUsage(schema, options)
const requestSchemas: Record<string, SchemaInfo> = {}
const responseSchemas: Record<string, SchemaInfo> = {}
const errorSchemas: Record<string, SchemaInfo> = {}
// Create a map of schema references for lazy loading
const schemaRefs = new Map<string, string>()
if (schema.components?.schemas) {
for (const schemaName of Object.keys(schema.components.schemas)) {
schemaRefs.set(schemaName, `_${schemaName}`)
}
}
if (schema.components?.schemas) {
for (const [schemaName, schemaObj] of Object.entries(
schema.components.schemas,
)) {
if (!schemaObj) continue
const requestDefaultNonNullable =
options?.requestDefaultNonNullable ?? false
const responseDefaultNonNullable =
options?.responseDefaultNonNullable ?? true
const isRequest = requestSchemaNames.has(schemaName)
const isResponse = responseSchemaNames.has(schemaName)
const isError = errorSchemaNames.has(schemaName)
const schemaRef = schemaObj as
| OpenAPIV3_1.SchemaObject
| OpenAPIV3_1.ReferenceObject
if (isRequest) {
requestSchemas[schemaName] = {
code: schemaToZod(schemaRef, schema, schemaRefs, {
defaultNonNullable: requestDefaultNonNullable,
}),
type: schemaToZodType(schemaRef, schema, {
defaultNonNullable: requestDefaultNonNullable,
}),
}
}
if (isResponse) {
responseSchemas[schemaName] = {
code: schemaToZod(schemaRef, schema, schemaRefs, {
defaultNonNullable: responseDefaultNonNullable,
}),
type: schemaToZodType(schemaRef, schema, {
defaultNonNullable: responseDefaultNonNullable,
}),
}
}
if (isError) {
errorSchemas[schemaName] = {
code: schemaToZod(schemaRef, schema, schemaRefs, {
defaultNonNullable: responseDefaultNonNullable,
}),
type: schemaToZodType(schemaRef, schema, {
defaultNonNullable: responseDefaultNonNullable,
}),
}
}
}
}
// Collect all transitively referenced schemas from category schemas
const allCategoryNames = new Set([
...requestSchemaNames,
...responseSchemaNames,
...errorSchemaNames,
])
const allReferencedNames = new Set<string>()
for (const schemaName of allCategoryNames) {
const schemaDef = schema.components?.schemas?.[schemaName]
if (schemaDef) {
collectSchemaNames(
schemaDef as OpenAPIV3_1.SchemaObject | OpenAPIV3_1.ReferenceObject,
allReferencedNames,
{ followComponentRefs: true, document: schema },
)
}
}
// Generate dependency schemas (referenced via $ref but need _Name variables)
const dependencySchemas: Record<string, SchemaInfo> = {}
for (const name of allReferencedNames) {
const schemaDef = schema.components?.schemas?.[name]
if (!schemaDef) continue
const schemaRef = schemaDef as
| OpenAPIV3_1.SchemaObject
| OpenAPIV3_1.ReferenceObject
dependencySchemas[name] = {
code: schemaToZod(schemaRef, schema, schemaRefs),
type: schemaToZodType(schemaRef, schema),
}
}
return {
requestSchemas,
responseSchemas,
errorSchemas,
dependencySchemas,
pathMappings,
}
}
// =============================================================================
// Main Generator Function
// =============================================================================
/**
* Generate Zod schema code from OpenAPI documents
*
* @param schemas - Map of server names to OpenAPI documents
* @param options - Generator options
* @returns Generated JavaScript/TypeScript code string
*/
export function generateZodSchemas(
schemas: Record<string, OpenAPIV3_1.Document>,
options?: DevupApiTypeGeneratorOptions,
): string {
const serverSchemas: Record<string, CollectedSchemas> = {}
for (const [originalServerName, schema] of Object.entries(schemas)) {
const normalizedServerName = normalizeServerName(originalServerName)
serverSchemas[normalizedServerName] = generateSchemasForDocument(
schema,
normalizedServerName,
options,
)
}
// Generate the output code
const lines: string[] = ['import { z } from "zod";', '']
// Generate schema definitions for each server
for (const [serverName, collected] of Object.entries(serverSchemas)) {
const safeServerName = serverName.replace(/[^a-zA-Z0-9]/g, '_')
// Dependency schemas (referenced via $ref, need _Name variables for z.lazy)
if (Object.keys(collected.dependencySchemas).length > 0) {
lines.push(`// Shared dependency schemas for ${serverName}`)
for (const [name, schemaInfo] of Object.entries(
collected.dependencySchemas,
)) {
lines.push(`const _${name} = ${schemaInfo.code};`)
}
lines.push('')
}
// Request schemas
if (Object.keys(collected.requestSchemas).length > 0) {
lines.push(`// Request schemas for ${serverName}`)
for (const [name, schemaInfo] of Object.entries(
collected.requestSchemas,
)) {
lines.push(
`const ${safeServerName}_request_${name} = ${schemaInfo.code};`,
)
}
lines.push('')
}
// Response schemas
if (Object.keys(collected.responseSchemas).length > 0) {
lines.push(`// Response schemas for ${serverName}`)
for (const [name, schemaInfo] of Object.entries(
collected.responseSchemas,
)) {
lines.push(
`const ${safeServerName}_response_${name} = ${schemaInfo.code};`,
)
}
lines.push('')
}
// Error schemas
if (Object.keys(collected.errorSchemas).length > 0) {
lines.push(`// Error schemas for ${serverName}`)
for (const [name, schemaInfo] of Object.entries(collected.errorSchemas)) {
lines.push(
`const ${safeServerName}_error_${name} = ${schemaInfo.code};`,
)
}
lines.push('')
}
}
// Generate exports
lines.push('// Exported schemas')
// Build schemas object for each server
for (const [serverName, collected] of Object.entries(serverSchemas)) {
const safeServerName = serverName.replace(/[^a-zA-Z0-9]/g, '_')
// Request schemas object
const requestEntries = Object.keys(collected.requestSchemas)
.map(
(name) =>
` ${wrapInterfaceKeyGuard(name)}: ${safeServerName}_request_${name}`,
)
.join(',\n')
lines.push(`export const ${safeServerName}_requestSchemas = {`)
lines.push(requestEntries || '')
lines.push('};')
lines.push('')
// Response schemas object
const responseEntries = Object.keys(collected.responseSchemas)
.map(
(name) =>
` ${wrapInterfaceKeyGuard(name)}: ${safeServerName}_response_${name}`,
)
.join(',\n')
lines.push(`export const ${safeServerName}_responseSchemas = {`)
lines.push(responseEntries || '')
lines.push('};')
lines.push('')
// Error schemas object
const errorEntries = Object.keys(collected.errorSchemas)
.map(
(name) =>
` ${wrapInterfaceKeyGuard(name)}: ${safeServerName}_error_${name}`,
)
.join(',\n')
lines.push(`export const ${safeServerName}_errorSchemas = {`)
lines.push(errorEntries || '')
lines.push('};')
lines.push('')
// Path schemas object (maps path/operationId to request schema)
const methods = ['post', 'put', 'patch', 'delete'] as const
for (const method of methods) {
const pathEntries: string[] = []
const methodMappings = collected.pathMappings[method]
for (const [pathKey, mapping] of Object.entries(methodMappings)) {
if (
mapping.schemaName &&
collected.requestSchemas[mapping.schemaName]
) {
pathEntries.push(
` ${wrapInterfaceKeyGuard(pathKey)}: ${safeServerName}_request_${mapping.schemaName}`,
)
}
}
if (pathEntries.length > 0) {
lines.push(`export const ${safeServerName}_${method}PathSchemas = {`)
lines.push(pathEntries.join(',\n'))
lines.push('};')
lines.push('')
} else {
lines.push(`export const ${safeServerName}_${method}PathSchemas = {};`)
lines.push('')
}
}
}
// Generate combined schemas export
const serverNames = Object.keys(serverSchemas)
if (serverNames.length === 1) {
// Single server - export directly
const safeServerName = (serverNames[0] as string).replace(
/[^a-zA-Z0-9]/g,
'_',
)
lines.push('export const schemas = {')
lines.push(` request: ${safeServerName}_requestSchemas,`)
lines.push(` response: ${safeServerName}_responseSchemas,`)
lines.push(` error: ${safeServerName}_errorSchemas,`)
lines.push('};')
lines.push('')
lines.push(
`export const requestSchemas = ${safeServerName}_requestSchemas;`,
)
lines.push(
`export const responseSchemas = ${safeServerName}_responseSchemas;`,
)
lines.push(`export const errorSchemas = ${safeServerName}_errorSchemas;`)
lines.push('')
lines.push('// Path to schema mappings')
lines.push(
`export const postPathSchemas = ${safeServerName}_postPathSchemas;`,
)
lines.push(
`export const putPathSchemas = ${safeServerName}_putPathSchemas;`,
)
lines.push(
`export const patchPathSchemas = ${safeServerName}_patchPathSchemas;`,
)
lines.push(
`export const deletePathSchemas = ${safeServerName}_deletePathSchemas;`,
)
lines.push('')
lines.push('export const pathSchemas = {')
lines.push(' post: postPathSchemas,')
lines.push(' put: putPathSchemas,')
lines.push(' patch: patchPathSchemas,')
lines.push(' delete: deletePathSchemas,')
lines.push('};')
} else {
// Multiple servers - export as nested object
lines.push('export const schemas = {')
for (const serverName of serverNames) {
const safeServerName = serverName.replace(/[^a-zA-Z0-9]/g, '_')
lines.push(` ${wrapInterfaceKeyGuard(serverName)}: {`)
lines.push(` request: ${safeServerName}_requestSchemas,`)
lines.push(` response: ${safeServerName}_responseSchemas,`)
lines.push(` error: ${safeServerName}_errorSchemas,`)
lines.push(' },')
}
lines.push('};')
// Also export flat versions for single-server convenience
if (serverNames.length > 0) {
const defaultServer = serverNames[0] as string
const safeDefaultServer = defaultServer.replace(/[^a-zA-Z0-9]/g, '_')
lines.push('')
lines.push('// Default server exports (first server)')
lines.push(
`export const requestSchemas = ${safeDefaultServer}_requestSchemas;`,
)
lines.push(
`export const responseSchemas = ${safeDefaultServer}_responseSchemas;`,
)
lines.push(
`export const errorSchemas = ${safeDefaultServer}_errorSchemas;`,
)
lines.push('')
lines.push('// Path to schema mappings (first server)')
lines.push(
`export const postPathSchemas = ${safeDefaultServer}_postPathSchemas;`,
)
lines.push(
`export const putPathSchemas = ${safeDefaultServer}_putPathSchemas;`,
)
lines.push(
`export const patchPathSchemas = ${safeDefaultServer}_patchPathSchemas;`,
)
lines.push(
`export const deletePathSchemas = ${safeDefaultServer}_deletePathSchemas;`,
)
lines.push('')
lines.push('export const pathSchemas = {')
lines.push(' post: postPathSchemas,')
lines.push(' put: putPathSchemas,')
lines.push(' patch: patchPathSchemas,')
lines.push(' delete: deletePathSchemas,')
lines.push('};')
}
}
return lines.join('\n')
}
/**
* Generate Zod schema type declarations for module augmentation
*/
export function generateZodTypeDeclarations(
schemas: Record<string, OpenAPIV3_1.Document>,
options?: DevupApiTypeGeneratorOptions,
): string {
const serverSchemas: Record<string, CollectedSchemas> = {}
for (const [originalServerName, schema] of Object.entries(schemas)) {
const normalizedServerName = normalizeServerName(originalServerName)
serverSchemas[normalizedServerName] = generateSchemasForDocument(
schema,
normalizedServerName,
options,
)
}
const lines: string[] = [
'import "@devup-api/zod";',
'import type { z } from "zod";',
'',
'declare module "@devup-api/zod" {',
]
// Generate interface declarations for each server
for (const [serverName, collected] of Object.entries(serverSchemas)) {
// Request schemas interface
if (Object.keys(collected.requestSchemas).length > 0) {
lines.push(` interface DevupZodRequestSchemas {`)
lines.push(` ${wrapInterfaceKeyGuard(serverName)}: {`)
for (const [name, schemaInfo] of Object.entries(
collected.requestSchemas,
)) {
lines.push(` ${wrapInterfaceKeyGuard(name)}: ${schemaInfo.type};`)
}
lines.push(' };')
lines.push(' }')
lines.push('')
}
// Response schemas interface
if (Object.keys(collected.responseSchemas).length > 0) {
lines.push(` interface DevupZodResponseSchemas {`)
lines.push(` ${wrapInterfaceKeyGuard(serverName)}: {`)
for (const [name, schemaInfo] of Object.entries(
collected.responseSchemas,
)) {
lines.push(` ${wrapInterfaceKeyGuard(name)}: ${schemaInfo.type};`)
}
lines.push(' };')
lines.push(' }')
lines.push('')
}
// Error schemas interface
if (Object.keys(collected.errorSchemas).length > 0) {
lines.push(` interface DevupZodErrorSchemas {`)
lines.push(` ${wrapInterfaceKeyGuard(serverName)}: {`)
for (const [name, schemaInfo] of Object.entries(collected.errorSchemas)) {
lines.push(` ${wrapInterfaceKeyGuard(name)}: ${schemaInfo.type};`)
}
lines.push(' };')
lines.push(' }')
lines.push('')
}
}
lines.push('}')
return lines.join('\n')
}