-
Notifications
You must be signed in to change notification settings - Fork 6
/
zod.go
505 lines (416 loc) · 12.8 KB
/
zod.go
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
package supervillain
import (
"encoding/json"
"fmt"
"reflect"
"regexp"
"sort"
"strings"
)
type Option interface {
apply(c *Converter)
}
type strictCustomSchemasOption bool
func (s strictCustomSchemasOption) apply(c *Converter) {
c.strictCustomSchemas = bool(s)
}
func WithStrictCustomSchemas(s bool) Option {
return strictCustomSchemasOption(s)
}
func NewConverter(custom map[string]CustomFn, opts ...Option) Converter {
c := Converter{
prefix: "",
outputs: make(map[string]entry),
custom: custom,
}
for _, opt := range opts {
opt.apply(&c)
}
return c
}
func (c *Converter) Convert(input interface{}) string {
t := reflect.TypeOf(input)
c.addSchema(t.Name(), c.convertStructTopLevel(t))
output := strings.Builder{}
sorted := []entry{}
for _, ent := range c.outputs {
sorted = append(sorted, ent)
}
sort.Sort(ByOrder(sorted))
for _, ent := range sorted {
output.WriteString(ent.data)
output.WriteString("\n\n")
}
return output.String()
}
func (c *Converter) ConvertSlice(inputs []interface{}) string {
for _, input := range inputs {
t := reflect.TypeOf(input)
c.addSchema(t.Name(), c.convertStructTopLevel(t))
}
output := strings.Builder{}
sorted := []entry{}
for _, ent := range c.outputs {
sorted = append(sorted, ent)
}
sort.Sort(ByOrder(sorted))
for _, ent := range sorted {
output.WriteString(ent.data)
output.WriteString("\n\n")
}
return output.String()
}
func StructToZodSchema(input interface{}, opts ...Option) string {
c := Converter{
prefix: "",
outputs: make(map[string]entry),
}
for _, opt := range opts {
opt.apply(&c)
}
t := reflect.TypeOf(input)
c.addSchema(t.Name(), c.convertStructTopLevel(t))
output := strings.Builder{}
sorted := []entry{}
for _, ent := range c.outputs {
sorted = append(sorted, ent)
}
sort.Sort(ByOrder(sorted))
for _, ent := range sorted {
output.WriteString(ent.data)
output.WriteString("\n\n")
}
return output.String()
}
func StructToZodSchemaWithPrefix(prefix string, input interface{}, opts ...Option) string {
c := Converter{
prefix: prefix,
outputs: make(map[string]entry),
}
for _, opt := range opts {
opt.apply(&c)
}
t := reflect.TypeOf(input)
c.addSchema(t.Name(), c.convertStructTopLevel(t))
output := strings.Builder{}
sorted := []entry{}
for _, ent := range c.outputs {
sorted = append(sorted, ent)
}
sort.Sort(ByOrder(sorted))
for _, ent := range sorted {
output.WriteString(ent.data)
output.WriteString("\n\n")
}
return output.String()
}
var typeMapping = map[reflect.Kind]string{
reflect.Bool: "boolean",
reflect.Int: "number",
reflect.Int8: "number",
reflect.Int16: "number",
reflect.Int32: "number",
reflect.Int64: "number",
reflect.Uint: "number",
reflect.Uint8: "number",
reflect.Uint16: "number",
reflect.Uint32: "number",
reflect.Uint64: "number",
reflect.Uintptr: "number",
reflect.Float32: "number",
reflect.Float64: "number",
reflect.Complex64: "number",
reflect.Complex128: "number",
reflect.String: "string",
reflect.Interface: "any",
}
type entry struct {
order int
data string
}
type ByOrder []entry
func (a ByOrder) Len() int { return len(a) }
func (a ByOrder) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByOrder) Less(i, j int) bool { return a[i].order < a[j].order }
type CustomFn func(*Converter, reflect.Type, string, string, int) string
type Converter struct {
prefix string
structs int
outputs map[string]entry
custom map[string]CustomFn
strictCustomSchemas bool
}
func (c *Converter) addSchema(name string, data string) {
//First check if the object already exists. If it does do not replace. This is needed for second order
_, ok := c.outputs[name]
if !ok {
order := c.structs
c.outputs[name] = entry{order, data}
c.structs = order + 1
}
}
func schemaName(prefix, name string) string {
return fmt.Sprintf("%s%sSchema", prefix, name)
}
func fieldName(input reflect.StructField) string {
if json := input.Tag.Get("json"); json != "" {
args := strings.Split(json, ",")
if len(args[0]) > 0 {
return args[0]
}
// This is also valid:
// json:",omitempty"
// so in this case, args[0] will be empty, so fall through to using the
// raw field name.
}
// When Golang marshals a struct to JSON and it doesn't have any JSON tags
// that give the fields names, it defaults to just using the field's name.
return input.Name
}
func typeName(t reflect.Type) string {
if t.Kind() == reflect.Struct {
return t.Name()
}
if t.Kind() == reflect.Ptr {
return typeName(t.Elem())
}
if t.Kind() == reflect.Slice {
return typeName(t.Elem())
}
if t.Kind() == reflect.Map {
return typeName(t.Elem())
}
return "UNKNOWN"
}
func (c *Converter) convertStructTopLevel(t reflect.Type) string {
output := strings.Builder{}
name := t.Name()
output.WriteString(fmt.Sprintf(
`export const %s = %s
`,
schemaName(c.prefix, name), c.convertStruct(t, 0)))
output.WriteString(fmt.Sprintf(`export type %s%s = z.infer<typeof %s%sSchema>`,
c.prefix, name, c.prefix, name))
return output.String()
}
func (c *Converter) convertStruct(input reflect.Type, indent int) string {
output := strings.Builder{}
output.WriteString(`z.object({
`)
c.convertStructFields(&output, input, indent+1, make(map[string]string))
output.WriteString(indentation(indent))
output.WriteString(`})`)
return output.String()
}
func (c *Converter) convertStructFields(output *strings.Builder, structType reflect.Type, indent int, fields map[string]string) {
for i := 0; i < structType.NumField(); i++ {
field := structType.Field(i)
shouldInlineField := structType.Name() == "" && field.Anonymous || field.Tag.Get("json") == ",inline"
if shouldInlineField {
inlineStruct := field.Type
if inlineStruct.Kind() == reflect.Ptr {
inlineStruct = inlineStruct.Elem()
}
c.convertStructFields(output, inlineStruct, indent, fields)
} else {
name := fieldName(field)
if name == "-" || fields[name] != "" {
continue
}
optional := isOptional(field)
nullable := isNullable(field)
line := c.convertField(field, indent, optional, nullable)
output.WriteString(line)
fields[name] = line
}
}
}
var matchGenericTypeName = regexp.MustCompile(`(.+)\[(.+)\]`)
// checking it a reflected type is a generic isn't supported as far as I can see
// so this simple check looks for a `[` character in the type name: `T1[T2]`.
func isGeneric(t reflect.Type) bool {
return strings.Contains(t.Name(), "[")
}
// gets the full name and if it's a generic type, strips out the [T] part.
func getFullName(t reflect.Type) (string, string) {
var typename string
var generic string
if isGeneric(t) {
m := matchGenericTypeName.FindAllStringSubmatch(t.Name(), 1)[0]
typename = m[1]
generic = m[2]
} else {
typename = t.Name()
}
return fmt.Sprintf("%s.%s", t.PkgPath(), typename), generic
}
type ConstantSchema interface {
ZodSchema() string
}
type DynamicSchema interface {
ZodSchema(c *Converter, t reflect.Type, name, generic string, indent int) string
}
type DynamicFunctionSchema interface {
ZodSchema(convert func(t reflect.Type, name string, indent int) string, t reflect.Type, name, generic string, indent int) string
}
func (c *Converter) isCustom(t reflect.Type) bool {
fullName, _ := getFullName(t)
_, inMap := c.custom[fullName]
ptrT := reflect.PointerTo(t)
return (inMap ||
t.Implements(reflect.TypeOf((*ConstantSchema)(nil)).Elem())) ||
t.Implements(reflect.TypeOf((*DynamicSchema)(nil)).Elem()) ||
t.Implements(reflect.TypeOf((*DynamicFunctionSchema)(nil)).Elem()) ||
ptrT.Implements(reflect.TypeOf((*ConstantSchema)(nil)).Elem()) ||
ptrT.Implements(reflect.TypeOf((*DynamicSchema)(nil)).Elem()) ||
ptrT.Implements(reflect.TypeOf((*DynamicFunctionSchema)(nil)).Elem())
}
func (c *Converter) handleCustomType(t reflect.Type, name string, indent int) (string, bool) {
fullName, generic := getFullName(t)
custom, ok := c.custom[fullName]
if ok {
return custom(c, t, name, generic, indent), true
}
switch v := reflect.Zero(t).Interface().(type) {
case ConstantSchema:
return v.ZodSchema(), true
case DynamicSchema:
return v.ZodSchema(c, t, name, generic, indent), true
case DynamicFunctionSchema:
return v.ZodSchema(c.ConvertType, t, name, generic, indent), true
}
switch v := reflect.Zero(reflect.PointerTo(t)).Interface().(type) {
case ConstantSchema:
return v.ZodSchema(), true
case DynamicSchema:
return v.ZodSchema(c, t, name, generic, indent), true
case DynamicFunctionSchema:
return v.ZodSchema(c.ConvertType, t, name, generic, indent), true
}
if _, ok := t.MethodByName("ZodSchema"); ok {
panic(fmt.Sprint("found a ZodSchema method with unexpected signature on type: ", fullName))
}
return "", false
}
func (c *Converter) ConvertType(t reflect.Type, name string, indent int) string {
if t.Kind() == reflect.Ptr {
inner := t.Elem()
return c.ConvertType(inner, name, indent)
}
if custom, ok := c.handleCustomType(t, name, indent); ok {
return custom
}
fullName, _ := getFullName(t)
if fullName == "time.Time" {
// timestamps are serialised to strings.
return "z.string()"
}
if c.strictCustomSchemas &&
(t.Implements(reflect.TypeOf((*json.Marshaler)(nil)).Elem()) ||
reflect.PointerTo(t).Implements(reflect.TypeOf((*json.Marshaler)(nil)).Elem())) {
panic(fmt.Sprint("found type with custom marshalling but no custom schema: ", fullName))
}
if t.Kind() == reflect.Slice {
if t.Elem().Kind() == reflect.Uint8 {
// Per https://pkg.go.dev/encoding/json#Marshal, []byte is marshalled as a
// base64-encoded string.
return "z.string()"
}
return fmt.Sprintf(
"%s.array()",
c.ConvertType(t.Elem(), name, indent))
}
if t.Kind() == reflect.Struct {
// Handle nested un-named structs - these are inline.
if t.Name() == "" {
return c.convertStruct(t, indent)
} else {
c.addSchema(name, c.convertStructTopLevel(t))
return schemaName(c.prefix, name)
}
}
if t.Kind() == reflect.Map {
return c.convertMap(t, name, indent)
}
ztype, ok := typeMapping[t.Kind()]
if !ok {
panic(fmt.Sprint("cannot handle: ", t.Kind()))
}
return fmt.Sprintf("z.%s()", ztype)
}
func (c *Converter) convertField(f reflect.StructField, indent int, optional, nullable bool) string {
name := fieldName(f)
// fields named `-` are not exported to JSON so don't export zod types
if name == "-" {
return ""
}
// because nullability is processed before custom types, this makes sure
// the custom type has control over nullability.
isCustom := c.isCustom(f.Type)
optionalCall := ""
if optional {
optionalCall = ".optional()"
}
nullableCall := ""
if nullable && !isCustom {
nullableCall = ".nullable()"
}
return fmt.Sprintf(
"%s%s: %s%s%s,\n",
indentation(indent),
name,
c.ConvertType(f.Type, typeName(f.Type), indent),
optionalCall,
nullableCall)
}
func (c *Converter) convertMap(t reflect.Type, name string, indent int) string {
return fmt.Sprintf(`z.record(%s, %s)`,
c.ConvertType(t.Key(), name, indent),
c.ConvertType(t.Elem(), name, indent))
}
func isNullable(field reflect.StructField) bool {
// interfaces are currently exported with "any" type, which already includes "null"
if isInterface(field) {
return false
}
// pointers can be nil, which are mapped to null in JS/TS.
if field.Type.Kind() == reflect.Ptr {
// However, if a pointer field is tagged with "omitempty", it usually cannot be exported as "null"
// since nil is a pointer's empty value.
if isOptional(field) {
// Unless it is a pointer to a slice, a map, a pointer, or an interface
// because values with those types can themselves be nil and will be exported as "null".
k := field.Type.Elem().Kind()
return k == reflect.Ptr || k == reflect.Slice || k == reflect.Map
}
return true
}
// nil slices and maps are exported as null so these types are usually nullable
if field.Type.Kind() == reflect.Slice || field.Type.Kind() == reflect.Map {
// unless the are also optional in which case they are no longer nullable
return !isOptional(field)
}
return false
}
// Checks whether the first non-pointer type is an interface
func isInterface(field reflect.StructField) bool {
t := field.Type
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
return t.Kind() == reflect.Interface
}
func isOptional(field reflect.StructField) bool {
// Non-pointer struct types and direct or indirect interface types should never be optional().
// Struct fields that are themselves structs ignore the "omitempty" tag because
// structs do not have an empty value.
// Interfaces are currently exported with "any" type, which already includes "undefined"
if field.Type.Kind() == reflect.Struct || isInterface(field) {
return false
}
// Otherwise, omitempty zero-values are omitted and are mapped to undefined in JS/TS.
return strings.Contains(field.Tag.Get("json"), "omitempty")
}
func indentation(level int) string {
return strings.Repeat(" ", level*2)
}