forked from bcherny/json-schema-to-typescript
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparser.ts
524 lines (491 loc) · 15.8 KB
/
parser.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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
import {JSONSchema4Type, JSONSchema4TypeName} from 'json-schema'
import {findKey, includes, isPlainObject, map, memoize, omit} from 'lodash'
import {format} from 'util'
import {Options} from './'
import {typesOfSchema} from './typesOfSchema'
import {
AST,
T_ANY,
T_ANY_ADDITIONAL_PROPERTIES,
TInterface,
TInterfaceParam,
TNamedInterface,
TTuple,
T_UNKNOWN,
T_UNKNOWN_ADDITIONAL_PROPERTIES,
TIntersection
} from './types/AST'
import {
getRootSchema,
isPrimitive,
JSONSchema as LinkedJSONSchema,
JSONSchemaWithDefinitions,
NormalizedJSONSchema,
SchemaSchema,
SchemaType
} from './types/JSONSchema'
import {generateName, log, maybeStripDefault, maybeStripNameHints} from './utils'
export type Processed = Map<LinkedJSONSchema, Map<SchemaType, AST>>
export type UsedNames = Set<string>
export function parse(
schema: LinkedJSONSchema | JSONSchema4Type,
options: Options,
keyName?: string,
processed: Processed = new Map(),
usedNames = new Set<string>()
): AST {
if (isPrimitive(schema)) {
return parseLiteral(schema, keyName)
}
const types = typesOfSchema(schema)
if (types.length === 1) {
const ast = parseAsTypeWithCache(schema, types[0], options, keyName, processed, usedNames)
log('blue', 'parser', 'Types:', types, 'Input:', schema, 'Output:', ast)
return ast
}
// Be careful to first process the intersection before processing its params,
// so that it gets first pick for standalone name.
const ast = parseAsTypeWithCache(
{
$id: schema.$id,
allOf: [],
description: schema.description,
title: schema.title
},
'ALL_OF',
options,
keyName,
processed,
usedNames
) as TIntersection
ast.params = types.map(type =>
// We hoist description (for comment) and id/title (for standaloneName)
// to the parent intersection type, so we remove it from the children.
parseAsTypeWithCache(maybeStripNameHints(schema), type, options, keyName, processed, usedNames)
)
log('blue', 'parser', 'Types:', types, 'Input:', schema, 'Output:', ast)
return ast
}
function parseAsTypeWithCache(
schema: LinkedJSONSchema,
type: SchemaType,
options: Options,
keyName?: string,
processed: Processed = new Map(),
usedNames = new Set<string>()
): AST {
// If we've seen this node before, return it.
let cachedTypeMap = processed.get(schema)
if (!cachedTypeMap) {
cachedTypeMap = new Map()
processed.set(schema, cachedTypeMap)
}
const cachedAST = cachedTypeMap.get(type)
if (cachedAST) {
return cachedAST
}
// Cache processed ASTs before they are actually computed, then update
// them in place using set(). This is to avoid cycles.
// TODO: Investigate alternative approaches (lazy-computing nodes, etc.)
const ast = {} as AST
cachedTypeMap.set(type, ast)
// Update the AST in place. This updates the `processed` cache, as well
// as any nodes that directly reference the node.
return Object.assign(ast, parseNonLiteral(schema, type, options, keyName, processed, usedNames))
}
function parseLiteral(schema: JSONSchema4Type, keyName: string | undefined): AST {
return {
keyName,
params: schema,
type: 'LITERAL'
}
}
function parseNonLiteral(
schema: LinkedJSONSchema,
type: SchemaType,
options: Options,
keyName: string | undefined,
processed: Processed,
usedNames: UsedNames
): AST {
const definitions = getDefinitionsMemoized(getRootSchema(schema as any)) // TODO
const keyNameFromDefinition = findKey(definitions, _ => _ === schema)
switch (type) {
case 'ALL_OF':
return {
comment: schema.description,
keyName,
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames),
params: schema.allOf!.map(_ => parse(_, options, undefined, processed, usedNames)),
type: 'INTERSECTION'
}
case 'ANY':
return {
...(options.unknownAny ? T_UNKNOWN : T_ANY),
comment: schema.description,
keyName,
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames)
}
case 'ANY_OF':
return {
comment: schema.description,
keyName,
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames),
params: schema.anyOf!.map(_ => parse(_, options, undefined, processed, usedNames)),
type: 'UNION'
}
case 'BOOLEAN':
return {
comment: schema.description,
keyName,
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames),
type: 'BOOLEAN'
}
case 'CUSTOM_TYPE':
return {
comment: schema.description,
keyName,
params: schema.tsType!,
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames),
type: 'CUSTOM_TYPE'
}
case 'NAMED_ENUM':
return {
comment: schema.description,
keyName,
standaloneName: standaloneName(schema, keyNameFromDefinition ?? keyName, usedNames)!,
params: schema.enum!.map((_, n) => ({
ast: parseLiteral(_, undefined),
keyName: schema.tsEnumNames![n]
})),
type: 'ENUM'
}
case 'NAMED_SCHEMA':
return newInterface(schema as SchemaSchema, options, processed, usedNames, keyName)
case 'NULL':
return {
comment: schema.description,
keyName,
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames),
type: 'NULL'
}
case 'NUMBER':
return {
comment: schema.description,
keyName,
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames),
type: 'NUMBER'
}
case 'OBJECT':
return {
comment: schema.description,
keyName,
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames),
type: 'OBJECT'
}
case 'ONE_OF':
return {
comment: schema.description,
keyName,
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames),
params: schema.oneOf!.map(_ => parse(_, options, undefined, processed, usedNames)),
type: 'UNION'
}
case 'REFERENCE':
throw Error(format('Refs should have been resolved by the resolver!', schema))
case 'STRING':
return {
comment: schema.description,
keyName,
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames),
type: 'STRING'
}
case 'TYPED_ARRAY':
if (Array.isArray(schema.items)) {
// normalised to not be undefined
const minItems = schema.minItems!
const maxItems = schema.maxItems!
const arrayType: TTuple = {
comment: schema.description,
keyName,
maxItems,
minItems,
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames),
params: schema.items.map(_ => parse(_, options, undefined, processed, usedNames)),
type: 'TUPLE'
}
if (schema.additionalItems === true) {
arrayType.spreadParam = options.unknownAny ? T_UNKNOWN : T_ANY
} else if (schema.additionalItems) {
arrayType.spreadParam = parse(schema.additionalItems, options, undefined, processed, usedNames)
}
return arrayType
} else {
return {
comment: schema.description,
keyName,
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames),
params: parse(schema.items!, options, undefined, processed, usedNames),
type: 'ARRAY'
}
}
case 'UNION':
return {
comment: schema.description,
keyName,
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames),
params: (schema.type as JSONSchema4TypeName[]).map(type => {
const member: LinkedJSONSchema = {...omit(schema, '$id', 'description', 'title'), type}
return parse(maybeStripDefault(member as any), options, undefined, processed, usedNames)
}),
type: 'UNION'
}
case 'UNNAMED_ENUM':
return {
comment: schema.description,
keyName,
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames),
params: schema.enum!.map(_ => parseLiteral(_, undefined)),
type: 'UNION'
}
case 'UNNAMED_SCHEMA':
return newInterface(schema as SchemaSchema, options, processed, usedNames, keyName, keyNameFromDefinition)
case 'UNTYPED_ARRAY':
// normalised to not be undefined
const minItems = schema.minItems!
const maxItems = typeof schema.maxItems === 'number' ? schema.maxItems : -1
const params = options.unknownAny ? T_UNKNOWN : T_ANY
if (minItems > 0 || maxItems >= 0) {
return {
comment: schema.description,
keyName,
maxItems: schema.maxItems,
minItems,
// create a tuple of length N
params: Array(Math.max(maxItems, minItems) || 0).fill(params),
// if there is no maximum, then add a spread item to collect the rest
spreadParam: maxItems >= 0 ? undefined : params,
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames),
type: 'TUPLE'
}
}
return {
comment: schema.description,
keyName,
params,
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames),
type: 'ARRAY'
}
}
}
/**
* Compute a schema name using a series of fallbacks
*/
function standaloneName(
schema: LinkedJSONSchema,
keyNameFromDefinition: string | undefined,
usedNames: UsedNames
): string | undefined {
const name = schema.title || schema.$id || keyNameFromDefinition
if (name) {
return generateName(name, usedNames)
}
}
function newInterface(
schema: SchemaSchema,
options: Options,
processed: Processed,
usedNames: UsedNames,
keyName?: string,
keyNameFromDefinition?: string
): TInterface | TIntersection {
let complexAdditionalProperties: false | NormalizedJSONSchema
if (schema.additionalProperties !== undefined && typeof schema.additionalProperties !== 'boolean') {
complexAdditionalProperties = schema.additionalProperties
schema.additionalProperties = false
} else {
complexAdditionalProperties = false
}
const name = standaloneName(schema, keyNameFromDefinition, usedNames)!
const parsedInterface: TInterface = {
comment: schema.description,
keyName,
params: parseSchema(schema, options, processed, usedNames, name),
standaloneName: name,
superTypes: parseSuperTypes(schema, options, processed, usedNames),
type: 'INTERFACE'
}
if (complexAdditionalProperties === false) {
return parsedInterface
} else {
const parsedAdditionalProperties: TInterface = {
params: [
{
ast: parse(complexAdditionalProperties, options, '[k: string]', processed, usedNames),
isPatternProperty: false,
isRequired: true,
isUnreachableDefinition: false,
keyName: '[k: string]'
}
],
superTypes: [],
type: 'INTERFACE'
}
if (parsedInterface.params.length > 0) {
delete parsedInterface.standaloneName
return {
comment: schema.description,
keyName,
standaloneName: name,
params: [parsedInterface, parsedAdditionalProperties],
type: 'INTERSECTION'
}
} else {
// there were only additionalProperties
return {
...parsedAdditionalProperties,
comment: schema.description,
keyName,
standaloneName: name
}
}
}
}
function parseSuperTypes(
schema: SchemaSchema,
options: Options,
processed: Processed,
usedNames: UsedNames
): TNamedInterface[] {
// Type assertion needed because of dereferencing step
// TODO: Type it upstream
const superTypes = schema.extends as SchemaSchema[] | undefined
if (!superTypes) {
return []
}
return superTypes.map(_ => parse(_, options, undefined, processed, usedNames) as TNamedInterface)
}
/**
* Helper to parse schema properties into params on the parent schema's type
*/
function parseSchema(
schema: SchemaSchema,
options: Options,
processed: Processed,
usedNames: UsedNames,
parentSchemaName: string
): TInterfaceParam[] {
let asts: TInterfaceParam[] = map(schema.properties, (value, key: string) => ({
ast: parse(value, options, key, processed, usedNames),
isPatternProperty: false,
isRequired: includes(schema.required || [], key),
isUnreachableDefinition: false,
keyName: key
}))
let singlePatternProperty = false
if (schema.patternProperties) {
// partially support patternProperties. in the case that
// additionalProperties is not set, and there is only a single
// value definition, we can validate against that.
singlePatternProperty = !schema.additionalProperties && Object.keys(schema.patternProperties).length === 1
asts = asts.concat(
map(schema.patternProperties, (value, key: string) => {
const ast = parse(value, options, key, processed, usedNames)
const comment = `This interface was referenced by \`${parentSchemaName}\`'s JSON-Schema definition
via the \`patternProperty\` "${key}".`
ast.comment = ast.comment ? `${ast.comment}\n\n${comment}` : comment
return {
ast,
isPatternProperty: !singlePatternProperty,
isRequired: singlePatternProperty || includes(schema.required || [], key),
isUnreachableDefinition: false,
keyName: singlePatternProperty ? '[k: string]' : key
}
})
)
}
if (options.unreachableDefinitions) {
asts = asts.concat(
map(schema.$defs, (value, key: string) => {
const ast = parse(value, options, key, processed, usedNames)
const comment = `This interface was referenced by \`${parentSchemaName}\`'s JSON-Schema
via the \`definition\` "${key}".`
ast.comment = ast.comment ? `${ast.comment}\n\n${comment}` : comment
return {
ast,
isPatternProperty: false,
isRequired: includes(schema.required || [], key),
isUnreachableDefinition: true,
keyName: key
}
})
)
}
// handle additionalProperties
switch (schema.additionalProperties) {
case undefined:
case true:
if (singlePatternProperty) {
return asts
}
return asts.concat({
ast: options.unknownAny ? T_UNKNOWN_ADDITIONAL_PROPERTIES : T_ANY_ADDITIONAL_PROPERTIES,
isPatternProperty: false,
isRequired: true,
isUnreachableDefinition: false,
keyName: '[k: string]'
})
case false:
return asts
// pass "true" as the last param because in TS, properties
// defined via index signatures are already optional
default:
return asts.concat({
ast: parse(schema.additionalProperties, options, '[k: string]', processed, usedNames),
isPatternProperty: false,
isRequired: true,
isUnreachableDefinition: false,
keyName: '[k: string]'
})
}
}
type Definitions = {[k: string]: LinkedJSONSchema}
function getDefinitions(
schema: LinkedJSONSchema,
isSchema = true,
processed = new Set<LinkedJSONSchema>()
): Definitions {
if (processed.has(schema)) {
return {}
}
processed.add(schema)
if (Array.isArray(schema)) {
return schema.reduce(
(prev, cur) => ({
...prev,
...getDefinitions(cur, false, processed)
}),
{}
)
}
if (isPlainObject(schema)) {
return {
...(isSchema && hasDefinitions(schema) ? schema.$defs : {}),
...Object.keys(schema).reduce<Definitions>(
(prev, cur) => ({
...prev,
...getDefinitions(schema[cur], false, processed)
}),
{}
)
}
}
return {}
}
const getDefinitionsMemoized = memoize(getDefinitions)
/**
* TODO: Reduce rate of false positives
*/
function hasDefinitions(schema: LinkedJSONSchema): schema is JSONSchemaWithDefinitions {
return '$defs' in schema
}