-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
472 lines (398 loc) · 13.2 KB
/
index.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
var righto = require('righto');
var flatten = require('@flatten/array');
var asyncOr = require('async-or');
function Type(){}
function Default(value){
this.value = value;
}
var constructors = {
'String': ''.constructor,
'Number': (0).constructor,
'Boolean': true.constructor
}
function getName(spec){
var type = typeof spec;
return type === 'function' ? spec.name :
type === 'object' ? JSON.stringify(Object.keys(spec).reduce((result, key) => {
result[key] = getName(spec[key]);
return result;
}, {})) :
type;
}
function isBaseType(spec){
return (
spec === null ||
spec.name in constructors &&
constructors[spec.name] === spec
);
}
function throwError(message, errors){
var error = new Error(`\nBlazon error:\n\t${message}\n\nSpec:\n\t${errors}\nSource:`)
error.stack = error.stack.replace(/^.*\/discriminate\/.*$\n/gm, '');
throw error;
}
function buildPath(path, key){
return (path ? path + '.' : '') + key;
}
function checkBaseType(spec, value, path, callback){
if(
spec === null && value === spec ||
spec &&
value != null &&
value.constructor.name === spec.name &&
value.constructor.name in constructors &&
value.constructor === constructors[value.constructor.name]
){
return callback(null, value);
}
callback({
path: path[0],
message: `${path[1]} must be ${spec === null ? 'null' : 'a ' + getName(spec)}, but saw \`${JSON.stringify(value)}\``
});
}
function getAnyErrors(hasErrors, allResults, callback){
if(!hasErrors){
return callback(null, allResults
.map(result => result[1])
.filter(error => error)
);
}
callback(allResults
.map(result => result[0])
.filter(error => error)
);
}
function checkAllResults(validationChecks, callback){
var allResults = righto.all(validationChecks.map(validation => righto.surely(validation)));
var hasErrors = righto.handle(righto.all(validationChecks).get(() => false), (error, done) => done(null, !!error));
var result = righto(getAnyErrors, hasErrors, allResults);
result(callback);
}
function checkObject(spec, target, data, path, callback){
if(data == null || !(data instanceof Object)){
return callback({
path: path[0],
message: `${path[1]} should be an Object, but saw \`${JSON.stringify(data)}\``
});
}
var validationChecks = Object.keys(spec).map(key =>
righto(check, spec[key], target[key] || {}, data[key], [buildPath(path[0], key), key])
.get(result => {
if(result || key in data){
target[key] = result && result instanceof Default ? result.value : result;
}
})
);
// console.log(target);
var result = righto(checkAllResults, validationChecks)
.get(() => {
return target
});
result(callback);
}
function SubSpec(){}
function check(spec, target, value, path, callback){
if(spec && spec.prototype instanceof SubSpec){
return spec(path, value, function(error, result){
if(error){
return callback(error.errors);
}
callback(null, result);
});
}
if(spec && spec instanceof Type){
return spec.validate(target, value, path, callback);
}
if(isBaseType(spec)){
return checkBaseType(spec, value, path, callback);
} else if(spec instanceof Function){
if(value && value instanceof spec){
return callback(null, value);
}
} else if(spec instanceof Object){
return checkObject(spec, target, value, path, callback);
}
callback({
path: path[0],
message: `Invalid type: Expected ${getName(spec)}, Got: ${value}`
});
}
function Required(spec){
if(!(this instanceof Required)){
return new Required(spec);
}
this.spec = spec;
return this;
}
Required.prototype = Object.create(Type.prototype);
Required.prototype.constructor = Required;
Required.prototype.validate = function(target, value, path, callback){
if(value == null){
return callback({
path: path[0],
message: `${path[1]} is required.`
})
}
return check(this.spec, target, value, path, callback);
}
function Maybe(spec, defaultValue){
var hasDefault = arguments.length > 1;
if(!(this instanceof Maybe)){
if(hasDefault){
return new Maybe(spec, defaultValue);
}
return new Maybe(spec);
}
this.spec = spec;
if(hasDefault){
this.defaultValue = new Default(defaultValue);
}
return this;
}
Maybe.prototype = Object.create(Type.prototype);
Maybe.prototype.constructor = Maybe;
Maybe.prototype.validate = function(target, value, path, callback){
if(value == null){
if('defaultValue' in this){
return callback(null, this.defaultValue);
}
return callback(null, value);
}
var result = righto.handle(
righto(check, this.spec, target, value, path),
(error, done) => {
done({
path: path[0],
message: `${path[1]} must be a ${getName(this.spec)} or null, but saw \`${JSON.stringify(value)}\``
})
}
);
result(callback);
}
function Custom(validater){
if(!(this instanceof Custom)){
return new Custom(validater);
}
this.validater = validater;
}
Custom.prototype = Object.create(Type.prototype);
Custom.prototype.constructor = Custom;
Custom.prototype.validate = function(target, value, path, callback){
this.validater(path, value, callback);
}
function And(){
if(!(this instanceof And)){
return And.apply(Object.create(And.prototype), arguments);
}
this.types = [].slice.call(arguments);
return this;
}
And.prototype = Object.create(Type.prototype);
And.prototype.constructor = And;
And.prototype.validate = function(target, value, path, callback){
var itemValidations = this.types.map(type => righto(check, type, target, value, path));
var result = righto(checkAllResults, itemValidations)
.get((results) => results[results.length - 1]);
result(callback);
}
function Or(){
if(!(this instanceof Or)){
return Or.apply(Object.create(Or.prototype), arguments);
}
this.types = [].slice.call(arguments);
return this;
}
Or.prototype = Object.create(Type.prototype);
Or.prototype.constructor = Or;
Or.prototype.validate = function(target, value, path, callback){
var itemValidations = this.types.map(type => righto(check, type, target, value, path));
var result = righto.handle(
righto(asyncOr, itemValidations),
(error, done) => {
var newError = righto.all(itemValidations.map(validation =>
righto.surely(righto(validation)).get(0)
)).get(errors => {
return righto.fail({
path: path[0],
message: `${path[1]} must be a ${this.types.map(type => getName(type)).join(' or ')}, but saw \`${JSON.stringify(value)}\``
});
});
newError(done);
}
);
result(callback);
}
function Any(){
if(!(this instanceof Any)){
return Any.apply(Object.create(Any.prototype), arguments);
}
return this;
}
Any.prototype = Object.create(Type.prototype);
Any.prototype.constructor = Any;
Any.prototype.validate = function(target, value, path, callback){
callback(null, value);
}
function List(type, minLength, maxLength){
if(!(this instanceof List)){
return List.apply(Object.create(List.prototype), arguments);
}
this.type = type;
this.minLength = minLength || 0;
this.maxLength = maxLength || Infinity;
return this;
}
List.prototype = Object.create(Type.prototype);
List.prototype.constructor = List;
List.prototype.print = function(){
return `${this.constructor.name}(${printType(this.type)}), minimum length: ${this.minLength}, maximum length: ${this.maxLength}`;
}
List.prototype.validate = function(target, value, path, callback){
var type = this.type;
if(!Array.isArray(value)){
return callback({
path: path[0],
message: `${path[1] || 'value'} must be an array, but saw \`${JSON.stringify(value)}\``
})
}
if(value.length < this.minLength){
return callback({
path: path[0],
message: `${path[1] || 'value'} must be of minimum length ${this.minLength}, but length was ${value.length}`
})
}
if(value.length > this.maxLength){
return callback({
path: path[0],
message: `${path[1] || 'value'} must be of maximum length ${this.maxLength}, but length was ${value.length}`
})
}
var valid = righto.all(value.map((item, index) => {
var itemPath = buildPath(path[0], index)
return righto.surely((type && type instanceof SubSpec)
? righto(type, itemPath, item)
: righto(discriminate(itemPath, type), item)
)
})).get(results => {
var errors = results.map(result => result[0] && result[0].errors).filter(error => error);
if(errors.length){
return righto.fail(errors)
}
return results.map(result => result[1]);
})
valid(callback);
}
var casts = {
'String': (value, path, callback) => {
if(value && value instanceof Object){
return callback({
path: path[0],
message: `${path[1] || 'value'} must be castable to String, but saw \`${JSON.stringify(value)}\``
})
}
return callback(null, String(value));
},
'Number': (value, path, callback) => {
if(typeof value === 'number'){
return callback(null, value);
}
var result = Number(value);
if(result != String(value) || isNaN(result)){
return callback({
path: path[0],
message: `${path[1] || 'value'} must be castable to Number, but saw \`${JSON.stringify(value)}\``
})
}
return callback(null, result);
},
'Boolean': (value, path, callback) => {
var type = typeof value;
if(type === 'boolean'){
return callback(null, value);
}
if(type === 'string' && value === 'true' || value === 'false'){
return callback(null, value === 'true');
}
if(type === 'number' && value === 0 || value === 1){
return callback(null, value !== 0);
}
callback({
path: path[0],
message: `${path[1] || 'value'} must be castable to Boolean, but saw \`${JSON.stringify(value)}\``
})
}
}
function Cast(baseOrSourceType, targetType, customConverter){
if(!customConverter && !isBaseType(baseOrSourceType)){
throw new Error(`Only BaseTypes (${Object.keys(constructors)}) can be cast to`);
}
if(arguments.length === 2){
throw new Error(`Cast can only be either Cast(targetBaseType) OR Cast(sourceType, targetType, customConverter)`);
}
if(!(this instanceof Cast)){
return new Cast(baseOrSourceType, targetType, customConverter);
}
this.targetType = targetType;
this.baseOrSourceType = baseOrSourceType;
this.customConverter = customConverter;
return this;
}
Cast.prototype = Object.create(Type.prototype);
Cast.prototype.constructor = Cast;
Cast.prototype.print = function(){
return `${this.constructor.name}(${printType(this.type)}), minimum length: ${this.minLength}, maximum length: ${this.maxLength}`;
}
Cast.prototype.validate = function(target, value, path, callback){
casts[this.baseOrSourceType.name](value, path, callback);
}
function discriminate(name, spec){
if(arguments.length < 2){
spec = name;
name = null;
}
var path = [name, name];
function Spec(parentPath, data, callback){
if(arguments.length < 3){
callback = data;
data = parentPath;
} else {
path = parentPath;
}
function done(errors, result){
if(errors){
return callback({
message: 'Invalid ' + (name || 'data'),
errors: flatten(errors)
})
}
callback(null, result);
}
if(isBaseType(spec)){
return checkBaseType(spec, data, path, done);
}
if(!(this instanceof Spec)){
return new Spec(data, callback);
}
if(spec instanceof Type){
return spec.validate({}, data, path, function(error, result){
return done(error && flatten([error]), result);
});
}
check(spec, this, data, path, done);
}
Spec.prototype = Object.create(SubSpec.prototype);
Spec.constructor = Spec;
Spec.validate = function(data, callback){
Spec(data, callback);
}
return Spec;
}
module.exports = discriminate;
module.exports.Required = Required;
module.exports.Maybe = Maybe;
module.exports.Custom = Custom;
module.exports.And = And;
module.exports.Or = Or;
module.exports.Any = Any;
module.exports.List = List;
module.exports.Cast = Cast;