-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
400 lines (335 loc) · 10.7 KB
/
main.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
package main
import (
"fmt"
"os"
"sort"
"text/template"
"github.com/tada-team/tdproto/codegen"
)
func main() {
tdprotoInfo, err := codegen.ParseTdproto()
if err != nil {
panic(err)
}
if err := generateTypeScript(tdprotoInfo.TdModels); err != nil {
panic(err)
}
}
var tsTypesMap = map[string]string{
"string": "string",
"int": "number",
"int32": "number",
"int64": "number", // TODO: must be string
"uint": "number",
"uint16": "number",
"uint32": "number",
"uint64": "number",
"float": "number",
"float32": "number",
"float64": "number",
"bool": "boolean",
"interface{}": "any",
"ISODateTimeString": "string",
"time.Time": "string",
"UiSettings": "UiSettings",
"UiSettingsData": "UiSettingsData",
}
var tsFieldNameSubstitutions = map[string]string{
"Default": "isDefault",
"New": "isNew",
"Public": "isPublic",
"Static": "isStatic",
}
type TypeScriptSumType struct {
Name string
Values []string
}
type TypeScriptTypeAliasInfo struct {
Name string
BaseType string
}
type TypeScriptFieldInfo struct {
Name string
JsonName string
IsReadOnly bool
IsOmitEmpty bool
TypeName string
IsNotPrimitive bool
IsList bool
Help string
}
type TypeScriptClassInfo struct {
Name string
Fields []TypeScriptFieldInfo
Help string
}
type TypeScriptInfo struct {
Classes []TypeScriptClassInfo
TypesAliases []TypeScriptTypeAliasInfo
SumTypes []TypeScriptSumType
}
func getHelpClass(input string) string {
if input != "" {
return input
} else {
return "MISSING CLASS DOCUMENTATION"
}
}
func getHelpField(input string) string {
if input != "" {
return input
} else {
return "DOCUMENTATION MISSING"
}
}
func convertTdprotoInfoToTypeScript(tdprotoInfo *codegen.TdPackage) (tsInfo TypeScriptInfo, err error) {
var unwrapStructArrays = make(map[string]string)
var enumTypes = make(map[string]string)
for _, tdprotoEnumInfo := range tdprotoInfo.GetEnums() {
var tsEnumValues []string
tsEnumValues = append(tsEnumValues, tdprotoEnumInfo.Values...)
tsInfo.SumTypes = append(tsInfo.SumTypes, TypeScriptSumType{
Name: tdprotoEnumInfo.Name,
Values: tsEnumValues,
})
tsTypesMap[tdprotoEnumInfo.Name] = tdprotoEnumInfo.Name
enumTypes[tdprotoEnumInfo.Name] = ""
}
for _, tdprotoTypeInfo := range tdprotoInfo.TdTypes {
_, isEnum := enumTypes[tdprotoTypeInfo.Name]
if isEnum {
// Enums are handled elsewhere
continue
}
// Unwrap arrays of structs
if tdprotoTypeInfo.IsArray {
unwrapStructArrays[tdprotoTypeInfo.Name] = tdprotoTypeInfo.BaseType
continue
}
typeAliasName := tdprotoTypeInfo.Name
typeAliasBaseType := tsTypesMap[tdprotoTypeInfo.BaseType]
tsNewTypeAlias := TypeScriptTypeAliasInfo{
Name: typeAliasName,
BaseType: typeAliasBaseType,
}
tsInfo.TypesAliases = append(tsInfo.TypesAliases, tsNewTypeAlias)
tsTypesMap[typeAliasName] = typeAliasName
}
for _, tdprotoStructInfo := range tdprotoInfo.TdStructs {
tsNewClass := TypeScriptClassInfo{
Name: codegen.UppercaseFirstLetter(tdprotoStructInfo.Name),
Help: getHelpClass(tdprotoStructInfo.Help),
}
for _, tdprotoStructField := range tdprotoStructInfo.GetAllJsonFields(tdprotoInfo) {
if tdprotoStructField.IsNotSerialized {
continue
}
tsFieldName, isSubstituted := tsFieldNameSubstitutions[tdprotoStructField.Name]
if !isSubstituted {
tsFieldName = codegen.SnakeCaseToLowerCamel(tdprotoStructField.JsonName)
}
isNotPrimitive := false
tsTypeName, ok := tsTypesMap[tdprotoStructField.TypeStr]
if !ok {
tsTypeName = codegen.UppercaseFirstLetter(tdprotoStructField.TypeStr)
isNotPrimitive = true
}
isList := tdprotoStructField.IsList
unwrappedTypeName, doUnwrap := unwrapStructArrays[tsTypeName]
if doUnwrap {
tsTypeName = unwrappedTypeName
isList = true
}
if tdprotoStructField.KeyTypeStr != "" {
tsTypeName = fmt.Sprintf("Record<%s, %s>", tdprotoStructField.KeyTypeStr, tsTypeName)
}
tsNewClass.Fields = append(tsNewClass.Fields, TypeScriptFieldInfo{
Name: tsFieldName,
JsonName: tdprotoStructField.JsonName,
IsReadOnly: tdprotoStructField.IsReadOnly,
IsOmitEmpty: tdprotoStructField.IsOmitEmpty,
TypeName: tsTypeName,
IsNotPrimitive: isNotPrimitive,
IsList: isList,
Help: getHelpField(tdprotoStructField.Help),
})
}
// Put non-optional arguments before optional
sort.Slice(tsNewClass.Fields, func(i, j int) bool {
if tsNewClass.Fields[i].IsOmitEmpty != tsNewClass.Fields[j].IsOmitEmpty {
return !tsNewClass.Fields[i].IsOmitEmpty && tsNewClass.Fields[j].IsOmitEmpty
} else {
return tsNewClass.Fields[i].Name < tsNewClass.Fields[j].Name
}
})
tsInfo.Classes = append(tsInfo.Classes, tsNewClass)
}
// Sort everything by name
sort.Slice(tsInfo.Classes, func(i, j int) bool {
return tsInfo.Classes[i].Name < tsInfo.Classes[j].Name
})
sort.Slice(tsInfo.SumTypes, func(i, j int) bool {
return tsInfo.SumTypes[i].Name < tsInfo.SumTypes[j].Name
})
sort.Slice(tsInfo.TypesAliases, func(i, j int) bool {
return tsInfo.TypesAliases[i].Name < tsInfo.TypesAliases[j].Name
})
return tsInfo, nil
}
func generateTypeScript(tdprotoInfo *codegen.TdPackage) error {
tsInfo, err := convertTdprotoInfoToTypeScript(tdprotoInfo)
if err != nil {
return err
}
_, _ = fmt.Fprint(os.Stdout, tsHeader)
for _, tsSumTypeInfo := range tsInfo.SumTypes {
if err := tsSumTypesTemplate.Execute(os.Stdout, tsSumTypeInfo); err != nil {
return err
}
}
for _, tsTypeAliasInfo := range tsInfo.TypesAliases {
if err := tsTypeTemplate.Execute(os.Stdout, tsTypeAliasInfo); err != nil {
return err
}
}
_, err = fmt.Fprint(os.Stdout, tsManualClasses)
if err != nil {
return nil
}
for _, tsClassInfo := range tsInfo.Classes {
if err := tsInterfaceTemplate.Execute(os.Stdout, tsClassInfo); err != nil {
return err
}
}
return nil
}
const tsHeader = `/* eslint-disable @typescript-eslint/no-use-before-define */
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
/* eslint-disable @typescript-eslint/no-unused-vars */
interface TDProtoClass<T> {
readonly mappableFields: ReadonlyArray<keyof T>;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type UiSettings = Record<string, any>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type UiSettingsData = Record<string, any>
`
const tsManualClasses = `
export interface TeamUnreadJSON {
/* eslint-disable camelcase */
direct: UnreadJSON;
group: UnreadJSON;
task: UnreadJSON;
meeting: UnreadJSON;
thread: UnreadJSON;
/* eslint-enable camelcase */
}
export class TeamUnread implements TDProtoClass<TeamUnread> {
constructor (
public direct: Unread,
public group: Unread,
public task: Unread,
public meeting: Unread,
public thread: Unread,
) {}
public static fromJSON (raw: TeamUnreadJSON): TeamUnread {
return new TeamUnread(
Unread.fromJSON(raw.direct),
Unread.fromJSON(raw.group),
Unread.fromJSON(raw.task),
Unread.fromJSON(raw.meeting),
Unread.fromJSON(raw.thread),
)
}
public mappableFields = [
'direct',
'group',
'task',
'meeting',
'thread',
] as const
readonly #mapper = {
/* eslint-disable camelcase */
direct: () => ({ direct: this.direct.toJSON() }),
group: () => ({ group: this.group.toJSON() }),
task: () => ({ task: this.task.toJSON() }),
meeting: () => ({ meeting: this.meeting.toJSON() }),
thread: () => ({ thread: this.thread.toJSON() }),
/* eslint-enable camelcase */
}
public toJSON (): TeamUnreadJSON
public toJSON (fields: Array<this['mappableFields'][number]>): Partial<TeamUnreadJSON>
public toJSON (fields?: Array<this['mappableFields'][number]>) {
if (fields && fields.length > 0) {
return Object.assign({}, ...fields.map(f => this.#mapper[f]()))
} else {
return Object.assign({}, ...Object.values(this.#mapper).map(v => v()))
}
}
}
`
var tsInterfaceTemplate = template.Must(template.New("tsInterface").Parse(`export interface {{.Name -}}JSON {
/* eslint-disable camelcase */
{{- range $field := .Fields}}
{{- if eq $field.TypeName "any"}}
// eslint-disable-next-line @typescript-eslint/no-explicit-any{{- end}}
{{$field.JsonName}}{{if $field.IsOmitEmpty}}?{{end}}: {{$field.TypeName -}}
{{- if $field.IsNotPrimitive -}}JSON{{end}}
{{- if $field.IsList -}}[]{{end}};{{end}}
/* eslint-enable camelcase */
}
export class {{.Name}} implements TDProtoClass<{{- .Name -}}> {
/**
* {{.Help}}
{{range $field := .Fields}}* @param {{$field.Name}} {{$field.Help}}
{{end}}*/
constructor (
{{- range $field := .Fields}}
{{- if eq $field.TypeName "any"}}
// eslint-disable-next-line @typescript-eslint/no-explicit-any{{- end}}
public {{if $field.IsReadOnly}}readonly {{end}}{{$field.Name}}{{if $field.IsOmitEmpty}}?{{end}}: {{$field.TypeName -}}
{{- if $field.IsList -}}[]{{end}},{{end}}
) {}
public static fromJSON (raw: {{.Name -}}JSON): {{.Name}} {
return new {{.Name -}}(
{{- range $field := .Fields}}
{{- if $field.IsNotPrimitive}}
{{if $field.IsOmitEmpty -}} raw.{{- $field.JsonName}} && {{end}}
{{- if $field.IsList}}raw.{{- $field.JsonName}}.map({{$field.TypeName}}.fromJSON)
{{- else -}} {{- $field.TypeName -}}.fromJSON(raw.{{- $field.JsonName -}}){{end}}
{{- else}}
raw.{{- $field.JsonName -}}
{{- end -}}
,{{end}}
)
}
public mappableFields = [
{{- range $field := .Fields}}
'{{- $field.Name -}}',{{end}}
] as const
readonly #mapper = {
/* eslint-disable camelcase */
{{- range $field := .Fields}}
{{$field.Name -}}: () => ({ {{$field.JsonName -}}: this.{{$field.Name}}
{{- if $field.IsNotPrimitive -}}{{- if $field.IsOmitEmpty}}?{{end}}
{{- if $field.IsList}}.map(u => u.toJSON()){{else}}.toJSON(){{end}}{{end}} }),{{end}}
/* eslint-enable camelcase */
}
public toJSON (): {{.Name -}}JSON
public toJSON (fields: Array<this['mappableFields'][number]>): Partial<{{- .Name -}}JSON>
public toJSON (fields?: Array<this['mappableFields'][number]>) {
if (fields && fields.length > 0) {
return Object.assign({}, ...fields.map(f => this.#mapper[f]()))
} else {
return Object.assign({}, ...Object.values(this.#mapper).map(v => v()))
}
}
}
`))
var tsTypeTemplate = template.Must(template.New("tsType").Parse(`
export type {{.Name}} = {{.BaseType}}
`))
var tsSumTypesTemplate = template.Must(template.New("tsSumTypes").Parse(`export type {{.Name}} =
{{range $value := .Values}} | '{{- $value -}}'
{{end}}
`))