/
schema.js
505 lines (491 loc) Β· 15 KB
/
schema.js
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
// @flow strict-local
import ThrowableDiagnostic, {
generateJSONCodeHighlights,
escapeMarkdown,
encodeJSONKeyComponent,
} from '@parcel/diagnostic';
import type {Mapping} from 'json-source-map';
import nullthrows from 'nullthrows';
// flowlint-next-line untyped-import:off
import levenshtein from 'fastest-levenshtein';
export type SchemaEntity =
| SchemaObject
| SchemaArray
| SchemaBoolean
| SchemaString
| SchemaNumber
| SchemaEnum
| SchemaOneOf
| SchemaAllOf
| SchemaNot
| SchemaAny;
export type SchemaArray = {|
type: 'array',
items?: SchemaEntity,
__type?: string,
|};
export type SchemaBoolean = {|
type: 'boolean',
__type?: string,
|};
export type SchemaOneOf = {|
oneOf: Array<SchemaEntity>,
|};
export type SchemaAllOf = {|
allOf: Array<SchemaEntity>,
|};
export type SchemaNot = {|
not: SchemaEntity,
__message: string,
|};
export type SchemaString = {|
type: 'string',
enum?: Array<string>,
__validate?: (val: string) => ?string,
__type?: string,
|};
export type SchemaNumber = {|
type: 'number',
enum?: Array<number>,
__type?: string,
|};
export type SchemaEnum = {|
enum: Array<mixed>,
|};
export type SchemaObject = {|
type: 'object',
properties: {[string]: SchemaEntity, ...},
additionalProperties?: boolean | SchemaEntity,
required?: Array<string>,
__forbiddenProperties?: Array<string>,
__type?: string,
|};
export type SchemaAny = {||};
export type SchemaError =
| {|
type: 'type',
expectedTypes: Array<string>,
dataType: ?'key' | 'value',
dataPath: string,
ancestors: Array<SchemaEntity>,
prettyType?: string,
|}
| {|
type: 'enum',
expectedValues: Array<mixed>,
dataType: 'key' | 'value',
actualValue: mixed,
dataPath: string,
ancestors: Array<SchemaEntity>,
prettyType?: string,
|}
| {|
type: 'forbidden-prop',
prop: string,
expectedProps: Array<string>,
actualProps: Array<string>,
dataType: 'key',
dataPath: string,
ancestors: Array<SchemaEntity>,
prettyType?: string,
|}
| {|
type: 'missing-prop',
prop: string,
expectedProps: Array<string>,
actualProps: Array<string>,
dataType: 'key' | 'value',
dataPath: string,
ancestors: Array<SchemaEntity>,
prettyType?: string,
|}
| {|
type: 'other',
actualValue: mixed,
dataType: ?'key' | 'value',
message?: string,
dataPath: string,
ancestors: Array<SchemaEntity>,
|};
function validateSchema(schema: SchemaEntity, data: mixed): Array<SchemaError> {
function walk(
schemaAncestors,
dataNode,
dataPath,
): ?SchemaError | Array<SchemaError> {
let [schemaNode] = schemaAncestors;
if (schemaNode.type) {
let type = Array.isArray(dataNode) ? 'array' : typeof dataNode;
if (schemaNode.type !== type) {
return {
type: 'type',
dataType: 'value',
dataPath,
expectedTypes: [schemaNode.type],
ancestors: schemaAncestors,
prettyType: schemaNode.__type,
};
} else {
switch (schemaNode.type) {
case 'array': {
if (schemaNode.items) {
let results: Array<SchemaError | Array<SchemaError>> = [];
// $FlowFixMe type was already checked
for (let i = 0; i < dataNode.length; i++) {
let result = walk(
[schemaNode.items].concat(schemaAncestors),
// $FlowFixMe type was already checked
dataNode[i],
dataPath + '/' + i,
);
if (result) results.push(result);
}
if (results.length)
return results.reduce((acc, v) => acc.concat(v), []);
}
break;
}
case 'string': {
// $FlowFixMe type was already checked
let value: string = dataNode;
if (schemaNode.enum) {
if (!schemaNode.enum.includes(value)) {
return {
type: 'enum',
dataType: 'value',
dataPath,
expectedValues: schemaNode.enum,
actualValue: value,
ancestors: schemaAncestors,
};
}
} else if (schemaNode.__validate) {
let validationError = schemaNode.__validate(value);
if (typeof validationError == 'string') {
return {
type: 'other',
dataType: 'value',
dataPath,
message: validationError,
actualValue: value,
ancestors: schemaAncestors,
};
}
}
break;
}
case 'number': {
// $FlowFixMe type was already checked
let value: number = dataNode;
if (schemaNode.enum) {
if (!schemaNode.enum.includes(value)) {
return {
type: 'enum',
dataType: 'value',
dataPath,
expectedValues: schemaNode.enum,
actualValue: value,
ancestors: schemaAncestors,
};
}
}
break;
}
case 'object': {
let results: Array<Array<SchemaError> | SchemaError> = [];
let invalidProps;
if (schemaNode.__forbiddenProperties) {
// $FlowFixMe type was already checked
let keys = Object.keys(dataNode);
invalidProps = schemaNode.__forbiddenProperties.filter(val =>
keys.includes(val),
);
results.push(
...invalidProps.map(
k =>
({
type: 'forbidden-prop',
dataPath: dataPath + '/' + encodeJSONKeyComponent(k),
dataType: 'key',
prop: k,
expectedProps: Object.keys(schemaNode.properties),
actualProps: keys,
ancestors: schemaAncestors,
}: SchemaError),
),
);
}
if (schemaNode.required) {
// $FlowFixMe type was already checked
let keys = Object.keys(dataNode);
let missingKeys = schemaNode.required.filter(
val => !keys.includes(val),
);
results.push(
...missingKeys.map(
k =>
({
type: 'missing-prop',
dataPath,
dataType: 'value',
prop: k,
expectedProps: schemaNode.required,
actualProps: keys,
ancestors: schemaAncestors,
}: SchemaError),
),
);
}
if (schemaNode.properties) {
let {additionalProperties = true} = schemaNode;
// $FlowFixMe type was already checked
for (let k in dataNode) {
if (invalidProps && invalidProps.includes(k)) {
// Don't check type on forbidden props
continue;
} else if (k in schemaNode.properties) {
let result = walk(
[schemaNode.properties[k]].concat(schemaAncestors),
// $FlowFixMe type was already checked
dataNode[k],
dataPath + '/' + encodeJSONKeyComponent(k),
);
if (result) results.push(result);
} else {
if (typeof additionalProperties === 'boolean') {
if (!additionalProperties) {
results.push({
type: 'enum',
dataType: 'key',
dataPath: dataPath + '/' + encodeJSONKeyComponent(k),
expectedValues: Object.keys(
schemaNode.properties,
).filter(
// $FlowFixMe type was already checked
p => !(p in dataNode),
),
actualValue: k,
ancestors: schemaAncestors,
prettyType: schemaNode.__type,
});
}
} else {
let result = walk(
[additionalProperties].concat(schemaAncestors),
// $FlowFixMe type was already checked
dataNode[k],
dataPath + '/' + encodeJSONKeyComponent(k),
);
if (result) results.push(result);
}
}
}
}
if (results.length)
return results.reduce((acc, v) => acc.concat(v), []);
break;
}
case 'boolean':
// NOOP, type was checked already
break;
default:
throw new Error(`Unimplemented schema type ${type}?`);
}
}
} else {
if (schemaNode.enum && !schemaNode.enum.includes(dataNode)) {
return {
type: 'enum',
dataType: 'value',
dataPath: dataPath,
expectedValues: schemaNode.enum,
actualValue: schemaNode,
ancestors: schemaAncestors,
};
}
if (schemaNode.oneOf || schemaNode.allOf) {
let list = schemaNode.oneOf || schemaNode.allOf;
let results: Array<SchemaError | Array<SchemaError>> = [];
for (let f of list) {
let result = walk([f].concat(schemaAncestors), dataNode, dataPath);
if (result) results.push(result);
}
if (
schemaNode.oneOf
? results.length == schemaNode.oneOf.length
: results.length > 0
) {
// return the result with more values / longer key
results.sort((a, b) =>
Array.isArray(a) || Array.isArray(b)
? Array.isArray(a) && !Array.isArray(b)
? -1
: !Array.isArray(a) && Array.isArray(b)
? 1
: Array.isArray(a) && Array.isArray(b)
? b.length - a.length
: 0
: b.dataPath.length - a.dataPath.length,
);
return results[0];
}
} else if (schemaNode.not) {
let result = walk(
[schemaNode.not].concat(schemaAncestors),
dataNode,
dataPath,
);
if (!result || result.length == 0) {
return {
type: 'other',
dataPath,
dataType: null,
message: schemaNode.__message,
actualValue: dataNode,
ancestors: schemaAncestors,
};
}
}
}
return undefined;
}
let result = walk([schema], data, '');
return Array.isArray(result) ? result : result ? [result] : [];
}
export default validateSchema;
export function fuzzySearch(
expectedValues: Array<string>,
actualValue: string,
): Array<string> {
let result = expectedValues
.map(exp => [exp, levenshtein.distance(exp, actualValue)])
.filter(
// Remove if more than half of the string would need to be changed
([, d]) => d * 2 < actualValue.length,
);
result.sort(([, a], [, b]) => a - b);
return result.map(([v]) => v);
}
validateSchema.diagnostic = function (
schema: SchemaEntity,
data: {|
...
| {|
source?: ?string,
data?: mixed,
|}
| {|
source: string,
map: {|
data: mixed,
pointers: {|[key: string]: Mapping|},
|},
|},
filePath?: ?string,
prependKey?: ?string,
|},
origin: string,
message: string,
): void {
if (
'source' in data &&
'data' in data &&
typeof data.source !== 'string' &&
!data
) {
throw new Error(
'At least one of data.source and data.data must be defined!',
);
}
let object = data.map
? data.map.data
: // $FlowFixMe we can assume it's a JSON object
data.data ?? JSON.parse(data.source);
let errors = validateSchema(schema, object);
if (errors.length) {
let keys = errors.map(e => {
let message;
if (e.type === 'enum') {
let {actualValue} = e;
let expectedValues = e.expectedValues.map(String);
let likely =
actualValue != null
? fuzzySearch(expectedValues, String(actualValue))
: [];
if (likely.length > 0) {
message = `Did you mean ${likely
.map(v => JSON.stringify(v))
.join(', ')}?`;
} else if (expectedValues.length > 0) {
message = `Possible values: ${expectedValues
.map(v => JSON.stringify(v))
.join(', ')}`;
} else {
message = 'Unexpected value';
}
} else if (e.type === 'forbidden-prop') {
let {prop, expectedProps, actualProps} = e;
let likely = fuzzySearch(expectedProps, prop).filter(
v => !actualProps.includes(v),
);
if (likely.length > 0) {
message = `Did you mean ${likely
.map(v => JSON.stringify(v))
.join(', ')}?`;
} else {
message = 'Unexpected property';
}
} else if (e.type === 'missing-prop') {
let {prop, actualProps} = e;
let likely = fuzzySearch(actualProps, prop);
if (likely.length > 0) {
message = `Did you mean ${JSON.stringify(prop)}?`;
e.dataPath += '/' + likely[0];
e.dataType = 'key';
} else {
message = `Missing property ${prop}`;
}
} else if (e.type === 'type') {
if (e.prettyType != null) {
message = `Expected ${e.prettyType}`;
} else {
message = `Expected type ${e.expectedTypes.join(', ')}`;
}
} else {
message = e.message;
}
return {key: e.dataPath, type: e.dataType, message};
});
let map, code;
if (data.map) {
map = data.map;
code = data.source;
} else {
// $FlowFixMe we can assume that data is valid JSON
map = data.source ?? JSON.stringify(nullthrows(data.data), 0, '\t');
code = map;
}
let codeFrames = [
{
filePath: data.filePath ?? undefined,
language: 'json',
code,
codeHighlights: generateJSONCodeHighlights(
map,
keys.map(({key, type, message}) => ({
key: (data.prependKey ?? '') + key,
type: type,
message: message != null ? escapeMarkdown(message) : message,
})),
),
},
];
throw new ThrowableDiagnostic({
diagnostic: {
message: message,
origin,
codeFrames,
},
});
}
};