-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtypeChecking.js
603 lines (521 loc) · 18.7 KB
/
typeChecking.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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
/**
* @fileoverview typeChecking.js - A runtime type checking and assertion library.
*
* @formats browser script tag, nodejs module
*
* @language syntax: es5 +const +rest - globals: es6 +console
*
* @linter ESLint
*
* @namespace typeChecking
*
* @design These type checking functions are strict, i.e. they do not coerce any of their arguments.
*
* @references Other dynamic type checking and runtime assertion libraries:
*
* With traditional syntax (TDD assertion style):
*
* {@link https://nodejs.org/api/assert.html Node module 'assert' (node doc) }
* {@link https://github.com/joyent/node-assert-plus (git) } Has support for 'process.env.NODE_NDEBUG'.
* {@link http://chaijs.com/api/assert/ chai.assert (doc) } Has assertions, extension API
*
* {@link https://github.com/facebook/prop-types prop-types } Has duck types, type combinators, React integration
*
* {@link https://github.com/etcinit/ensure ensure.js (git) } Has function wrappers, record types
* {@link https://github.com/PuerkitoBio/implement.js implement.js (git) } Has duck types, custom error objects
* {@link https://github.com/busterjs/samsam samsam (git) }
* {@link https://github.com/zvictor/ArgueJS ArgueJS (git) }
* {@link https://github.com/sharkbrainguy/type.js Type.js (git) } Has duck types, type combinators
* {@link https://github.com/mmaelzer/surely surely } Has function wrappers, an extension method, predefined type specs
*
* With chained syntax (BDD assertion style):
*
* {@link http://chaijs.com/api/bdd chai.should, chai.expect (doc) }
* {@link https://github.com/philbooth/check-types.js check-types (git) }
* {@link https://github.com/Automattic/expect.js expect.js (git) }
* {@link https://github.com/arasatasaygin/is.js is.js (git) }
*/
'use strict';
/*eslint indent: "off" */
/*eslint-env amd, browser, nashorn, node */
// UMD snippet (with AMD, NodeJS, and Browser support)
(function (root, moduleName, moduleExports) {
// AMD support
if(typeof define === "function" && define.amd) {
define(moduleName, function () {
return moduleExports;
});
}
// NodeJS support
else if(typeof module === "object") {
if(typeof module.exports === "object") {
module.exports = moduleExports;
}
else module = moduleExports; // eslint-disable-line no-global-assign
}
// Browser support
else if(typeof root === "object" && root !== null) {
root[moduleName] = moduleExports;
}
else throw new Error("Cannot export.");
}(this, "typeChecking", (function () {
const typeChecking = Object.create(null);
typeChecking.disabled = false;
const areSymbolsSupported = typeof Symbol === "function";
const areTypedArraysSupported = typeof Int8Array === "function";
const isSymbolIteratorSupported = (areSymbolsSupported && typeof Symbol.iterator === "symbol");
const isSymbolToStringTagSupported = (areSymbolsSupported && typeof Symbol.toStringTag === "symbol");
const TypedArray = (areTypedArraysSupported ? Object.getPrototypeOf(Int8Array) : null);
const TypedArrayPrototype = (areTypedArraysSupported ? TypedArray.prototype : null);
const NDEBUG = getNdebug();
function getNdebug() {
const platform = (
(typeof process === "object" && typeof process.env === "object") ? "node" :
(typeof java === "object" && typeof java.lang === "object") ? "jjs" :
"browser"
);
switch(platform) {
case "node": return !!(process.env.NODE_NDEBUG);
case "jjs": return !!(java.lang.System.getProperty("nashorn.ndebug"));
default: return false;
}
}
function getErrorMessage(errorType, parameterName, readableTypeDescription) {
return `An instance of '${errorType.name}' was about to be thrown but the error constructor was called incorrectly: argument ${parameterName} was not ${readableTypeDescription}.`;
}
function AssertionError(message="") {
if(typeof message !== "string") {
// Do not modify the 'stack' property in this case.
throw new TypeError(getErrorMessage(AssertionError, "message", "a string"));
}
this.message = message;
if(typeof Error.captureStackTrace === "function") {
Error.captureStackTrace(this, AssertionError);
}
}
AssertionError.prototype = Object.create(Error.prototype);
AssertionError.prototype.name = "AssertionError";
typeChecking.AssertionError = AssertionError;
// @param {string} [message]
// @param {function} [thrower] - A function that should not show up in the stack trace of the generated error.
function throwNewAssertionError(message="", thrower) {
if(typeof message !== "string") {
// Do not attempt to modify the 'stack' property in this case.
throw new TypeError(getErrorMessage(AssertionError, "message", "a string"));
}
const error = new typeChecking.AssertionError(message);
if("1" in arguments) {
if(typeof thrower !== "function") {
throw new TypeError(getErrorMessage(TypeError, "thrower", "a function"));
}
if(typeof Error.captureStackTrace === "function") {
Error.captureStackTrace(error, thrower);
}
}
throw error;
}
typeChecking.throwNewAssertionError = throwNewAssertionError;
// @param {string} typeDescription - A non-empty and preferably readable description of the type which was expected.
// @param {function} [thrower] - A function that should not show up in the stack trace of the generated error.
function throwNewTypeError(typeDescription, thrower) {
if(typeof typeDescription !== "string" || typeDescription === "") {
// Do not attempt to modify the 'stack' property in this case.
throw new TypeError(getErrorMessage(TypeError, "typeDescription", "a non-empty string"));
}
const error = new TypeError("expected " + typeDescription + ".");
if("1" in arguments) {
if(typeof thrower !== "function") {
throw new TypeError(getErrorMessage(TypeError, "thrower", "a function"));
}
if(typeof Error.captureStackTrace === "function") {
Error.captureStackTrace(error, thrower);
}
}
throw error;
}
typeChecking.throwNewTypeError = throwNewTypeError;
typeChecking.assert =
function assert(booleanValue, message="") {
if(typeof booleanValue !== "boolean") throwNewTypeError("a boolean value", assert);
if(typeof message !== "string") throwNewTypeError("a string", assert);
if(assert.disabled) return;
if(booleanValue !== true) throwNewAssertionError(message, assert);
};
typeChecking.assert.disabled = NDEBUG;
typeChecking.isArray =
function isArray(x) {
return Array.isArray(x);
};
// 24.1.5 'ArrayBuffer' instances each have an [[ArrayBufferData]] internal slot and an [[ArrayBufferByteLength]] internal slot.
typeChecking.isArrayBuffer =
function isArrayBuffer(x) {
try {
Reflect.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get.call(x);
return true;
}
catch(_) {
return false;
}
};
// Allows function objects unlike Lodash (https://lodash.com/docs#isArrayLike).
// @note: an object being array-like does not guarantee that all generic 'Array' methods will work on it:
// some of those methods require their argument's length to be less than 2^32.
typeChecking.isArrayLike =
function isArrayLike(x) {
return typeof x === "string" || (typeof x === "object" || typeof x === "function")
&& x !== null && Number.isSafeInteger(x.length) && x.length >= 0;
};
typeChecking.isArrayLikeObject =
function isArrayLikeObject(x) {
return (typeof x === "object" || typeof x === "function")
&& x !== null && Number.isSafeInteger(x.length) && x.length >= 0;
};
typeChecking.isBoolean =
function isBoolean(x) {
return typeof x === "boolean";
};
typeChecking.isDataView =
function isDataView(x) {
try {
Object.getOwnPropertyDescriptor(DataView.prototype, "buffer").get.call(x);
return true;
}
catch(_) {
return false;
}
};
typeChecking.isDate =
function isDate(x) {
try {
Date.prototype.getDate.call(x);
return true;
}
catch(_) {
return false;
}
};
// @see Duck typing https://en.wikipedia.org/wiki/Duck_typing
typeChecking.isDuckOf =
function isDuckOf(x, object) {
typeChecking.expectNonPrimitive(object);
if(typeChecking.isPrimitive(x)) return false;
for(var i in object) {
if(typeof x[i] !== typeof object[i]) return false;
}
return true;
};
typeChecking.isGeneratorFunction = function isGeneratorFunction(x) {
if(!isSymbolIteratorSupported) return false;
if(typeof x !== "function") return false;
try {
return String.prototype.startsWith.call(Function.prototype.toString.call(x), "function*");
}
catch(_) {
return false;
}
};
typeChecking.isFunction =
function isFunction(x) {
return typeof x === "function";
};
typeChecking.isInstanceOf =
function isInstanceOf(x, ctor) {
return x !== null && typeof x !== "undefined"
&& typeof ctor === "function" && x instanceof ctor;
};
typeChecking.isImmutable =
function isImmutable(value) {
return typeChecking.isPrimitive(value) || (Object.isSealed(value) && Object.isFrozen(value));
};
typeChecking.isInteger =
function isInteger(value) {
return typeof value === "number" && value % 1 === 0;
};
typeChecking.isIterable =
function isIterable(value) {
if(!isSymbolIteratorSupported) return false;
if(value === null || typeof value === "undefined") return false;
return Symbol.iterator in Object(value);
};
// @see https://stackoverflow.com/questions/29924932/how-to-reliably-check-an-object-is-an-ecmascript-6-map-set
typeChecking.isMap =
function isMap(o) {
try {
Map.prototype.has.call(o); // throws if o is not an object or has no [[MapData]]
return true;
}
catch(_) {
return false;
}
};
typeChecking.isMutable =
function isMutable(value) {
return !typeChecking.isImmutable(value);
};
typeChecking.isMutableArrayLikeObject =
function isMutableArrayLikeObject(value) {
return typeChecking.isArrayLikeObject(value) && !typeChecking.isImmutable(value);
};
typeChecking.isNegativeInteger =
function isNegativeInteger(value) {
return typeof value === "number" && value % 1 === 0
&& value <= 0 && value > Number.NEGATIVE_INFINITY && !Object.is(value, 0);
};
typeChecking.isNegativeNumber =
function isNegativeNumber(value) {
return typeof value === "number" && value <= 0 && !Object.is(value, 0);
};
typeChecking.isNonEmptyArray =
function isNonEmptyArray(arg) {
return Array.isArray(arg) && arg.length > 0;
};
typeChecking.isNonEmptyArrayLike =
function isNonEmptyArrayLike(arg) {
return typeChecking.isArrayLike(arg) && arg.length > 0;
};
typeChecking.isNonEmptyString =
function isNonEmptyString(arg) {
return typeof arg === "string" && arg !== "";
};
typeChecking.isNonNull =
function isNonNull(x) {
return x !== null && typeof x !== "undefined";
};
typeChecking.isNonPrimitive =
function isNonPrimitive(x) {
return !typeChecking.isPrimitive(x);
};
typeChecking.isNumber =
function isNumber(value) {
return typeof value === "number";
};
typeChecking.isPositiveInteger =
function isPositiveInteger(value) {
return typeof value === "number" && value % 1 === 0
&& value >= 0 && value < Number.POSITIVE_INFINITY && !Object.is(value, -0);
};
typeChecking.isPositiveNumber =
function isPositiveNumber(value) {
return typeof value === "number" && value >= 0 && !Object.is(value, -0);
};
typeChecking.isPrimitive =
function isPrimitive(x) {
return x === null || typeof x === "undefined" || typeof x === "boolean" || typeof x === "number" || typeof x === "string" || typeof x === "symbol";
};
typeChecking.isRegExp =
function isRegExp(x) {
if(isSymbolToStringTagSupported) {
try {
// 21.2.5.10 get RegExp.prototype.source
Reflect.getOwnPropertyDescriptor(RegExp.prototype, "source").get.call(x);
// Now 'x' is either a 'RegExp' instance or the 'RegExp.prototype' object, which is not a 'RegExp' instance.
return x !== RegExp.prototype;
}
catch(_) {
return false;
}
}
return Object.prototype.toString.call(x) === "[object RegExp]";
};
typeChecking.isRegularNumber =
function isRegularNumber(value) {
if(typeof value !== "number") return false;
// Checks for NaN
if(value !== value) return false;
return value < Number.POSITIVE_INFINITY && value > Number.NEGATIVE_INFINITY;
};
typeChecking.isSafeInteger =
function isSafeInteger(value) {
return typeof value === "number" && value % 1 === 0
&& value >= Number.MIN_SAFE_INTEGER && value <= Number.MAX_SAFE_INTEGER;
};
// @see https://stackoverflow.com/questions/29924932/how-to-reliably-check-an-object-is-an-ecmascript-6-map-set
typeChecking.isSet =
function isSet(o) {
try {
Set.prototype.has.call(o); // throws if o is not an object or has no [[SetData]]
return true;
}
catch(_) {
return false;
}
};
// 24.1.5 'SharedArrayBuffer' instances each have an [[ArrayBufferData]] internal slot and an [[ArrayBufferByteLength]] internal slot.
typeChecking.isSharedArrayBuffer =
function isSharedArrayBuffer(x) {
try {
Reflect.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, "byteLength").get.call(x);
return true;
}
catch(_) {
return false;
}
};
typeChecking.isStrictlyNegativeInteger =
function isStrictlyNegativeInteger(value) {
return typeof value === "number" && value % 1 === 0
&& value < 0 && value > Number.NEGATIVE_INFINITY;
};
typeChecking.isStrictlyNegativeNumber =
function isStrictlyNegativeNumber(value) {
return typeof value === "number" && value < 0;
};
typeChecking.isStrictlyPositiveInteger =
function isStrictlyPositiveInteger(value) {
return typeof value === "number" && value % 1 === 0
&& value > 0 && value < Number.POSITIVE_INFINITY;
};
typeChecking.isStrictlyPositiveNumber =
function isStrictlyPositiveNumber(value) {
return typeof value === "number" && value > 0;
};
typeChecking.isString =
function isString(x) {
return typeof x === "string";
};
typeChecking.isSymbol =
function isSymbol(value) {
return typeof value === "symbol";
};
typeChecking.isTypedArray =
function isTypedArray(arg) {
if(typeof arg !== "object" || arg === null) return false;
try {
Reflect.getOwnPropertyDescriptor(TypedArrayPrototype, "byteLength").get.call(arg);
return true;
}
catch(_) {
return false;
}
};
typeChecking.isWeakMap =
function isWeakMap(o) {
try {
WeakMap.prototype.has.call(o, {});
return true;
}
catch(_) {
return false;
}
};
typeChecking.isWeakSet =
function isWeakSet(o) {
try {
WeakSet.prototype.has.call(o, {});
return true;
}
catch(_) {
return false;
}
};
const descriptionsByTypeName = {
'Array': "an 'Array' object",
'ArrayBuffer': "an 'ArrayBuffer' object",
'ArrayLike': "an array-like value",
'ArrayLikeObject': "an array-like object",
'Boolean': "a boolean",
'Date': "a 'Date' object",
'DuckOf': "a duck of the given 'duckType'",
'Function': "a function",
'GeneratorFunction': "a generator function",
'InstanceOf': "an instance of the given constructor",
'Integer': "an integer",
'Iterable': "an iterable",
'Map': "a 'Map' object",
'MutableArrayLikeObject': "a mutable array-like object",
'NegativeInteger': "a negative integer",
'NegativeNumber': "a negative number",
'NonEmptyArray': "a non-empty Array object",
'NonEmptyArrayLike': "a non-empty array-like value",
'NonEmptyString': "a non-empty string",
'NonNull': "neither 'null' nor 'undefined'",
'NonPrimitive': "a non-primitive value",
'Number': "a number",
'PositiveInteger': "a positive integer",
'PositiveNumber': "a positive number",
'Primitive': "a primitive value",
'RegularNumber': "a regular number",
'RegExp': "a 'RegExp' object",
'SafeInteger': "a safe integer",
'Set': "a 'Set' object",
'SharedArrayBuffer': "a 'SharedArrayBuffer' object",
'StrictlyNegativeInteger': "a strictly negative integer",
'StrictlyNegativeNumber': "a strictly negative number",
'StrictlyPositiveInteger': "a strictly positive integer",
'StrictlyPositiveNumber': "a strictly positive number",
'String': "a string",
'Symbol': "a symbol",
'TypedArray': "a typed array",
'WeakMap': "a 'WeakMap' object",
'WeakSet': "a 'WeakSet' object",
};
const typeNames = Object.keys(descriptionsByTypeName);
for(const typeName of typeNames) {
const description = descriptionsByTypeName[typeName];
if(typeof description !== "string" || description === "") throw new TypeError(`Invalid or missing type description for type '${typeName}'.`);
const predicateName = "is" + typeName;
const predicate = typeChecking[predicateName];
if(typeof predicate !== "function") throw new TypeError(`Invalid or missing predicate: '${predicateName}'.`);
}
for(const typeName of typeNames) {
// eslint-disable-next-line no-loop-func
(function makeExpectation(typeName) {
typeChecking["expect" + typeName] = (function expectation(arg, ...args) {
if(typeChecking.disabled) return;
if(!typeChecking["is" + typeName](arg, ...args)) {
throwNewTypeError(descriptionsByTypeName[typeName], expectation);
}
});
}(typeName));
}
for(const typeName of typeNames) {
// eslint-disable-next-line no-loop-func
(function makePluralExpectation(typeName) {
const description = descriptionsByTypeName[typeName];
const predicate = typeChecking["is" + typeName];
const pluralTypeName = pluralizeTypeName(typeName);
const pluralTypeDescription = "an array (or array-like object) where every element is " + description;
const elementTypeDescription = "every element to be " + description;
function pluralizeTypeName(typeName) {
if(typeName.endsWith("instanceOf")) {
return typeName.slice(0, -("instanceOf".length)) + "instancesOf";
}
else if(typeName.endsWith("Of")) {
return typeName.slice(0, -("Of".length)) + "sOf";
}
else if(typeName.endsWith("s") || typeName.endsWith("x")) {
return typeName + "es";
}
else {
return typeName + "s";
}
}
typeChecking["expect" + pluralTypeName] = (function expectation(values, ...args) {
if(typeChecking.disabled) return;
if(!typeChecking.isArrayLikeObject(values)) {
throwNewTypeError(pluralTypeDescription, expectation);
}
for(const value of values) {
if(!predicate(value, ...args)) {
throwNewTypeError(elementTypeDescription, expectation);
}
}
});
}(typeName));
}
for(const typeName of typeNames) {
// eslint-disable-next-line no-loop-func
(function makeOptionalExpectation(typeName) {
const description = descriptionsByTypeName[typeName];
const predicate = typeChecking["is" + typeName];
typeChecking["expectOptional" + typeName] = (function expectation(arg, ...args) {
if(typeChecking.disabled) return;
if(typeof arg === 'undefined') return;
if(!predicate(arg, ...args)) {
throwNewTypeError(description, expectation);
}
});
}(typeName));
}
return typeChecking;
}())));