-
Notifications
You must be signed in to change notification settings - Fork 0
/
sanityjs.js
538 lines (463 loc) · 21.8 KB
/
sanityjs.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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
/*! sanityjs v1.7.1 2016-10-07 */
(function(){
var sanityjs = {};
var array_length_warning = 20;
var recursion_count_warn = 20;
var recursion_count_log = 3;
sanityjs.toType = toCleanType;
sanityjs.isBoolean = isBoolean;
sanityjs.isNumber = isNumber;
sanityjs.isInteger = isInteger;
sanityjs.isFloat = isFloat;
sanityjs.isString = isString;
sanityjs.isDate = isDate;
sanityjs.isRegExp = isRegExp;
sanityjs.isError = isError;
sanityjs.isArguments = isArguments;
sanityjs.isFunction = isFunction;
sanityjs.isUndefined = isUndefined;
sanityjs.isDefined = isDefined;
sanityjs.isArray = isArray;
sanityjs.isObject = isObject;
sanityjs.isObjectEmpty = isObjectEmpty;
sanityjs.isEqual = isEqual;
function toCleanType(obj){
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}
function toType(obj) {
return ({}).toString.call(obj);
}
function isBoolean(obj) { return obj === true || obj === false || toType(obj) === '[object Boolean]'; }
function isNumber(obj) { return toType(obj) === '[object Number]'; } // positive for NaN and Infinity
function isInteger(obj) { return isNumber(obj) && obj % 1 === 0; } // negative for NaN and Infinity
function isFloat(obj) { return isNumber(obj) && obj % 1 !== 0; } // negative for NaN and Infinity
function isString(obj) { return toType(obj) === '[object String]'; }
function isDate(obj) { return toType(obj) === '[object Date]'; }
function isRegExp(obj) { return toType(obj) === '[object RegExp]'; }
function isError(obj) { return toType(obj) === '[object Error]'; }
function isArguments(obj) { return toType(obj) === '[object Arguments]'; }
function isFunction(obj) { return toType(obj) === '[object Function]'; }
function isUndefined(obj) { return obj === void 0 || toType(obj) === '[object Undefined]' ; }
function isDefined(obj) { return !isUndefined(obj); }
function isArray(obj) { return Array.isArray(obj); }
function isObject(obj) { return toType(obj) === '[object Object]'; }
function isObjectEmpty(obj) { return Object.keys(obj).length === 0; }
// function isBoolean(obj) { return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; }
// function isNumber(obj) { return toString.call(obj) === '[object Number]'; } // positive for NaN and Infinity
// function isInteger(obj) { return isNumber(obj) && obj % 1 === 0; } // negative for NaN and Infinity
// function isFloat(obj) { return isNumber(obj) && obj % 1 !== 0; } // negative for NaN and Infinity
// function isString(obj) { return toString.call(obj) === '[object String]'; }
// function isDate(obj) { return toString.call(obj) === '[object Date]'; }
// function isRegExp(obj) { return toString.call(obj) === '[object RegExp]'; }
// function isError(obj) { return toString.call(obj) === '[object Error]'; }
// function isArguments(obj) { return toString.call(obj) === '[object Arguments]'; }
// function isFunction(obj) { return toString.call(obj) === '[object Function]'; }
// function isUndefined(obj) { return obj === void 0; }
// function isDefined(obj) { return !isUndefined(obj); }
// function isArray(obj) { return Array.isArray(obj); }
// function isObject(obj) { return typeof obj === 'object' && !isArray(obj) && !!obj; }
// function isObjectEmpty(obj) { return Object.keys(obj).length === 0; }
// Function lamely stolen from underscore js
// http://underscorejs.org/
function isEqual(a, b, aStack, bStack) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
if (a === b) return a !== 0 || 1 / a === 1 / b;
// A strict comparison is necessary because `null == undefined`.
if (a === null || b === null) return a === b;
// Compare `[[Class]]` names.
var className = toString.call(a);
if (className !== toString.call(b)) return false;
switch (className) {
// Strings, numbers, regular expressions, dates, and booleans are compared by value.
case '[object RegExp]':
// RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return '' + a === '' + b;
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive.
// Object(NaN) is equivalent to NaN
if (+a !== +a) return +b !== +b;
// An `egal` comparison is performed for other numeric values.
return +a === 0 ? 1 / +a === 1 / b : +a === +b;
case '[object Date]':
case '[object Boolean]':
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a === +b;
}
var areArrays = className === '[object Array]';
if (!areArrays) {
if (typeof a != 'object' || typeof b != 'object') return false;
// Objects with different constructors are not equivalent, but `Object`s or `Array`s
// from different frames are.
var aCtor = a.constructor,
bCtor = b.constructor;
if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
_.isFunction(bCtor) && bCtor instanceof bCtor) && ('constructor' in a && 'constructor' in b)) {
return false;
}
}
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
// Initializing stack of traversed objects.
// It's done here since we only need them for objects and arrays comparison.
aStack = aStack || [];
bStack = bStack || [];
var length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (aStack[length] === a) return bStack[length] === b;
}
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
// Recursively compare objects and arrays.
if (areArrays) {
// Compare array lengths to determine if a deep comparison is necessary.
length = a.length;
if (length !== b.length) return false;
// Deep compare the contents, ignoring non-numeric properties.
while (length--) {
if (!isEqual(a[length], b[length], aStack, bStack)) return false;
}
} else {
// Deep compare objects.
var keys = _keys(a),
key;
length = keys.length;
// Ensure that both objects contain the same number of properties before comparing deep equality.
if (_keys(b).length !== length) return false;
while (length--) {
// Deep compare each member
key = keys[length];
if (!(_has(b, key) && isEqual(a[key], b[key], aStack, bStack))) return false;
}
}
// Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return true;
}
// Retrieve the names of an object's own properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`.
function _keys(obj){
if (!isObject(obj)) return [];
if (Object.keys) return Object.keys(obj);
var keys = [];
for (var key in obj) if (_has(obj, key)) keys.push(key);
// Ahem, IE < 9.
// if (hasEnumBug) collectNonEnumProps(obj, keys);
return keys;
}
// Shortcut function for checking if an object has a given property directly
// on itself (in other words, not on a prototype).
function _has(obj, key) {
return obj !== null && Object.prototype.hasOwnProperty.call(obj, key);
}
function error(message, options) {
if( isUndefined(options) || !isObject(options) )
options = {};
options.throw_exception = isDefined(options.throw_exception) ? options.throw_exception : true;
options.verbose = isDefined(options.verbose) ? options.verbose : false;
if( options.throw_exception )
throw new TypeError(message);
else if ( options.verbose )
console.error("[SanityJS Error]: " + message);
// return false, only called if throw_exception at false
return false;
}
function warn(message, options){
if( isUndefined(options) || !isObject(options) )
options = {};
options.throw_exception = isDefined(options.throw_exception) ? options.throw_exception : true;
options.verbose = isDefined(options.verbose) ? options.verbose : false;
if( options.verbose )
console.warn("[SanityJS Warning]: " + message);
}
function log(message, options){
if( isUndefined(options) || !isObject(options) )
options = {};
options.throw_exception = isDefined(options.throw_exception) ? options.throw_exception : true;
options.verbose = isDefined(options.verbose) ? options.verbose : false;
if( options.verbose )
console.log("[SanityJS Log]: " + message);
}
sanityjs.object_check = object_check;
function object_check(obj, type, name, options, ctx, recursion_count ) {
// checking name, needs to be done first because next error message exploit this value
if( isUndefined(name) || !isString(name) ){
warn("Bad third parameter 'name' in function object_check. It should be a string. Default empty name used instead.", options);
name = "";
}
// if no type or bad type given, return
if( isUndefined(type) || (!isObject(type) && !isString(type) && !isArray(type)) )
return error("Bad second parameter 'type' for obj '"+name+"' in function object_check. It's a mandatory argument, must be a string, an object or an array", options);
// if type is an array, we're checking many types
if( isArray(type) ){
var t;
var nb_type = type.length;
var true_log_function = console.log;
var true_error_function = console.error;
var messages = "";
console.log = function(str){messages+=" "+str;};
console.error = function(str){messages+=" "+str;};
for(t=0;t<nb_type;t++){
try{
if( object_check(obj, type[t], name, options, ctx, recursion_count) ){
console.log = true_log_function;
console.error = true_error_function;
return true;
}
} catch(e){
messages+=" "+e.message;
}
}
console.log = true_log_function;
console.error = true_error_function;
return error(messages, options);
}
// if type is a string, set it as an object for compatibility with the object type case
if ( isString(type) )
type = {type:type};
// // if object is a string, and type given isn't string or stringnum, then obj is a JSON and should be parsed
// if( isString(obj) && type.type !=="string" && type.type !== "stringnum" ){
// try{
// obj = JSON.parse(obj);
// }catch(e){
// // if fails, then it's likely that a string is checked while expected to be something else
// // if JSON parse fails while actually trying to parse a JSON, then no error will be stated
// warn("JSON parse of " + name + " failed. If this object wasn't intended to be a JSON then ignore this warning.", options);
// }
// }
// // if type is not explicitely the type "undefined" and obj is undefined, returns immediatly
// // not a mandatory line, but is clearer
// if (type.type !== "undefined" && isUndefined(obj) )
// return error("Object '" + name + "' is undefined.", options);
// handling ctx, ctx attributes and recursion count creation
if( isUndefined(ctx) || !isObject(ctx) ){
if( isDefined(ctx) && !isObject(ctx) )
warn("Bad fifth parameter 'ctx' for obj '"+name+"' in function object_check. It should be an object. Recovered by overwriting.", options);
ctx = {};
}
if( isUndefined(ctx.labels) || !isObject(ctx.labels) ){
if( isDefined(ctx.labels) && !isObject(ctx.labels) )
warn("Bad argument 'labels' of parameter 'ctx' for obj '"+name+"' in function object_check. It should be an object. Recovered by overwriting.", options);
ctx.labels = {};
}
if( isUndefined(ctx.recursion_depth) || !isInteger(ctx.recursion_depth) ){
if( isDefined(ctx.recursion_depth) && !isObject(ctx.recursion_depth) )
warn("Bad argument 'recursion_depth' of parameter 'ctx' for obj '"+name+"' in function object_check. It should be an integer. Recovered by overwriting.", options);
ctx.recursion_depth = 0;
}
if( isUndefined(ctx.recursion_count_warned) || !isBoolean(ctx.recursion_count_warned) ){
if( isDefined(ctx.recursion_count_warned) && !isBoolean(ctx.recursion_count_warned) )
warn("Bad argument 'recursion_count_warned' of parameter 'ctx' for obj '"+name+"' in function object_check. It should be a boolean. Recovered by overwriting.", options);
ctx.recursion_count_warned = false;
}
if( isUndefined(recursion_count) || !isInteger(recursion_count) ){
if( isDefined(recursion_count) && !isInteger(recursion_count) )
warn("Bad sixth parameter 'recursion_count' for obj '"+name+"' in function object_check. It should be an integer. Recovered by overwriting.", options);
recursion_count = -1;
}
// verifying recursion count and warning if recursion is too deep
recursion_count++;
if( recursion_count > recursion_count_warn && !ctx.recursion_count_warned ){
warn( "Object depth reached " + recursion_count_warn + ". Behavior beyond this depth can't be guaranteed and checker might slow down." , options);
ctx.recursion_count_warned = true;
}
if( recursion_count > ctx.recursion_depth )
ctx.recursion_depth = recursion_count;
// if type is an object, this means it contains more checking rules
// type.type type of obj described as a string
// type.equal what obj should be equal to
// type.not_equal what obj shouldn't be equal to
// type.not_empty obj shouldn't be empty
// type.cb function that will be called given obj as parameter
// type.cb_message string that will be displayed if cb call fails
// type.label label that is used to store and remember this object during the recursion
// type.length what should be obj's length if obj is an array or a string
// type.full_check verify the type of all elements of obj if obj is an array, check only first element otherwise
// type.structure the structure of obj if obj is an object
// type.sub_type the type of the elements of obj if obj is an array
type.not_empty = isDefined(type.not_empty) ? type.not_empty : false;
type.full_check = isDefined(type.full_check) ? type.full_check : false;
// testing type parameters sanity
if( isDefined(type.equal) && !isArray(type.equal) )
return error("Bad equal parameter for object " +name+ ". It should be an array", options);
if( isDefined(type.not_equal) && !isArray(type.not_equal) )
return error("Bad not_equal parameter for object " +name+ ". It should be an array", options);
if( isDefined(type.cb) && !isFunction(type.cb) )
return error("Bad cb parameter for object " +name+ ". It should be a function", options);
if( isDefined(type.cb_message) && !isString(type.cb_message) )
return error("Bad cb_message parameter for object " +name+ ". It should be a string", options);
if( isDefined(type.label) && !isString(type.label) )
return error("Bad label parameter for object " +name+ ". It should be a string", options);
if( isDefined(type.length) && !isInteger(type.length) )
return error("Bad length parameter for object " +name+ ". It should be an integer", options);
if( isDefined(type.structure) && !isArray(type.structure) )
return error("Bad structure parameter for object " +name+ ". It should be an array", options);
if( isDefined(type.sub_type) && ( !isObject(type.sub_type) && !isString(type.sub_type) && !isArray(type.sub_type) ) )
return error("Bad sub_type parameter for object " +name+ ". It should be a string, an object or an array", options);
var r;
var i;
switch (type.type) {
case "defined":
r = isDefined(obj);
break;
case "undefined":
r = isUndefined(obj);
break;
case "boolean":
r = isBoolean(obj);
break;
case "number":
r = isNumber(obj);
if( !r ) break;
if ( isNaN(obj) )
return error("Object " + name + " is NaN.", options);
if ( !isFinite(obj) )
return error("Object " + name + " is of type " + type.type + " but is Infinite.", options);
break;
case "integer":
r = isInteger(obj);
break;
case "float":
r = isFloat(obj);
break;
case "string":
r = isString(obj);
if( !r ) break;
// if length given, test the length of the string
if( isDefined(type.length) && obj.length !== type.length)
return error("Object '" + name + "' of type " + type.type + " is of length " + obj.length + " but was expected to be of length " + type.length + ".", options);
// test emptyness if asked
if ( type.not_empty && obj.length === 0)
return error("Object '" + name + "' of type " + type.type + " is expected not to be empty.", options);
break;
case "stringnum":
r = (isString(obj) && parseFloat(obj)) || isNumber(obj);
break;
case "array":
r = isArray(obj);
if( !r ) break;
// if length given, test the length of the array
if (isDefined(type.length) && obj.length !== type.length)
return error("Object '" + name + "' of type " + type.type + " is of length " + obj.length + " but was expected to be of length " + type.length + ".", options);
if ( type.not_empty && obj.length === 0)
return error("Parameter '" + name + "' of type " + type.type + " is expected not to be empty.", options);
// if sub_type is not empty, this means the type of the first element will be checked
if (obj.length > 0 && isDefined(type.sub_type)) {
// if full_check is set, check all elements of array
if ( type.full_check && type.full_check){
if( obj.length > array_length_warning )
warn("Full check requested on the array "+name+" of length superior to " + array_length_warning +". This can cause the checker to be slow.", options);
for (i = 0; i < obj.length; i++){
if (!object_check(obj[i], type.sub_type, name+"["+i+"]", options, ctx, recursion_count)) return false;
// else check only the first one
}
}
else
if (!object_check(obj[0], type.sub_type, name+"[0]", options, ctx, recursion_count)) return false;
}
break;
case "object":
r = isObject(obj);
if( !r ) break;
// if structure is not empty, this means it must be checked through a structure
if (isDefined(type.structure)){
// objects are described with an array of objects containing informations and structures of the fields
for (i = 0; i < type.structure.length; i++) {
// for each field, check obj of the vield
if (!object_check(obj[type.structure[i].name], type.structure[i].type, name + "." + type.structure[i].name, options, ctx, recursion_count)) return false;
}
}
// test emptyness if asked
if (type.not_empty && isObjectEmpty(obj))
return error("Parameter '" + name + "' of type " + type.type + " is expected not to be empty.", options);
break;
case "function":
r = isFunction(obj);
break;
case "error":
r = isError(obj);
break;
case "date":
r = isDate(obj);
break;
case "regexp":
r = isRegExp(obj);
break;
default:
return error("Type " + type.type + " cannot be checked, or checker has not implemented this type.", options);
}
if (!r)
return error("Parameter '" + name + "' is not of the type " + type.type + ".", options);
// // test equality if asked
// if (isDefined(type.equal) && !isEqual(obj, type.equal))
// return error("Parameter '" + name + "' of value " + obj + " is not equal to " + type.equal + ".", options);
// test equality if asked
if (isDefined(type.equal) && type.equal.length !== 0) {
var equal = false;
for (i = 0; i < type.equal.length; i++) {
if ( isEqual(obj, type.equal[i]) )
equal = true;
}
if( !equal )
return error("Parameter '" + name + "' of value " + obj + " should be equal to one of these values: " + type.equal + ".", options);
}
// test inequality if asked
if (isDefined(type.not_equal) && type.not_equal.length !== 0) {
for (i = 0; i < type.not_equal.length; i++) {
if ( isEqual(obj, type.not_equal[i]) )
return error("Parameter '" + name + "' is equal to " + type.not_equal[i] + ", it should not.", options);
}
}
// handling labels
if( isDefined(type.label) )
ctx.labels[type.label] = obj;
// call cb on obj
if( isDefined(type.cb) ){
r = type.cb(obj, type, name, ctx.labels);
if( !r ){
if( isDefined(type.cb_message) )
return error("Parameter '" + name + "' " + type.cb_message, options);
else
return error("Parameter '" + name + "' failed passing the callback.", options);
}
}
// logging success for first object
if( recursion_count === 0 && ctx.recursion_depth >= recursion_count_log )
log("Object " + name + " has been successfuly checked with " + ctx.recursion_depth + " recursion depth.", options );
return true;
}
sanityjs.arguments_check = arguments_check;
function arguments_check(argument_types, options) {
// if no argument_types or bad argument_types given, returns
if( isUndefined(argument_types) || (!isArray(argument_types)) )
return error("Bad fist parameter argument_types. It's a mandatory argument, must be an array of types.", options);
// get caller's arguments
caller_arguments = Array.prototype.slice.call(arguments.callee.caller.arguments);
// get caller's arguments name
caller_arguments_names = arguments.callee.caller.toString()
.replace(/((\/\/.*$)|(\/\*[\s\S]*?\*\/)|(\s))/mg,'')
.match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m)[1]
.split(/,/);
// if given argument types is higher than actual arguments, return error
// equal or lower argument types is accepted
if (argument_types.length > caller_arguments.length)
return error("Function called with " + caller_arguments.length + " arguments, was expecting " + argument_types.length + ".", options);
// verify each argument
for (var i = 0; i < argument_types.length; i++) {
if (!object_check(caller_arguments[i], argument_types[i], caller_arguments_names[i], options, {})) return false;
}
return true;
}
if( typeof module !== 'undefined' && module.exports )
module.exports = sanityjs;
this.sanityjs = sanityjs;
})();