-
Notifications
You must be signed in to change notification settings - Fork 13
/
type-generator.ts
432 lines (352 loc) · 13.3 KB
/
type-generator.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
import { JSONSchema4, JSONSchema4Type } from "json-schema";
import { CodeMaker, toPascalCase } from "codemaker";
import { constantCase } from "change-case";
export interface TypeGeneratorOptions {
exclude?: string[];
}
export interface GeneratedConstruct {
readonly fqn: string;
readonly kind: string;
readonly schema: JSONSchema4;
}
export class TypeGenerator {
private readonly typesToEmit: { [name: string]: (code: CodeMaker) => void } = {};
private readonly emittedTypes = new Set<string>();
constructor(private readonly schema: JSONSchema4) { }
public emitConstruct(def: GeneratedConstruct) {
this.emitLater(def.kind, code => {
const schema = def.schema;
const optionsStructName = `${toPascalCase(def.kind)}Options`;
const options = createOptionsStructSchema();
this.emitType(optionsStructName, options, def.fqn)
emitConstruct();
function createOptionsStructSchema() {
const copy: JSONSchema4 = { ...def.schema };
copy.required = copy.required || [];
copy.required = copy.required.filter(x => x !== 'apiVersion' && x !== 'kind' && x !== 'status');
return copy;
}
function emitConstruct() {
code.line('/**');
code.line(` * ${def.schema.description}`);
code.line(` *`);
code.line(` * @schema ${def.fqn}`)
code.line(` */`);
code.openBlock(`export class ${toPascalCase(def.kind)} extends ArmResource`);
emitInitializer();
code.closeBlock();
}
function emitInitializer() {
code.line(`/**`);
code.line(` * Defines a "${def.fqn}" Arm Template object`);
code.line(` * @param scope the scope in which to define this object`);
code.line(` * @param name a scope-local name for the object`);
code.line(` * @param options configuration options`);
code.line(` */`);
const hasRequired = schema.required && Array.isArray(schema.required) && schema.required.length > 0;
const defaultOptions = hasRequired ? '' : ' = {}';
code.openBlock(`public constructor(scope: Construct, name: string, options: ${optionsStructName}${defaultOptions})`);
emitInitializerSuper();
code.closeBlock();
}
function emitInitializerSuper() {
code.open(`super(scope, name, {`);
code.line(`...options,`);
code.line(`armResourceType: '${def.kind}',`);
code.close(`});`);
}
});
}
public emitType(typeName: string, def: JSONSchema4, structFqn: string): string {
typeName = normalizeTypeName(typeName);
if (def.$ref) {
return this.typeForRef(def);
}
// unions
if (def.oneOf || def.anyOf) {
const foo = def.oneOf || def.anyOf
if (foo === undefined) {
throw new Error("undefined shouldn't happen here")
}
const reducer = (accumulator: JSONSchema4[], type: JSONSchema4) => {
if (type.$ref && type.$ref.match(/expression$/)) {
return accumulator
} else {
accumulator.push(type)
}
return accumulator
}
const cleanTypes = foo.reduce(reducer, [])
if (cleanTypes.length > 1) {
// console.log({ cleanTypes })
this.emitUnion(typeName, def, structFqn)
return typeName;
} else {
return this.typeForProperty(typeName, cleanTypes[0])
}
}
if (def.type === 'string' && def.format === 'date-time') {
return `Date`;
}
switch (def.type) {
case undefined: return 'string';
case 'boolean': return 'boolean';
case 'array': return `${this.typeForArray(typeName, def)}[]`;
case 'any': return 'any';
case 'null': return 'any';
}
if (def.type === 'number' || def.type === 'integer') {
return 'number';
}
if (def.type === 'string') {
if (def.format === 'date-time') {
return 'Date';
}
if (def.pattern) {
let cleanTypeName = typeName
if (typeName.match("#")) {
const parts = typeName.split("#") || []
cleanTypeName = (parts[1] || '').substr('/definitions/'.length);
}
// console.log({ cleanTypeName })
this.emitPattern(`${toPascalCase(cleanTypeName)}Pattern`, def, structFqn)
return `${toPascalCase(cleanTypeName)}Pattern`
}
if (def.enum) {
let cleanTypeName = typeName
if (typeName.match("#")) {
const parts = typeName.split("#") || []
cleanTypeName = (parts[1] || '').substr('/definitions/'.length);
}
// console.log({ cleanTypeName })
return this.emitEnum(`${toPascalCase(cleanTypeName)}`, def.enum)
}
return 'string';
}
if (Array.isArray(def.type)) {
return 'any';
}
if (def.type !== 'object') {
throw new Error(`unexpected schema type ${def.type}. Expecting "object"`);
}
// map
if (!def.properties && def.additionalProperties && typeof (def.additionalProperties) === 'object') {
return `{ [key: string]: ${this.typeForProperty(typeName, def.additionalProperties)} }`;
}
// struct
if (def.properties) {
const parts = typeName.split("#") || [];
if (parts.length > 1) {
const cleanTypeName = toPascalCase(
(parts[1] || "").substr("/definitions/".length)
);
this.emitStruct(cleanTypeName, def, structFqn);
return cleanTypeName;
} else {
const cleanTypeName = toPascalCase(parts[0]);
this.emitStruct(cleanTypeName, def, structFqn);
return cleanTypeName;
}
}
return 'any';
}
public generate(code: CodeMaker) {
while (Object.keys(this.typesToEmit).length) {
const name = Object.keys(this.typesToEmit)[0];
const emitter = this.typesToEmit[name];
emitter(code);
code.line();
delete this.typesToEmit[name];
this.emittedTypes.add(name);
}
}
private emitLater(typeName: string, codeEmitter: (code: CodeMaker) => void) {
if (this.emittedTypes.has(typeName)) {
return;
}
this.typesToEmit[typeName] = codeEmitter;
}
private emitUnion(typeName: string, def: JSONSchema4, fqn: string) {
this.emitLater(typeName, code => {
this.emitDescription(code, fqn, def.description);
let list = ''
code.openBlock(`export class ${typeName}`);
for (const option of def.oneOf || def.anyOf || []) {
if (!option.enum && option.type === 'array') list = '[]';
let type = ''
if (option.$ref) {
type = this.typeForRef(option);
} else if (option.enum) {
let cleanTypeName = typeName
if (typeName.match("#")) {
const parts = typeName.split("#") || []
cleanTypeName = (parts[1] || '').substr('/definitions/'.length);
}
type = this.emitEnum(`${cleanTypeName}`, option.enum)
} else if (!option.enum && option.type === 'array') {
if (!option.items) type = 'any';
const items = option.items as any
if (items.$ref) {
type = this.typeForRef(items);
} else if (items.type) {
type = items.type
}
else {
type = 'any'
}
} else if (option.properties) {
type = typeName + def.oneOf?.indexOf(option)
this.emitStruct(type, option, `${type}`)
} else if (Array.isArray(option.type) || option.required) {
type = 'any'
} else {
if (option.type) {
type = option.type === 'integer' ? 'number' : option.type as string;
} else {
type = 'any'
}
}
const methodName = 'from' + type[0].toUpperCase() + type.substr(1);
code.openBlock(`public static ${methodName}(value: ${type}${list}): ${typeName}`);
code.line(`return new ${typeName}(value);`);
code.closeBlock();
}
code.openBlock(`private constructor(value: any)`);
code.line(`Object.defineProperty(this, 'resolve', { value: () => value });`);
code.closeBlock();
code.closeBlock();
});
}
private emitEnum(typeName: string, values: JSONSchema4Type[]) {
this.emitLater(typeName, code => {
code.openBlock(`export enum ${typeName}`);
values.forEach((v) => {
const validName = `${v}`.match(/^([a-zA-Z_])+$/) ? constantCase(`${v}`) : `"${typeName}_${constantCase(`${v}`)}"`
// console.log({ validName })
code.line(`${validName} = '${v}',`)
})
code.closeBlock();
});
return typeName
}
// { type: 'string',
// pattern: '^\\[([^\\[].*)?\\]$',
// description:
// 'Deployment template expression. See https://aka.ms/arm-template-expressions for more details on the ARM expression syntax.' }
private emitPattern(typeName: string, structDef: JSONSchema4, structFqn: string) {
this.emitLater(typeName, code => {
this.emitDescription(code, structFqn, structDef.description);
code.openBlock(`export class ${typeName}`);
code.openBlock(`public static pattern(value: string): string`);
code.line(`return value;`);
code.closeBlock();
code.closeBlock();
});
}
private emitStruct(typeName: string, structDef: JSONSchema4, structFqn: string) {
// console.log({ struct: typeName })
this.emitLater(typeName, code => {
this.emitDescription(code, structFqn, structDef.description);
code.openBlock(`export interface ${typeName}`);
for (const [propName, propSpec] of Object.entries(structDef.properties || {})) {
if (propName.startsWith('x-')) {
continue; // skip extensions for now
}
this.emitProperty(code, propName, propSpec, structFqn, structDef);
}
code.closeBlock();
});
}
private emitProperty(code: CodeMaker, name: string, propDef: JSONSchema4, structFqn: string, structDef: JSONSchema4) {
const originalName = name;
// if name is not camelCase, convert it to camel case, but this is likely to
// produce invalid output during synthesis, so add some annotation to the docs.
if (name[0] === name[0].toUpperCase()) {
name = code.toCamelCase(name);
}
// if the name starts with '$' (like $ref or $schema), we remove the "$"
// and it's the same deal - will produce invalid output
if (name.startsWith('$')) {
name = name.substring(1);
}
this.emitDescription(code, `${structFqn}#${originalName}`, propDef.description);
const propertyType = this.typeForProperty(`${structFqn}.${name}`, propDef);
const required = this.isPropertyRequired(name, structDef);
const optional = required ? '' : '?';
code.line(`readonly ${name}${optional}: ${propertyType};`);
code.line();
}
private emitDescription(code: CodeMaker, fqn: string, description?: string, annotations: { [type: string]: string } = {}) {
code.line('/**');
if (description) {
description = description.replace(/\*\//g, '_/');
const extractDefault = /Defaults?\W+(to|is)\W+(.+)/g.exec(description);
const def = extractDefault && extractDefault[2];
code.line(` * ${description}`);
if (def) {
annotations['default'] = def;
}
code.line(' *');
}
annotations['schema'] = fqn;
for (const [type, value] of Object.entries(annotations)) {
code.line(` * @${type} ${value}`);
}
code.line(' */')
}
private typeForProperty(propertyFqn: string, def: JSONSchema4): string {
const subtype = propertyFqn.split('.').map(x => toPascalCase(x)).join('');
return this.emitType(subtype, def, subtype);
}
private typeForRef(def: JSONSchema4): string {
if (!def.$ref) return 'any';
const parts = def.$ref?.split("#") || []
const typeName = (parts[1] || '').substr('/definitions/'.length);
// console.log({ ref: typeName })
const schema = this.resolveReference(def);
return this.emitType(typeName, schema, def.$ref);
}
private typeForArray(propertyFqn: string, def: JSONSchema4): string {
if (!def.items || typeof (def.items) !== 'object') {
return 'any';
// throw new Error(`unsupported array type ${def.items}`);
}
return this.typeForProperty(propertyFqn, def.items);
}
private resolveReference(def: JSONSchema4): JSONSchema4 {
const ref = def.$ref;
let found = undefined;
if (!ref) {
throw new Error('no reference found')
}
const parts = ref?.split("#") || []
const schema = this.schema
const lookup = (parts[1] || '').substr('/definitions/'.length);
if (!schema.definitions) {
throw new Error(`schema does not have "definitions"`);
}
found = schema.definitions[lookup];
if (!found) {
throw new Error(`cannot resolve local reference ${ref}`);
}
return found;
}
private isPropertyRequired(property: string, structDef: JSONSchema4) {
return Array.isArray(structDef.required) && structDef.required.includes(property);
}
}
function normalizeTypeName(typeName: string) {
if (!typeName.startsWith('I')) { // avoid the regex
return typeName;
}
// if the type name starts with IXXXFoo then make XXX lowercase because we assume
// it's an acromym that starts with an I, and this will be identified as an interface by JSII.
const re = /^I([A-Z]+)([A-Z][a-z]+[A-Za-z]+)$/.exec(typeName);
if (!re) {
return typeName;
}
const group1 = re[1];
const rest = re[2];
const normalized = `I${group1.toLocaleLowerCase()}${rest}`;
return normalized;
}