-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsvalid.js
462 lines (399 loc) · 12.7 KB
/
jsvalid.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
// jsvalid.js
// James Diacono
// 2024-09-03
// Public Domain
const violation_messages = {
missing_property_a: "Missing property '{a}'.",
not_equal_to_a: "Not equal to '{a}'.",
not_finite: "Not a finite number.",
not_type_a: "Not of type {a}.",
not_wun_of: "Not a valid option.",
object_length: "Wrong number of properties.",
out_of_bounds: "Out of bounds.",
unexpected: "Unexpected.",
unexpected_classification_a: "Unexpected classification '{a}'.",
unexpected_property_a: "Unexpected property '{a}'.",
wrong_pattern: "Wrong pattern."
};
const rx_variable = /\{([^{}]*)\}/g;
function interpolate(template, container) {
return template.replace(rx_variable, function (original, filling) {
try {
return String(container[filling]);
} catch (_) {
// Objects with a null prototype are unprintable. Perhaps other values are too.
return original;
}
});
}
function coalesce(left, right) {
// The nullish coalescing operator (??) as a function, for compatibility with
// older JavaScript engines.
return (
left === undefined
? right
: left
);
}
function make_violation(code, ...exhibits) {
let violation = {
message: interpolate(
violation_messages[code],
{a: exhibits[0]}
),
code
};
if (exhibits.length > 0) {
violation.a = exhibits[0];
}
return violation;
}
function is_object(value) {
return value && typeof value === "object" && !Array.isArray(value);
}
function owns(object, key) {
// This is several orders of magnitude faster than calling
// Object.keys(object).includes(key) when the number of keys is large.
return (
Object.prototype.hasOwnProperty.call(object, key)
&& Object.prototype.propertyIsEnumerable.call(object, key)
);
}
// The validator factories. ////////////////////////////////////////////////////
function type(expected_type) {
return function type_validator(subject) {
const subject_type = typeof subject;
return (
subject_type !== expected_type
? [make_violation("not_type_a", expected_type)]
: []
);
};
}
function any() {
return function any_validator() {
return [];
};
}
function literal(expected) {
return function literal_validator(subject) {
return (
(
subject === expected || (
Number.isNaN(expected) && Number.isNaN(subject)
)
)
? []
: [make_violation("not_equal_to_a", expected)]
);
};
}
function euphemize(value) {
// If 'value' is a not a function, it is wrapped in a "literal" validator.
return (
typeof value === "function"
? value
: literal(value)
);
}
function not(validator) {
return function not_validator(subject) {
return (
euphemize(validator)(subject).length > 0
? []
: [make_violation("unexpected")]
);
};
}
function all_of(validators, exhaustive = false) {
return function all_of_validator(subject) {
let all_violations = [];
validators.some(function (validator) {
const violations = validator(subject);
all_violations = all_violations.concat(violations);
const stop_now = (exhaustive === false && violations.length > 0);
return stop_now;
});
return all_violations;
};
}
function property(key, validator) {
// The 'property' validator applies the 'validator' to the 'key' property of the
// subject. The subject need not be an object, but an exception will be thrown
// if it is null or undefined.
function prepend_key_to_path(violation) {
return Object.assign({}, violation, {
path: (
violation.path === undefined
? [key]
: [key].concat(violation.path)
)
});
}
return function property_validator(subject) {
return euphemize(validator)(subject[key]).map(prepend_key_to_path);
};
}
function wun_of(validators, classifier) {
if (classifier !== undefined) {
return function classified_validator(subject) {
let key;
try {
key = classifier(subject);
} catch (_) {
// The classifier might have made reckless assumptions about the structure of
// the subject, which is perfectly fine.
}
if (
(typeof key === "string" || Number.isFinite(key))
&& owns(validators, String(key))
) {
return euphemize(validators[key])(subject);
}
return [make_violation("unexpected_classification_a", key)];
};
}
return function wun_of_validator(subject) {
// No classifier function was provided. We take a brute force approach, applying
// each validator until wun fits.
let all_violations = [];
return (
validators.map(euphemize).some(function (validator) {
const violations = validator(subject);
all_violations = all_violations.concat(violations);
return violations.length === 0;
})
? []
: [make_violation("not_wun_of"), ...all_violations]
);
};
}
function boolean() {
return type("boolean");
}
function number(
minimum,
maximum,
exclude_minimum = false,
exclude_maximum = false
) {
return all_of([
type("number"),
function number_validator(subject) {
if (!Number.isFinite(subject)) {
return [make_violation("not_finite")];
}
return (
(
(
minimum !== undefined && (
exclude_minimum
? subject <= minimum
: subject < minimum
)
) || (
maximum !== undefined && (
exclude_maximum
? subject >= maximum
: subject > maximum
)
)
)
? [make_violation("out_of_bounds")]
: []
);
}
]);
}
function integer(minimum, maximum) {
return all_of([
function integer_validator(subject) {
return (
!Number.isSafeInteger(subject)
? [make_violation("not_type_a", "integer")]
: []
);
},
number(minimum, maximum)
]);
}
function string(argument) {
return all_of([
type("string"),
(
argument === undefined
? any()
: (
typeof argument.test === "function"
? function pattern_validator(subject) {
return (
argument.test(subject)
? []
: [make_violation("wrong_pattern")]
);
}
: property("length", argument)
)
)
]);
}
function fn(length_validator = any()) {
return all_of([
type("function"),
property("length", length_validator)
]);
}
function array(validator_array, length_validator, rest_validator) {
if (!Array.isArray(validator_array)) {
// The case of a homogenous array is equivalent to that of a heterogeneous array
// with only a "rest" validator.
return array(
[],
coalesce(length_validator, any()),
coalesce(validator_array, any())
);
}
if (length_validator === undefined) {
length_validator = validator_array.length;
}
function validator_at(element_nr) {
// Returns the validator for an element at the specified position in the subject
// array.
return (
element_nr < validator_array.length
? validator_array[element_nr]
: (
rest_validator === undefined
? validator_array[element_nr % validator_array.length]
: rest_validator
)
);
}
return all_of([
function array_validator(subject) {
return (
!Array.isArray(subject)
? [make_violation("not_type_a", "array")]
: []
);
},
property("length", length_validator),
function elements_validator(subject) {
return all_of(
subject.map(function (_, element_nr) {
const validator = euphemize(validator_at(element_nr));
return property(element_nr, validator);
}),
true
)(subject);
}
]);
}
function object(zeroth, wunth, twoth) {
function heterogeneous() {
const required = coalesce(zeroth, {});
const optional = coalesce(wunth, {});
const allow_strays = coalesce(twoth, false);
function is_stray(key) {
return !owns(required, key) && !owns(optional, key);
}
return function heterogeneous_validator(subject) {
let violations = [];
// Required properties must exist directly on the subject, not just in its
// prototype chain. This ensures that JSON representations of valid subjects
// include all required properties.
Object.keys(required).forEach(function (key) {
if (owns(subject, key)) {
violations = violations.concat(
property(key, euphemize(required[key]))(subject)
);
} else {
violations.push(make_violation("missing_property_a", key));
}
});
// Optional properties are trickier. When an optional property is missing from
// the subject, there remains the possibility that it is buried somewhere in
// the prototype chain. If the value of such a property is invalid, it could
// cause problems when dredged up by unsuspecting code.
// To prevent this hazard, we simply access the optional property by name and
// validate the resulting value. A side effect of this approach is that a
// missing property is indistinguishable from a property with a value of
// undefined. I am ambivalent about this.
Object.keys(optional).forEach(function (key) {
if (subject[key] !== undefined) {
violations = violations.concat(
property(key, euphemize(optional[key]))(subject)
);
}
});
if (!allow_strays) {
violations = violations.concat(
Object.keys(subject).filter(is_stray).map(function (key) {
return make_violation("unexpected_property_a", key);
})
);
}
return violations;
};
}
function homogenous() {
const key_validator = coalesce(zeroth, any());
const value_validator = coalesce(wunth, any());
const length_validator = coalesce(twoth, any());
return function homogenous_validator(subject) {
const keys = Object.keys(subject);
const length_violations = euphemize(length_validator)(keys.length);
return all_of([
// Validate the keys.
...keys.map(function (key) {
return function () {
return euphemize(key_validator)(key);
};
}),
// Validate the values.
...keys.map(function (key) {
return property(key, value_validator);
}),
// Validate the number of keys.
function () {
return (
length_violations.length === 0
? []
: [make_violation("object_length")]
);
}
], true)(subject);
};
}
return all_of([
function object_validator(subject) {
return (
is_object(subject)
? []
: [make_violation("not_type_a", "object")]
);
},
(
(is_object(zeroth) || is_object(wunth))
? heterogeneous()
: homogenous()
)
]);
}
export default Object.freeze({
// Each of JSCheck's specifiers have a corresponding validator, with the
// exception of 'character' and 'falsy', which are not very useful, and
// 'sequence', which is stateful.
boolean,
number,
integer,
string,
function: fn,
array,
object,
wun_of,
all_of,
not,
literal,
any
});