-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidate.ts
418 lines (385 loc) · 12.1 KB
/
validate.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
import { isRFC3339 } from "./_rfc3339.ts";
import {
isDiscriminatorForm,
isElementsForm,
isEnumForm,
isPropertiesForm,
isRefForm,
isTypeForm,
isValuesForm,
Schema,
} from "./schema.ts";
/**
* ValidationConfig represents options you can pass to [validate](#validate).
*/
export interface ValidationConfig {
/**
* maxDepth is the maximum number of `ref`s to recursively follow before
* [validate](#validate) throws [MaxDepthExceededError](#MaxDepthExceededError).
*
* If maxDepth is zero, then no maximum depth will be enforced.
* [validate](#validate) will recursively follow `ref`s indefinitely, potentially
* causing a stack overflow.
*
* By default, maxDepth is zero.
*/
maxDepth: number;
/**
* maxErrors is the maximum number of errors to return from [validate](#validate).
*
* If maxErrors is positive, [validate](#validate) may return fewer errors than
* maxErrors, but it will never return more than maxErrors.
*
* If maxErrors is zero, [validate](#validate) will return all validation errors.
*
* By default, maxErrors is zero.
*/
maxErrors: number;
}
/**
* MaxDepthExceededError is the error returned if
* [ValidationConfig](#ValidationConfig)maxDepth} is exceeded during [validate](#validate).
*/
export class MaxDepthExceededError extends Error {}
class MaxErrorsReachedError extends Error {}
/**
* ValidationError represents a JSON Typedef validation error.
*
* In terms of the formal JSON Typedef specification, ValidationError
* corresponds to a JSON Typedef error "indicator". ValidationError is *not* a
* subclass of Error. It is just a plain old TypeScript interface.
*
* Both elements of ValidationError are meant to be used as the path segments of
* an [RFC6901 JSON Pointer](https://tools.ietf.org/html/rfc6901). This package
* does not provide an implementation of JSON Pointers for you, and you may
* choose to not use JSON Pointers at all.
*/
export interface ValidationError {
/**
* instancePath is the path to a part of the instance, or "input", that was
* rejected.
*/
instancePath: string[];
/**
* schemaPath is the path to the part of the schema that rejected the input.
*/
schemaPath: string[];
}
/**
* validate performs JSON Typedef validation of an instance (or "input") against
* a JSON Typedef schema, returning a standardized set of errors.
*
* This function may throw [MaxDepthExceededError](#MaxDepthExceededError) if you have configured
* a [ValidationConfig](#ValidationConfig)maxDepth}. If you do not configure such a maxDepth,
* then this function may cause a stack overflow. That's because of
* circularly-defined schemas like this one:
*
* ```json
* {
* "ref": "loop",
* "definitions": {
* "loop": { "ref": "loop" }
* }
* }
* ```
*
* If your schema is not circularly defined like this, then there is no risk for
* validate to overflow the stack.
*
* If you are only interested in a certain number of error messages, consider
* using [ValidationConfig](#ValidationConfig)maxErrors} to get better performance. For
* instance, if all you care about is whether the input is OK or if it has
* errors, you may want to set maxErrors to 1.
*
* @param schema The schema to validate data against
* @param instance The "input" to validate
* @param config Validation options. Optional.
*/
export function validate(
schema: Schema,
instance: unknown,
config?: ValidationConfig,
): ValidationError[] {
const state = {
errors: [],
instanceTokens: [],
schemaTokens: [[]],
root: schema,
config: config || { maxDepth: 0, maxErrors: 0 },
};
try {
validateWithState(state, schema, instance);
} catch (err) {
if (err instanceof MaxErrorsReachedError) {
// MaxErrorsReachedError is just a dummy error to abort further
// validation. The contents of state.errors are what we need to return.
} else {
// This is a genuine error. Let's re-throw it.
throw err;
}
}
return state.errors;
}
interface ValidationState {
errors: ValidationError[];
instanceTokens: string[];
schemaTokens: string[][];
root: Schema;
config: ValidationConfig;
}
function validateWithState(
state: ValidationState,
schema: Schema,
instance: unknown,
parentTag?: string,
) {
if (schema.nullable && instance === null) {
return;
}
if (isRefForm(schema)) {
if (state.schemaTokens.length === state.config.maxDepth) {
throw new MaxDepthExceededError();
}
// The ref form is the only case where we push a new array onto
// schemaTokens; we maintain a separate stack for each reference.
state.schemaTokens.push(["definitions", schema.ref]);
validateWithState(state, state.root.definitions![schema.ref], instance);
state.schemaTokens.pop();
} else if (isTypeForm(schema)) {
pushSchemaToken(state, "type");
switch (schema.type) {
case "boolean":
if (typeof instance !== "boolean") {
pushError(state);
}
break;
case "float32":
case "float64":
if (typeof instance !== "number") {
pushError(state);
}
break;
case "int8":
validateInt(state, instance, -128, 127);
break;
case "uint8":
validateInt(state, instance, 0, 255);
break;
case "int16":
validateInt(state, instance, -32768, 32767);
break;
case "uint16":
validateInt(state, instance, 0, 65535);
break;
case "int32":
validateInt(state, instance, -2147483648, 2147483647);
break;
case "uint32":
validateInt(state, instance, 0, 4294967295);
break;
case "string":
if (typeof instance !== "string") {
pushError(state);
}
break;
case "timestamp":
if (typeof instance !== "string") {
pushError(state);
} else {
if (!isRFC3339(instance)) {
pushError(state);
}
}
break;
}
popSchemaToken(state);
} else if (isEnumForm(schema)) {
pushSchemaToken(state, "enum");
if (typeof instance !== "string" || !schema.enum.includes(instance)) {
pushError(state);
}
popSchemaToken(state);
} else if (isElementsForm(schema)) {
pushSchemaToken(state, "elements");
if (Array.isArray(instance)) {
for (const [index, subInstance] of instance.entries()) {
pushInstanceToken(state, index.toString());
validateWithState(state, schema.elements, subInstance);
popInstanceToken(state);
}
} else {
pushError(state);
}
popSchemaToken(state);
} else if (isPropertiesForm(schema)) {
// JSON has six basic types of data (null, boolean, number, string,
// array, object). Of their standard JS countparts, three have a
// `typeof` of "object": null, array, and object.
//
// This check attempts to check if something is "really" an object.
if (
typeof instance === "object" &&
instance !== null &&
!Array.isArray(instance)
) {
if (schema.properties !== undefined) {
pushSchemaToken(state, "properties");
for (const [name, subSchema] of Object.entries(schema.properties)) {
pushSchemaToken(state, name);
// deno-lint-ignore no-prototype-builtins
if (instance.hasOwnProperty(name)) {
pushInstanceToken(state, name);
// deno-lint-ignore no-explicit-any
validateWithState(state, subSchema, (instance as any)[name]);
popInstanceToken(state);
} else {
pushError(state);
}
popSchemaToken(state);
}
popSchemaToken(state);
}
if (schema.optionalProperties !== undefined) {
pushSchemaToken(state, "optionalProperties");
for (
const [name, subSchema] of Object.entries(
schema.optionalProperties,
)
) {
pushSchemaToken(state, name);
// deno-lint-ignore no-prototype-builtins
if (instance.hasOwnProperty(name)) {
pushInstanceToken(state, name);
// deno-lint-ignore no-explicit-any
validateWithState(state, subSchema, (instance as any)[name]);
popInstanceToken(state);
}
popSchemaToken(state);
}
popSchemaToken(state);
}
if (schema.additionalProperties !== true) {
for (const name of Object.keys(instance)) {
const inRequired = schema.properties && name in schema.properties;
const inOptional = schema.optionalProperties &&
name in schema.optionalProperties;
if (!inRequired && !inOptional && name !== parentTag) {
pushInstanceToken(state, name);
pushError(state);
popInstanceToken(state);
}
}
}
} else {
if (schema.properties !== undefined) {
pushSchemaToken(state, "properties");
} else {
pushSchemaToken(state, "optionalProperties");
}
pushError(state);
popSchemaToken(state);
}
} else if (isValuesForm(schema)) {
pushSchemaToken(state, "values");
// See comment in properties form on why this is the test we use for
// checking for objects.
if (
typeof instance === "object" &&
instance !== null &&
!Array.isArray(instance)
) {
for (const [name, subInstance] of Object.entries(instance)) {
pushInstanceToken(state, name);
validateWithState(state, schema.values, subInstance);
popInstanceToken(state);
}
} else {
pushError(state);
}
popSchemaToken(state);
} else if (isDiscriminatorForm(schema)) {
// See comment in properties form on why this is the test we use for
// checking for objects.
if (
typeof instance === "object" &&
instance !== null &&
!Array.isArray(instance)
) {
// deno-lint-ignore no-prototype-builtins
if (instance.hasOwnProperty(schema.discriminator)) {
// deno-lint-ignore no-explicit-any
const tag = (instance as any)[schema.discriminator];
if (typeof tag === "string") {
if (tag in schema.mapping) {
pushSchemaToken(state, "mapping");
pushSchemaToken(state, tag);
validateWithState(
state,
schema.mapping[tag],
instance,
schema.discriminator,
);
popSchemaToken(state);
popSchemaToken(state);
} else {
pushSchemaToken(state, "mapping");
pushInstanceToken(state, schema.discriminator);
pushError(state);
popInstanceToken(state);
popSchemaToken(state);
}
} else {
pushSchemaToken(state, "discriminator");
pushInstanceToken(state, schema.discriminator);
pushError(state);
popInstanceToken(state);
popSchemaToken(state);
}
} else {
pushSchemaToken(state, "discriminator");
pushError(state);
popSchemaToken(state);
}
} else {
pushSchemaToken(state, "discriminator");
pushError(state);
popSchemaToken(state);
}
}
}
function validateInt(
state: ValidationState,
instance: unknown,
min: number,
max: number,
) {
if (
typeof instance !== "number" ||
!Number.isInteger(instance) ||
instance < min ||
instance > max
) {
pushError(state);
}
}
function pushInstanceToken(state: ValidationState, token: string) {
state.instanceTokens.push(token);
}
function popInstanceToken(state: ValidationState) {
state.instanceTokens.pop();
}
function pushSchemaToken(state: ValidationState, token: string) {
state.schemaTokens[state.schemaTokens.length - 1].push(token);
}
function popSchemaToken(state: ValidationState) {
state.schemaTokens[state.schemaTokens.length - 1].pop();
}
function pushError(state: ValidationState) {
state.errors.push({
instancePath: [...state.instanceTokens],
schemaPath: [...state.schemaTokens[state.schemaTokens.length - 1]],
});
if (state.errors.length === state.config.maxErrors) {
throw new MaxErrorsReachedError();
}
}