-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
zodOpenApi.impl.ts
438 lines (402 loc) · 12.8 KB
/
zodOpenApi.impl.ts
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
import type { SchemaObject, SchemaObjectType } from 'openapi3-ts/oas31'
import { merge } from 'ts-deepmerge'
import type { AnyZodObject, ZodTypeAny } from 'zod'
import { z } from 'zod'
/**
* Based on package `@anatine/zod-openapi`
* Workaround for recent `openapi3-ts/oas31` behavior
*
* @link https://github.com/anatine/zod-plugins/tree/main/packages/zod-openapi
*/
export interface OpenApiZodAny extends ZodTypeAny {
metaOpenApi?: SchemaObject | SchemaObject[]
}
interface OpenApiZodAnyObject extends AnyZodObject {
metaOpenApi?: SchemaObject | SchemaObject[]
}
interface ParsingArgs<T> {
zodRef: T
schemas: SchemaObject[]
useOutput?: boolean
}
export function extendApi<T extends OpenApiZodAny>(schema: T, SchemaObject: SchemaObject = {}): T {
schema.metaOpenApi = Object.assign(schema.metaOpenApi ?? {}, SchemaObject)
return schema
}
function iterateZodObject({ zodRef, useOutput }: ParsingArgs<OpenApiZodAnyObject>) {
return Object.keys(zodRef.shape).reduce(
(carry, key) => ({
...carry,
[key]: generateSchema(zodRef.shape[key], useOutput),
}),
{} as Record<string, SchemaObject>,
)
}
function parseTransformation({
zodRef,
schemas,
useOutput,
}: ParsingArgs<z.ZodTransformer<never> | z.ZodEffects<never>>): SchemaObject {
const input = generateSchema(zodRef._def.schema, useOutput)
let output = 'undefined'
if (useOutput && zodRef._def.effect) {
const effect = zodRef._def.effect.type === 'transform' ? zodRef._def.effect : null
if (effect && 'transform' in effect) {
try {
output = typeof effect.transform(
['integer', 'number'].includes(`${input.type}`)
? 0
: input.type === 'string'
? ''
: input.type === 'boolean'
? false
: input.type === 'object'
? {}
: input.type === 'null'
? null
: input.type === 'array'
? []
: undefined,
{ addIssue: () => undefined, path: [] }, // TODO: Discover if context is necessary here
)
} catch (e) {
/**/
}
}
}
return merge(
{
...(zodRef.description ? { description: zodRef.description } : {}),
...input,
...(['number', 'string', 'boolean', 'null'].includes(output)
? {
type: output as 'number' | 'string' | 'boolean' | 'null',
}
: {}),
},
...schemas,
)
}
function parseString({ zodRef, schemas }: ParsingArgs<z.ZodString>): SchemaObject {
const baseSchema: SchemaObject = {
type: 'string',
}
const { checks = [] } = zodRef._def
checks.forEach((item) => {
switch (item.kind) {
case 'email':
baseSchema.format = 'email'
break
case 'uuid':
baseSchema.format = 'uuid'
break
case 'cuid':
baseSchema.format = 'cuid'
break
case 'url':
baseSchema.format = 'uri'
break
case 'datetime':
baseSchema.format = 'date-time'
break
case 'length':
baseSchema.minLength = item.value
baseSchema.maxLength = item.value
break
case 'max':
baseSchema.maxLength = item.value
break
case 'min':
baseSchema.minLength = item.value
break
case 'regex':
baseSchema.pattern = item.regex.source
break
}
})
return merge(baseSchema, zodRef.description ? { description: zodRef.description } : {}, ...schemas)
}
function parseNumber({ zodRef, schemas }: ParsingArgs<z.ZodNumber>): SchemaObject {
const baseSchema: SchemaObject = {
type: 'number',
}
const { checks = [] } = zodRef._def
checks.forEach((item) => {
switch (item.kind) {
case 'max':
baseSchema.maximum = item.value
// TODO: option to make this always explicit? (false instead of non-existent)
if (!item.inclusive) {
;(baseSchema.exclusiveMaximum as any) = true
}
break
case 'min':
baseSchema.minimum = item.value
if (!item.inclusive) {
;(baseSchema.exclusiveMinimum as any) = true
}
break
case 'int':
baseSchema.type = 'integer'
break
case 'multipleOf':
baseSchema.multipleOf = item.value
}
})
return merge(baseSchema, zodRef.description ? { description: zodRef.description } : {}, ...schemas)
}
function parseObject({
zodRef,
schemas,
useOutput,
}: ParsingArgs<z.ZodObject<never, 'passthrough' | 'strict' | 'strip'>>): SchemaObject {
let additionalProperties: SchemaObject['additionalProperties']
// `catchall` obviates `strict`, `strip`, and `passthrough`
if (!(zodRef._def.catchall instanceof z.ZodNever || zodRef._def.catchall?._def.typeName === 'ZodNever')) {
additionalProperties = generateSchema(zodRef._def.catchall, useOutput)
} else if (zodRef._def.unknownKeys === 'passthrough') {
additionalProperties = true
} else if (zodRef._def.unknownKeys === 'strict') {
additionalProperties = false
}
// So that `undefined` values don't end up in the schema and be weird
additionalProperties = additionalProperties != null ? { additionalProperties } : {}
const requiredProperties = Object.keys((zodRef as z.AnyZodObject).shape).filter((key) => {
const item = (zodRef as z.AnyZodObject).shape[key]
return (
!(item.isOptional() || item instanceof z.ZodDefault || item._def.typeName === 'ZodDefault') &&
!(item instanceof z.ZodNever || item._def.typeName === 'ZodDefault')
)
})
const required = requiredProperties.length > 0 ? { required: requiredProperties } : {}
return merge(
{
type: 'object' as SchemaObjectType,
properties: iterateZodObject({
zodRef: zodRef as OpenApiZodAnyObject,
schemas,
useOutput,
}),
...required,
...additionalProperties,
},
zodRef.description ? { description: zodRef.description } : {},
...schemas,
)
}
function parseRecord({ zodRef, schemas, useOutput }: ParsingArgs<z.ZodRecord>): SchemaObject {
return merge(
{
type: 'object' as SchemaObjectType,
additionalProperties:
zodRef._def.valueType instanceof z.ZodUnknown ? {} : generateSchema(zodRef._def.valueType, useOutput),
},
zodRef.description ? { description: zodRef.description } : {},
...schemas,
)
}
function parseBigInt({ zodRef, schemas }: ParsingArgs<z.ZodBigInt>): SchemaObject {
return merge(
{ type: 'integer' as SchemaObjectType, format: 'int64' },
zodRef.description ? { description: zodRef.description } : {},
...schemas,
)
}
function parseBoolean({ zodRef, schemas }: ParsingArgs<z.ZodBoolean>): SchemaObject {
return merge(
{ type: 'boolean' as SchemaObjectType },
zodRef.description ? { description: zodRef.description } : {},
...schemas,
)
}
function parseDate({ zodRef, schemas }: ParsingArgs<z.ZodDate>): SchemaObject {
return merge(
{ type: 'string' as SchemaObjectType, format: 'date-time' },
zodRef.description ? { description: zodRef.description } : {},
...schemas,
)
}
function parseNull({ zodRef, schemas }: ParsingArgs<z.ZodNull>): SchemaObject {
return merge(
{
type: 'string' as SchemaObjectType,
format: 'null',
nullable: true,
},
zodRef.description ? { description: zodRef.description } : {},
...schemas,
)
}
function parseOptionalNullable({
schemas,
zodRef,
useOutput,
}: ParsingArgs<z.ZodOptional<OpenApiZodAny> | z.ZodNullable<OpenApiZodAny>>): SchemaObject {
return merge(
generateSchema(zodRef.unwrap(), useOutput),
zodRef.description ? { description: zodRef.description } : {},
...schemas,
)
}
function parseDefault({ schemas, zodRef, useOutput }: ParsingArgs<z.ZodDefault<OpenApiZodAny>>): SchemaObject {
return merge(
{
default: zodRef._def.defaultValue(),
...generateSchema(zodRef._def.innerType, useOutput),
},
zodRef.description ? { description: zodRef.description } : {},
...schemas,
)
}
function parseArray({ schemas, zodRef, useOutput }: ParsingArgs<z.ZodArray<OpenApiZodAny>>): SchemaObject {
const constraints: SchemaObject = {}
if (zodRef._def.exactLength != null) {
constraints.minItems = zodRef._def.exactLength.value
constraints.maxItems = zodRef._def.exactLength.value
}
if (zodRef._def.minLength != null) {
constraints.minItems = zodRef._def.minLength.value
}
if (zodRef._def.maxLength != null) {
constraints.maxItems = zodRef._def.maxLength.value
}
return merge(
{
type: 'array' as SchemaObjectType,
items: generateSchema(zodRef.element, useOutput),
...constraints,
},
zodRef.description ? { description: zodRef.description } : {},
...schemas,
)
}
function parseLiteral({ schemas, zodRef }: ParsingArgs<z.ZodLiteral<OpenApiZodAny>>): SchemaObject {
return merge(
{
type: typeof zodRef._def.value as 'string' | 'number' | 'boolean',
enum: [zodRef._def.value],
},
zodRef.description ? { description: zodRef.description } : {},
...schemas,
)
}
function parseEnum({ schemas, zodRef }: ParsingArgs<z.ZodEnum<never> | z.ZodNativeEnum<never>>): SchemaObject {
return merge(
{
type: typeof Object.values(zodRef._def.values)[0] as 'string' | 'number',
enum: Object.values(zodRef._def.values),
},
zodRef.description ? { description: zodRef.description } : {},
...schemas,
)
}
function parseIntersection({
schemas,
zodRef,
useOutput,
}: ParsingArgs<z.ZodIntersection<z.ZodTypeAny, z.ZodTypeAny>>): SchemaObject {
return merge(
{
allOf: [generateSchema(zodRef._def.left, useOutput), generateSchema(zodRef._def.right, useOutput)],
},
zodRef.description ? { description: zodRef.description } : {},
...schemas,
)
}
function parseUnion({
schemas,
zodRef,
useOutput,
}: ParsingArgs<z.ZodUnion<[z.ZodTypeAny, ...z.ZodTypeAny[]]>>): SchemaObject {
return merge(
{
oneOf: (zodRef as z.ZodUnion<[z.ZodTypeAny, ...z.ZodTypeAny[]]>)._def.options.map((schema) =>
generateSchema(schema, useOutput),
),
},
zodRef.description ? { description: zodRef.description } : {},
...schemas,
)
}
function parseDiscriminatedUnion({
schemas,
zodRef,
useOutput,
}: ParsingArgs<z.ZodDiscriminatedUnion<string, z.ZodDiscriminatedUnionOption<string>[]>>): SchemaObject {
return merge(
{
discriminator: {
propertyName: (zodRef as z.ZodDiscriminatedUnion<string, z.ZodDiscriminatedUnionOption<string>[]>)._def
.discriminator,
},
oneOf: Array.from(
(zodRef as z.ZodDiscriminatedUnion<string, z.ZodDiscriminatedUnionOption<string>[]>)._def.options.values(),
).map((schema) => generateSchema(schema, useOutput)),
},
zodRef.description ? { description: zodRef.description } : {},
...schemas,
)
}
function parseNever({ zodRef, schemas }: ParsingArgs<z.ZodNever>): SchemaObject {
return merge({ readOnly: true }, zodRef.description ? { description: zodRef.description } : {}, ...schemas)
}
function catchAllParser({ zodRef, schemas }: ParsingArgs<ZodTypeAny>): SchemaObject {
return merge(zodRef.description ? { description: zodRef.description } : {}, ...schemas)
}
const workerMap = {
ZodObject: parseObject,
ZodRecord: parseRecord,
ZodString: parseString,
ZodNumber: parseNumber,
ZodBigInt: parseBigInt,
ZodBoolean: parseBoolean,
ZodDate: parseDate,
ZodNull: parseNull,
ZodOptional: parseOptionalNullable,
ZodNullable: parseOptionalNullable,
ZodDefault: parseDefault,
ZodArray: parseArray,
ZodLiteral: parseLiteral,
ZodEnum: parseEnum,
ZodNativeEnum: parseEnum,
ZodTransformer: parseTransformation,
ZodEffects: parseTransformation,
ZodIntersection: parseIntersection,
ZodUnion: parseUnion,
ZodDiscriminatedUnion: parseDiscriminatedUnion,
ZodNever: parseNever,
// TODO Transform the rest to schemas
ZodUndefined: catchAllParser,
// TODO: `prefixItems` is allowed in OpenAPI 3.1 which can be used to create tuples
ZodTuple: catchAllParser,
ZodMap: catchAllParser,
ZodFunction: catchAllParser,
ZodLazy: catchAllParser,
ZodPromise: catchAllParser,
ZodAny: catchAllParser,
ZodUnknown: catchAllParser,
ZodVoid: catchAllParser,
}
type WorkerKeys = keyof typeof workerMap
export function generateSchema(zodRef: OpenApiZodAny, useOutput?: boolean): SchemaObject {
const { metaOpenApi = {} } = zodRef
const schemas = [
zodRef.isNullable && zodRef.isNullable() ? { nullable: true } : {},
...(Array.isArray(metaOpenApi) ? metaOpenApi : [metaOpenApi]),
]
try {
const typeName = zodRef._def.typeName as WorkerKeys
if (typeName in workerMap) {
return workerMap[typeName]({
zodRef: zodRef as never,
schemas,
useOutput,
})
}
return catchAllParser({ zodRef, schemas })
} catch (err) {
// eslint-disable-next-line no-console
console.error(err)
return catchAllParser({ zodRef, schemas })
}
}