-
Notifications
You must be signed in to change notification settings - Fork 0
/
to-ts-type.ts
498 lines (401 loc) · 14.8 KB
/
to-ts-type.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
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
/* eslint-disable @typescript-eslint/restrict-plus-operands */
import type {
Circular,
CircularRef,
InstanceOf,
SimpleDataType,
Tuple,
} from "@DataTypes/data-types";
import { BaseDataType, StringMatching } from "@DataTypes/data-types";
import { TypeKindNames } from "@DataTypes/type-kind-names";
import type {
AllOf,
AnyDataType,
ArrayOf,
BasicDataType,
Custom,
DataTypeVisitor,
Dict,
Literal,
OneOf,
RecordOf,
RecordOfVisitChild,
SetOf,
} from "@DataTypes/types";
import { Enum, EnumMember } from "@DataTypes/types";
import { TsFileScope } from "@TsTypeGenerator/file-scope";
import { NameGenerator } from "@TsTypeGenerator/name-generator";
import type {
ExternalTypeImport,
TsParsingOptions,
} from "@TsTypeGenerator/parser-options";
import type { TsBuilder } from "@TsTypeGenerator/ts-builder";
import { TsArrayBuilder } from "@TsTypeGenerator/type-builders/array-builder";
import type { TsBaseBuilder } from "@TsTypeGenerator/type-builders/base-builder";
import { TsDictBuilder } from "@TsTypeGenerator/type-builders/dictionary-builder";
import { TsEnumBuilder } from "@TsTypeGenerator/type-builders/enum-builder";
import { TsEnumMemberBuilder } from "@TsTypeGenerator/type-builders/enum-member-builder";
import { TsExternalTypeReference } from "@TsTypeGenerator/type-builders/external-type-reference";
import { TsInstanceOfBuilder } from "@TsTypeGenerator/type-builders/instanceof-builder";
import { TsIntersectionBuilder } from "@TsTypeGenerator/type-builders/intersection-builder";
import { TsLiteralBuilder } from "@TsTypeGenerator/type-builders/literal-builder";
import { TsRecordBuilder } from "@TsTypeGenerator/type-builders/record-builder";
import { TsSetBuilder } from "@TsTypeGenerator/type-builders/set-builder";
import { TsBooleanBuilder } from "@TsTypeGenerator/type-builders/simple-types/boolean-builder";
import { TsFunctionBuilder } from "@TsTypeGenerator/type-builders/simple-types/function-builder";
import { TsNullBuilder } from "@TsTypeGenerator/type-builders/simple-types/null-builder";
import { TsNumberBuilder } from "@TsTypeGenerator/type-builders/simple-types/number-builder";
import { TsStringBuilder } from "@TsTypeGenerator/type-builders/simple-types/string-builder";
import { TsSymbolBuilder } from "@TsTypeGenerator/type-builders/simple-types/symbol-builder";
import { TsUndefinedBuilder } from "@TsTypeGenerator/type-builders/simple-types/undefined-builder";
import { TsUnknownBuilder } from "@TsTypeGenerator/type-builders/simple-types/unknown-builder";
import { TsStringMatchingBuilder } from "@TsTypeGenerator/type-builders/string-matching-builder";
import { TsTupleBuilder } from "@TsTypeGenerator/type-builders/tuple-builder";
import { TsNamedReference } from "@TsTypeGenerator/type-builders/type-reference";
import { TsUnionBuilder } from "@TsTypeGenerator/type-builders/union-builder";
import { capitalize } from "@Utilities/capitalize";
export class ExternalTypeImportProxy {
private _resolvedName: string;
private _importName: string;
constructor(private ext: ExternalTypeImport) {
if (ext.valueImport == true) {
this._resolvedName = `typeof ${ext.typeName}`;
} else {
this._resolvedName = ext.typeName;
}
if (ext.originalName && ext.originalName !== ext.typeName) {
this._importName = `${ext.originalName} as ${ext.typeName}`;
} else {
this._importName = ext.typeName;
}
}
get path() {
return this.ext.path;
}
get typeName() {
return this._resolvedName;
}
get originalName() {
return this.ext.originalName;
}
get valueImport() {
return this.ext.valueImport;
}
get importName() {
return this._importName;
}
}
type R = TsBuilder;
class DataTypeTsGenerator implements DataTypeVisitor<R> {
fileScope: TsFileScope;
constructor(private options: TsParsingOptions) {
this.fileScope = new TsFileScope(options);
if (options.getExternalTypeImport) {
this.getExternalTypeImport = (type) => {
const ext = options.getExternalTypeImport!(type);
if (ext) {
return new ExternalTypeImportProxy(ext);
}
};
}
// eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check
switch (options.mode) {
case "fully-expanded":
this.addFileExportAndResolveBuilder = function (builder) {
return this.fileScope.addTypeExport(builder);
};
break;
case "named-expanded":
this.addFileExportAndResolveBuilder = function (builder) {
if (builder.isTitled) {
return this.fileScope.addTypeExport(builder);
}
return builder;
};
break;
}
}
private getExternalTypeImport = function (
type: any
): ExternalTypeImportProxy | undefined {
return undefined;
};
/**
* Adds the given builder to the exports of the file scope if
* the builder meets the criteria, and returns the given
* builder or the Reference builder, if the builder was added
* to the exports.
*/
private addFileExportAndResolveBuilder = function (
builder: TsBuilder & TsBaseBuilder
): TsBuilder {
return builder;
// default behavior for compact mode: do nothing
};
private tsAddMetadataToBuilder(builder: TsBaseBuilder, type: AnyDataType) {
const metadata = BaseDataType.getOriginalMetadata(type);
if (metadata.title) {
builder.setIsTitled(true);
builder.setName(metadata.title);
}
if (metadata.description) {
builder.setDescription(metadata.description);
}
return metadata;
}
private parseFunctionType(type: SimpleDataType<"function">) {
const externalImport = this.getExternalTypeImport(type);
if (externalImport) {
this.fileScope.addTypeImport(externalImport);
const builder = new TsExternalTypeReference(externalImport.typeName);
this.tsAddMetadataToBuilder(builder, type);
return this.addFileExportAndResolveBuilder(builder);
}
const builder = new TsFunctionBuilder();
this.tsAddMetadataToBuilder(builder, type);
return builder;
}
private parsePrimitive(type: BasicDataType): R {
let builder: TsBaseBuilder & TsBuilder;
switch (type.simpleType) {
case "string":
case "stringinteger":
case "stringnumeral":
builder = new TsStringBuilder();
break;
case "number":
case "integer":
builder = new TsNumberBuilder();
break;
case "boolean":
builder = new TsBooleanBuilder();
break;
case "symbol":
builder = new TsSymbolBuilder();
break;
case "undefined":
builder = new TsUndefinedBuilder();
break;
case "unknown":
builder = new TsUnknownBuilder();
break;
case "null":
builder = new TsNullBuilder();
break;
case "function":
return this.parseFunctionType(type as any);
}
this.tsAddMetadataToBuilder(builder, type);
return builder;
}
private parseArrayOf(type: ArrayOf, children: Array<R> = []): R {
const builder = new TsArrayBuilder();
this.tsAddMetadataToBuilder(builder, type);
builder.setTypes(children);
return this.addFileExportAndResolveBuilder(builder);
}
private parseTuple(type: Tuple, children: Array<R> = []): R {
const builder = new TsTupleBuilder();
this.tsAddMetadataToBuilder(builder, type);
builder.setTypes(children);
return this.addFileExportAndResolveBuilder(builder);
}
private parseRecordOf(
type: RecordOf,
children: RecordOfVisitChild<R>[] = []
): R {
const builder = new TsRecordBuilder();
this.tsAddMetadataToBuilder(builder, type);
for (let i = 0; i < children?.length; i++) {
const child = children[i];
builder.addProperty(child.propertyName, child.child, child.required);
}
return this.addFileExportAndResolveBuilder(builder);
}
private parseDict(type: Dict, children: Array<R> = []): R {
const builder = new TsDictBuilder();
this.tsAddMetadataToBuilder(builder, type);
builder.setTypes(children);
return this.addFileExportAndResolveBuilder(builder);
}
private parseSetOf(type: SetOf, children: Array<R> = []): R {
const builder = new TsSetBuilder();
this.tsAddMetadataToBuilder(builder, type);
builder.setTypes(children);
return this.addFileExportAndResolveBuilder(builder);
}
private parseOneOf(type: OneOf, children: Array<R>): R {
const builder = new TsUnionBuilder();
this.tsAddMetadataToBuilder(builder, type);
builder.setTypes(children);
return this.addFileExportAndResolveBuilder(builder);
}
private parseAllOf(type: AllOf, children: Array<R>): R {
const builder = new TsIntersectionBuilder();
this.tsAddMetadataToBuilder(builder, type);
builder.setTypes(children);
return this.addFileExportAndResolveBuilder(builder);
}
private parseLiteral(type: Literal): R {
const builder = new TsLiteralBuilder(type.literal);
this.tsAddMetadataToBuilder(builder, type);
return builder;
}
private parseEnum(type: Enum): R {
const metadata = Enum.getOriginalMetadata(type);
let typeName = metadata.enumName;
const externalImport = this.getExternalTypeImport(type);
if (externalImport) {
this.fileScope.addTypeImport(externalImport);
typeName = externalImport.typeName;
}
if (!typeName) {
throw new Error(
"Enum name is not defined. To be able to parse an Enum DataType `enumName` must be defined."
);
}
const builder = new TsEnumBuilder(typeName);
this.tsAddMetadataToBuilder(builder, type);
return builder;
}
private parseEnumMember(type: EnumMember): R {
const metadata = EnumMember.getOriginalMetadata(type);
const externalImport = this.getExternalTypeImport(type);
const typeName = metadata.enumName ?? externalImport?.typeName;
if (!typeName || !metadata.memberName) {
throw new Error(
"Enum name, or enum member name is not defined. To be able to parse an EnumMember DataType into Typescript definition `memberName` and `enumName` must be defined."
);
}
if (externalImport) {
this.fileScope.addTypeImport(externalImport);
}
const builder = new TsEnumMemberBuilder(typeName, metadata.memberName);
this.tsAddMetadataToBuilder(builder, type);
return builder;
}
private parseInstanceOf(type: InstanceOf): R {
const constructor = type.instanceOf as new () => unknown;
let typeName = constructor.name;
const externalImport = this.getExternalTypeImport(type);
if (externalImport) {
this.fileScope.addTypeImport(externalImport);
typeName = externalImport.typeName;
}
const builder = new TsInstanceOfBuilder(typeName);
this.tsAddMetadataToBuilder(builder, type);
if (builder.getName() === typeName) {
builder.setName(`Alias${capitalize(builder.getName()!)}`);
}
return this.addFileExportAndResolveBuilder(builder);
}
private parseCustom(type: Custom): R {
const externalImport = this.getExternalTypeImport(type);
if (externalImport) {
this.fileScope.addTypeImport(externalImport);
const builder = new TsExternalTypeReference(externalImport.typeName);
this.tsAddMetadataToBuilder(builder, type);
return this.addFileExportAndResolveBuilder(builder);
}
const builder = new TsUnknownBuilder();
this.tsAddMetadataToBuilder(builder, type);
return builder;
}
private parseStringMatching(type: StringMatching): R {
const { tsPattern } = StringMatching.getOriginalMetadata(type);
const builder = new TsStringMatchingBuilder(tsPattern);
this.tsAddMetadataToBuilder(builder, type);
return this.addFileExportAndResolveBuilder(builder);
}
private parseCircular(type: Circular, children: R[]): R {
const childType = type.type;
const [actualType] = children;
if (this.circulars.has(childType)) {
const name = this.circulars.get(childType)!;
actualType.setName(name);
return this.fileScope.addTypeExport(actualType as any, name);
}
return actualType;
}
private parseCircularRef(type: CircularRef): R {
const referencedType = type._getReferencedType();
const metadata = BaseDataType.getOriginalMetadata(referencedType);
const title = metadata.title;
if (this.circulars.has(referencedType)) {
return new TsNamedReference(this.circulars.get(referencedType)!);
}
if (title) {
const typeName = NameGenerator.generate(title);
this.circulars.set(referencedType, typeName);
return new TsNamedReference(typeName);
}
const typeName = NameGenerator.generate(
TypeKindNames.get(referencedType.kind) ?? "Circular"
);
this.circulars.set(referencedType, typeName);
return new TsNamedReference(typeName);
}
private circulars: Map<AnyDataType, string> = new Map();
visit(dataType: Exclude<AnyDataType, RecordOf>, children?: R[]): R;
visit(dataType: RecordOf, children?: RecordOfVisitChild<R>[]): R;
visit(type: AnyDataType, children?: (R | RecordOfVisitChild<R>)[]): R {
switch (type.kind) {
case "simple":
return this.parsePrimitive(type);
case "array":
return this.parseArrayOf(type, children as R[]);
case "tuple":
return this.parseTuple(type, children as R[]);
case "record":
return this.parseRecordOf(type, children as RecordOfVisitChild<R>[]);
case "dictionary":
return this.parseDict(type, children as R[]);
case "set":
return this.parseSetOf(type, children as R[]);
case "union":
return this.parseOneOf(type, children as R[]);
case "intersection":
return this.parseAllOf(type, children as R[]);
case "literal":
return this.parseLiteral(type);
case "enumUnion":
return this.parseEnum(type);
case "enumMember":
return this.parseEnumMember(type);
case "instanceOf":
return this.parseInstanceOf(type);
case "custom":
return this.parseCustom(type);
case "stringMatching":
return this.parseStringMatching(type);
case "circular":
return this.parseCircular(type, children as R[]);
case "circularRef":
return this.parseCircularRef(type);
}
}
}
/**
* Generates TypeScript type definition (as a string) from a
* DataType.
*/
export const toTsType = (
dataType: AnyDataType,
options?: Partial<TsParsingOptions>
): string => {
try {
const opt: TsParsingOptions = {
mode: options?.mode ?? "compact",
exports: options?.exports ?? "main",
declaration: options?.declaration ?? false,
onDuplicateName: options?.onDuplicateName ?? "error",
getExternalTypeImport: options?.getExternalTypeImport,
};
const generator = new DataTypeTsGenerator(opt);
const rootBuilder = dataType._acceptVisitor(generator);
generator.fileScope.addRootType(rootBuilder);
return generator.fileScope.build();
} finally {
NameGenerator.clear();
}
};