-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathassert.ts
More file actions
2358 lines (2168 loc) · 79.6 KB
/
assert.ts
File metadata and controls
2358 lines (2168 loc) · 79.6 KB
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @ts-check
/// <reference lib="esnext" />
/// <reference lib="esnext.iterator" />
/// <reference lib="dom" />
/// <reference lib="dom.iterable" />
/// <reference lib="dom.asynciterable" />
/// <reference lib="webworker.importscripts" />
"use strict";
/**
* @name assert.js
* @version 1.1.2
* @author Ferenc Czigler
* @see https://github.com/Serrin/assert.js/
* @license MIT https://opensource.org/licenses/MIT
*/
const VERSION = "assert.js v1.1.2";
/*
standard unit testing:
https://wiki.commonjs.org/wiki/Unit_Testing/1.0
Mozilla Assert functions
https://firefox-source-docs.mozilla.org/testing/assert.html
Google Clojure Asserts
https://google.github.io/closure-library/api/goog.asserts.html
*/
/* TypeScript types */
/**
* @description False like values.
* @see https://developer.mozilla.org/en-US/docs/Glossary/Falsy
* Missing values: NaN and document.all
*
* @internal
*/
type Falsy = null | undefined | false | 0 | -0 | 0n | "";
/* type Truthy<T> = Exclude<T, Falsy>; */
/**
* @description Map-like object with string or symbol keys.
*
* @internal
*/
type MapLike = Record<PropertyKey, any>;
/**
* @description string or String object
*
* @internal
*/
type StringLike = string | String;
/**
* @description TypedArray types.
*
* @internal
*/
type TypedArray = Exclude<ArrayBufferView, DataView>;
/**
* Generic comparable types.
*
* @internal
*/
type Comparable = number | bigint | string | boolean;
/**
* @description Options for AssertionError.
*
* @internal
*/
type AssertionErrorOptions = {
message?: unknown,
cause?: unknown,
actual?: unknown;
expected?: unknown;
operator?: string,
stackStartFn?: Function,
diff?: any
};
/**
* @description The result of a test operation, indicating success or failure.
*
* @internal
*/
type TestResult<T> =
| {ok: true, value: T, block: Function, name: string}
| {ok: false, error: Error, block: Function, name: string};
/**
* @description Return the typeof operator result of the given value,
* except return "null" instead of "object" for null.
*
* @internal
*/
type TypeOfTag =
| "null" | "undefined"
| "number" | "bigint" | "boolean" | "string" | "symbol"
| "object" | "function";
/**
* @description Return a more detailed class name of the given value. Similar to typeof but with better handling of built-ins (Array, Date, Map, etc.) and correct "null" classification.
*
* @internal
*/
type ClassOfTag = TypeOfTag | string;
/**
* The expected type(s) for type checking.
*
* @internal
*/
type ExpectedType = string | Function | Array<string | Function>;
/**
* The expected options object for type includes functions
*
* @internal
*/
type IncludesOptions = { keyOrValue: any, value?: any };
/**
* null or undefined
*
* @internal
*/
type Nullish = null | undefined;
/**
* @description Not null or undefined or object or function.
*
* @internal
*/
type NonNullablePrimitive = number | bigint | boolean | string | symbol;
/**
* @description Not object or function.
*
* @internal
*/
type Primitive = Nullish | NonNullablePrimitive;
/**
* @description Object or function.
*
* @internal
*/
type NonPrimitive = object | Function;
/** polyfills **/
/* globalThis; polyfill */
(function (global) {
if (!global.globalThis) {
if (Object.defineProperty) {
Object.defineProperty(global, "globalThis", {
configurable: true, enumerable: false, value: global, writable: true
});
} else {
global.globalThis = global;
}
}
})(typeof this === "object" ? this : Function("return this")());
/* Error.isError(); polyfill */
if (!("isError" in Error)) {
(Error as any).isError = function isError (value: unknown) {
let className =
Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
return (className === "error" || className === "domexception");
};
}
/* internal functions */
/**
* @description Return the typeof operator result of the given value, except the null object ("null" instead of "object").
*
* @param {unknown} value The value to check.
* @returns {TypeOfTag}
* @interal
*/
const _typeOf = (value: unknown): TypeOfTag =>
value === null ? "null" : typeof value;
/* const _typeOf = (value) => value === null ? "null" : typeof value; */
/**
* @description Return the typeof operator result of the given value,except return "null" instead of "object" for null, and provide detailed object class names (Array, Date, etc. and custom classes).
*
* @param {unknown} value - The value to check.
* @returns {ClassOfTag}
* @internal
*/
// @ts-ignore
function _classOf (value: unknown): ClassOfTag {
/* primitives */
const valueType: TypeOfTag = _typeOf(value);
if (valueType !== "object" && valueType !== "function") { return valueType; }
/* objects and functions */
let ctor: ClassOfTag;
try {
ctor = Object.getPrototypeOf(value)?.constructor?.name ?? "Object";
} catch (_e) {
ctor = Object.prototype.toString.call(value).slice(8, -1);
}
return ctor === "Object" || ctor === "Function" ? ctor.toLowerCase() : ctor;
}
/*
console.log(_classOf(null)) //"null"
console.log(_classOf(Object.create(null))) //"object"
console.log(_classOf({})) //"object"
console.log(_classOf(42)) //"number"
console.log(_classOf(Object(42))) //"Number"
console.log(_classOf([])) //"Array"
console.log(_classOf(() => {})) //"function"
console.log(_classOf(async () => {})) //"AsyncFunction"
console.log(_classOf(function* g() {})) //"GeneratorFunction"
console.log(_classOf(new (class Foo {})())) //"Foo"
*/
/**
* @description Checks if the values are deep equal.
*
* @param {unknown} value1 - The value to check.
* @param {unknown} value2 - The value to check.
* @returns {boolean} True if the value are deep equal, false otherwise.
* @internal
*/
function _isDeepStrictEqual (value1: any, value2: any): boolean {
/* helper functions */
const _isObject = (value: unknown): boolean => _typeOf(value) === "object";
const _isSameInstance = (value1: unknown, value2: unknown, Class: Function): boolean =>
value1 instanceof Class && value2 instanceof Class;
const _classof = (value: unknown): string =>
Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
const _ownKeys = (value: MapLike): Array<string | symbol> =>
[...Object.getOwnPropertyNames(value), ...Object.getOwnPropertySymbols(value)];
/* strict equality helper function */
const _isEqual = (value1: unknown, value2: unknown): boolean =>
Object.is(value1, value2);
/* primitives: Boolean, Number, BigInt, String + Function + Symbol */
if (_isEqual(value1, value2)) { return true; }
/* Object Wrappers (Boolean, Number, BigInt, String) */
if (_isObject(value1) && _isPrimitive(value2) && _classof(value1) === typeof value2) {
return _isEqual(value1.valueOf(), value2);
}
if (_isPrimitive(value1) && _isObject(value2) && typeof value1 === _classof(value2)) {
return _isEqual(value1, value2.valueOf());
}
/* type (primitives, object, null, NaN) */
/*if (_deepType(value1) !== _deepType(value2)) { return false; }*/
if (_typeOf(value1) !== _typeOf(value2)) { return false; }
/* objects */
if (_isObject(value1) && _isObject(value2)) {
/* objects / same memory adress */
if (_isEqual(value1, value2)) { return true; }
/* objects / not same constructor */
if (Object.getPrototypeOf(value1).constructor !==
Object.getPrototypeOf(value2).constructor
) {
return false;
}
/* objects / WeakMap + WeakSet */
if (_isSameInstance(value1, value2, WeakMap)
|| _isSameInstance(value1, value2, WeakSet)) {
return _isEqual(value1, value2);
}
/* objects / Wrapper objects: Number, Boolean, String, BigInt */
if (_isSameInstance(value1, value2, Number)
|| _isSameInstance(value1, value2, Boolean)
|| _isSameInstance(value1, value2, String)
|| _isSameInstance(value1, value2, BigInt)) {
return _isEqual(value1.valueOf(), value2.valueOf());
}
/* objects / Array */
if (Array.isArray(value1) && Array.isArray(value2)) {
if (value1.length !== value2.length) { return false; }
if (value1.length === 0) { return true; }
return value1.every((value: unknown, index: any): boolean =>
_isDeepStrictEqual(value, value2[index])
);
}
/* objects / TypedArrays */
if ( _isSameInstance(value1, value2, Int8Array)
|| _isSameInstance(value1, value2, Uint8Array)
|| _isSameInstance(value1, value2, Uint8ClampedArray)
|| _isSameInstance(value1, value2, Int16Array)
|| _isSameInstance(value1, value2, Uint16Array)
|| _isSameInstance(value1, value2, Int32Array)
|| _isSameInstance(value1, value2, Uint32Array)
|| ("Float16Array" in globalThis
? _isSameInstance(value1, value2, Float16Array)
: false
)
|| _isSameInstance(value1, value2, Float32Array)
|| _isSameInstance(value1, value2, Float64Array)
|| _isSameInstance(value1, value2, BigInt64Array)
|| _isSameInstance(value1, value2, BigUint64Array)) {
if (value1.length !== value2.length) { return false; }
if (value1.length === 0) { return true; }
return value1.every((value: unknown, index: any): boolean => _isEqual(value, value2[index]));
}
/* objects / ArrayBuffer */
if (_isSameInstance(value1, value2, ArrayBuffer)) {
if (value1.byteLength !== value2.byteLength) { return false; }
if (value1.byteLength === 0) { return true; }
let xTA = new Int8Array(value1), yTA = new Int8Array(value2);
return xTA.every((value: unknown, index: number): boolean =>
_isEqual(value, yTA[index]));
}
/* objects / DataView */
if (_isSameInstance(value1, value2, DataView)) {
if (value1.byteLength !== value2.byteLength) { return false; }
if (value1.byteLength === 0) { return true; }
for (let index = 0; index < value1.byteLength; index++) {
if (!_isEqual(value1.getUint8(index), value2.getUint8(index))) {
return false;
}
}
return true;
}
/* objects / Map */
if (_isSameInstance(value1, value2, Map)) {
if (value1.size !== value2.size) { return false; }
if (value1.size === 0) { return true; }
return [...value1.keys()].every((value: unknown): boolean =>
_isDeepStrictEqual(value1.get(value), value2.get(value)));
}
/* objects / Set */
if (_isSameInstance(value1, value2, Set)) {
if (value1.size !== value2.size) { return false; }
if (value1.size === 0) { return true; }
return [...value1.keys()].every(
(value: unknown): boolean => value2.has(value)
);
}
/* objects / RegExp */
if (_isSameInstance(value1, value2, RegExp)) {
return _isEqual(value1.lastIndex, value2.lastIndex)
&& _isEqual(value1.flags, value2.flags)
&& _isEqual(value1.source, value2.source);
}
/* objects / Error */
if (_isSameInstance(value1, value2, Error)) {
return _isDeepStrictEqual(
Object.getOwnPropertyNames(value1)
.reduce((acc, k): MapLike => { acc[k] = value1[k]; return acc; }, {}),
Object.getOwnPropertyNames(value2)
.reduce((acc, k): MapLike => { acc[k] = value2[k]; return acc; }, {})
);
}
/* objects / Date */
if (_isSameInstance(value1, value2, Date)) {
return _isEqual(+value1, +value2);
}
/* objects / Proxy -> not detectable */
/* objects / Objects */
let value1Keys: Array<string | symbol> = _ownKeys(value1);
let value2Keys: Array<string | symbol> = _ownKeys(value2);
if (value1Keys.length !== value2Keys.length) { return false; }
if (value1Keys.length === 0) { return true; }
return value1Keys.every((key: string | symbol): boolean =>
_isDeepStrictEqual(value1[key], value2[key]));
}
/* default return false */
return false;
}
/**
* @description Checks if the given value is the given type(s).
*
* @param {any} value - The value to check.
* @param {ExpectedType | undefined} [expectedType] - The type(s) for checking.
* @param {boolean} Throw Default false.
* @returns {boolean} True if the value is the given type(s), false otherwise.
* @throws If Throw is true and type checking is failed.
* @internal
*/
function _isType (
value: any,
expectedType?: ExpectedType | undefined,
Throw: boolean = false): string | Function | boolean {
/* Validate `expected` */
if (!(["string", "function", "undefined"].includes(typeof expectedType))
&& !Array.isArray(expectedType)) {
throw new TypeError(
`[isType] TypeError: expectedType must be string, function, array or undefined. Got ${typeof expectedType}`
);
}
/* Validate `Throw` */
if (typeof Throw !== "boolean") {
throw new TypeError(
`[isType] TypeError: Throw has to be a boolean. Got ${typeof Throw}`
);
}
/* Determine the type of `value` */
const vType: string = _typeOf(value);
/* If no expected type provided, return type or constructor */
if (expectedType == null) {
return vType === "object"
? Object.getPrototypeOf(value)?.constructor ?? "object"
: vType;
}
/* Normalize expected to an array */
let expectedArray: Array<string | Function> =
Array.isArray(expectedType) ? expectedType : [expectedType];
/* Checks against expected types or constructors */
let matched: boolean = expectedArray.some(
function (item: string | Function) {
if (typeof item === "string") { return vType === item; }
if (typeof item === "function") { return value != null && value instanceof item; }
/* validate expected array elements */
throw new TypeError(
`[isType] TypeError: expectedType array elements have to be a string or function. Got ${typeof item}`
);
}
);
/* Throw error if mismatch and `Throw` is true */
if (Throw && !matched) {
let vName: string =
value.toString ? value.toString() : Object.prototype.toString.call(value);
let eNames: string = expectedArray.map((item: any): string =>
(typeof item === "string" ? item.toString() : item.name ?? "anonymous")
).join(", ");
throw new TypeError(`[isType] TypeError: ${vName} is not a ${eNames}`);
}
return matched;
}
/**
* @description Checks if the given value is an object.
*
* @param {unknown} value - The value to check.
* @returns {boolean} True if the value is an object, false otherwise.
* @internal
*/
const _isObject = (value: unknown): value is object =>
value != null && typeof value === "object";
/**
* @description Checks if the given value is an error.
*
* @param {unknown} value - The value to check.
* @returns {boolean} True if the value is an error, false otherwise.
* @internal
*/
const _isError = (value: unknown): value is Error =>
Error.isError ? Error.isError(value) : value instanceof Error;
/**
* @description This function is a general purpose, type safe, predictable stringifier. Converts a value into a human-readable string for error messages Handles symbols, functions, nullish, circular references, etc.
*
* @param {unknown} value The value to check.
* @returns {string}
* @internal
*/
function _toSafeString (value: unknown): string {
const seen = new WeakSet<object>();
const replacer = (_key: string, value: unknown): unknown => {
if (typeof value === "function") {
return `[Function: ${value.name || "anonymous"}]`;
}
if (typeof value === "symbol") { return value.toString(); }
if (value instanceof Date) { return `Date(${value.toISOString()})`; }
if (_isError(value)) {
return `${value.name}: ${value.message}, ${value.stack ?? ""}`;
}
if (value && _isObject(value)) {
if (seen.has(value)) { return "[Circular]" };
seen.add(value);
}
return value;
};
if (["undefined", "null", "string", "number", "boolean", "bigint"]
.includes(_typeOf(value))) {
return String(value);
}
if (Array.isArray(value)) {
return `[${value.map(v => _toSafeString(v)).join(", ")}]`;
}
if (value instanceof Map) {
return `Map(${value.size}){${Array.from(value.entries()).map(([k, v]): string => `${_toSafeString(k)} => ${_toSafeString(v)}`).join(", ")}}`;
}
if (value instanceof Set) {
return `Set(${value.size}){${Array.from(value.values()).map(v => _toSafeString(v)).join(", ")}}`;
}
try {
return JSON.stringify(value, replacer) ?? String(value);
} catch (_e) {
return String(value);
}
}
/**
* @description Checks value1 is less than value2.
*
* @param {Comparable} value1 The value1 to check.
* @param {Comparable} value2 The value2 to check.
* @returns {boolean} value1 is less than value2.
* @internal
*/
const _isLessThan = (value1: Comparable, value2: Comparable): boolean =>
_typeOf(value1) === _typeOf(value2) && value1 < value2;
/**
* @description Checks value is greater than or equal min and value is less than or equal max.
*
* @param {Comparable} value The value1 to check.
* @param {Comparable} min The value2 to check.
* @param {Comparable} max The value2 to check.
* @returns {boolean} value is greater than or equal min and value is less than or equal max.
* @internal
*/
const _inRange = (value: Comparable, min: Comparable, max: Comparable): boolean =>
_typeOf(value) === _typeOf(min)
&& _typeOf(min) === _typeOf(max)
&& (
(min < value && value < max)
|| Object.is(value, min)
|| Object.is(value, max)
);
/**
* Checks if a key or value exists in a container.
*
* @param {any} container The container to check.
* @param {any} keyOrValue The key or value to look for.
* @param {unknown} valueIfKey The value to check if the key exists.
* @returns True if the key or value exists, false otherwise.
* @internal
*/
function _includes<T extends object, K extends keyof T>(container: T, keyOrValue: K, valueIfKey?: T[K]): boolean;
function _includes<T>(container: T[], value: T): boolean;
function _includes<T extends ArrayBufferView>(container: T, value: number): boolean;
function _includes<K, V>(container: Map<K, V>, keyOrValue: K, valueIfKey?: V): boolean;
function _includes<K extends object, V>(container: WeakMap<K, V>, keyOrValue: K): boolean;
function _includes<T>(container: Set<T>, value: T): boolean;
function _includes<T extends object>(container: WeakSet<T>, valueIfKey: T): boolean;
function _includes<T>(container: Iterable<T>, keyOrValue: T): boolean;
function _includes<T>(container: Iterator<T>, keyOrValue: T): boolean;
function _includes<T>(container: IterableIterator<T>, keyOrValue: T): boolean;
function _includes<T>(container: string, keyOrValue: unknown): boolean;
function _includes(container: any, keyOrValue: any, valueIfKey?: unknown): boolean {
/* String */
if (typeof container === "string" || container instanceof String) {
return String(container).includes(keyOrValue);
}
/* Check for primitives, null, undefined */
if (container == null || typeof container !== "object") { return false; }
/* Map + WeakMap */
if (container instanceof Map || container instanceof WeakMap) {
if (!container.has(keyOrValue)) { return false; }
return valueIfKey === undefined || Object.is(container.get(keyOrValue), valueIfKey);
}
/* WeakSet */
if (container instanceof WeakSet) { return container.has(keyOrValue); }
/* Iterator */
if (typeof (container).next === "function") {
let it = container;
let res = it.next();
while (!res.done) {
if (Object.is(res.value, keyOrValue)) { return true; }
res = it.next();
}
return false;
}
/* Array + TypedArray + Set + Iterables */
if (Array.isArray(container)
|| ArrayBuffer.isView(container)
|| container instanceof Set
|| typeof (container)[Symbol.iterator] === "function") {
let it = container[Symbol.iterator]();
let res = it.next();
while (!res.done) {
if (Object.is(res.value, keyOrValue)) { return true; }
res = it.next();
}
return false;
}
/* Plain object */
if (!Object.hasOwn(container, keyOrValue)) { return false; }
return valueIfKey === undefined || Object.is(container[keyOrValue], valueIfKey);
}
/**
* Checks if a value is empty.
*
* - `null`, `undefined`, and `NaN` are empty.
* - Arrays, TypedArrays, and strings are empty if length === 0.
* - Maps and Sets are empty if size === 0.
* - ArrayBuffer and DataView are empty if byteLength === 0.
* - Iterable objects are empty if they have no elements.
* - Plain objects are empty if they have no own properties.
*
* @param {any} value The value to check.
* @returns boolean
* @internal
*/
function _isEmpty (value: any): boolean {
/**
* Checks if a value is a TypedArray (Int8Array, etc.).
*
* @param {unknown} value The value to check.
* @returns boolean
*/
const _isTypedArray = (value: unknown): value is TypedArray =>
ArrayBuffer.isView(value) && !(value instanceof DataView);
/* Check undefined, null, NaN */
if (value == null || Number.isNaN(value)) { return true; }
/* Check Array, TypedArrays, string, String */
if (Array.isArray(value)
|| _isTypedArray(value)
|| typeof value === "string"
|| value instanceof String) {
return (value as any).length === 0;
}
/* Checks Map and Set */
if (value instanceof Map || value instanceof Set) { return value.size === 0; }
/* Check ArrayBuffer and DataView */
if (value instanceof ArrayBuffer || value instanceof DataView) {
return value.byteLength === 0;
}
/* Check Iterable objects */
if (typeof value[Symbol.iterator] === "function") {
const it = value[Symbol.iterator]();
return it.next().done; /* avoids consuming entire iterator */
}
/* Check Iterator objects */
if ("Iterator" in globalThis ? (value instanceof Iterator)
: (_typeOf(value) === "object" && typeof value.next === "function")) {
try {
/* Has at least one element */
for (const _ of value) { return false; }
return true;
} catch { /* Not iterable */ }
}
/* Other objects - check own properties (including symbols) */
if (_isObject(value)) {
const keys: unknown[] = [
...Object.getOwnPropertyNames(value),
...Object.getOwnPropertySymbols(value)
];
if (keys.length === 0) return true;
/* Special case: object with single "length" property that is 0 */
if (keys.length === 1
&& keys[0] === "length"
&& (value as { length?: unknown }).length === 0) {
return true;
}
}
/* Return default false */
return false;
}
/**
* @description Checks if the given value is Primitive.
*
* @param {unknown} value - The value to check.
* @returns True if the value is Primitive, false otherwise.
* @internal
*/
const _isPrimitive = (value: unknown): value is Primitive =>
_typeOf(value) !== "object" && _typeOf(value) !== "function";
/**
* @description If value is an error, then it will be thrown.
*
* @param {unknown} value - The value to check.
* @param {Function} caller
* @returns {void}
* @internal
*/
function _errorCheck (value: unknown, caller: Function): void {
if (_isError(value)) {
if (typeof (Error as any).captureStackTrace === "function") {
(Error as any).captureStackTrace(caller, value);
}
throw value;
}
}
/* exported functions */
/*
standard unit testing:
https://wiki.commonjs.org/wiki/Unit_Testing/1.0
*/
class AssertionError extends Error {
actual?: unknown;
expected?: unknown;
operator?: string;
code?: string;
constructor(message?: string, options?: AssertionErrorOptions) {
super(message);
this.code = "ERR_ASSERTION";
this.name = "AssertionError";
this.message = message ?? "AssertionError";
this.cause = message ?? "AssertionError";
if (options != null && typeof options === "object") {
this.actual = options?.actual;
this.expected = options?.expected;
this.operator = options?.operator;
}
/* capture stack properly */
if (typeof (Error as any).captureStackTrace === "function") {
(Error as any).captureStackTrace(this, AssertionError);
}
}
}
/**
* @description Ensures that `condition` is truthy. Throws an `AssertionError` if falsy.
*
* @param {unknown} condition The value to check.
* @param {unknown} [message] - Optional message or Error to throw.
* @returns {void}
* @throws {assert.AssertionError} If assertion is failed.
*/
function assert (condition: unknown, message?: unknown): asserts condition {
if (!condition) {
_errorCheck(message, assert);
let errorMessage =
`[assert] Assertion failed: ${_toSafeString(condition)} should be truly${message ? " - " + _toSafeString(message) : ""}`;
throw new assert.AssertionError(errorMessage, {
message: errorMessage,
cause: errorMessage,
actual: condition,
expected: true,
operator: "=="
});
}
}
/**
* @description Alias for `assert(condition, [message: string | Error]);`.
*
* @param {unknown} condition The value to check.
* @param {unknown} [message] - Optional message or Error to throw.
* @returns {void}
* @throws {assert.AssertionError} If assertion is failed.
*/
function ok (condition: unknown, message?: unknown): asserts condition {
assert(condition, message);
}
/**
* @description `assert.equal(actual, expected, [message: string | Error]);`
*
* @param {unknown} actual The actual value to check.
* @param {unknown} expected The expected value to check.
* @param {unknown} [message] - Optional message or Error to throw.
* @returns {void}
* @throws {assert.AssertionError} If assertion is failed.
*/
function equal (actual: unknown, expected: unknown, message?: unknown): void {
if (actual != expected) {
_errorCheck(message, equal);
let errorMessage =
`[equal] Assertion failed: ${_toSafeString(actual)} and ${_toSafeString(expected)} should be equal${message ? " - " + _toSafeString(message) : ""}`;
throw new assert.AssertionError(errorMessage, {
message: errorMessage,
cause: errorMessage,
actual: actual,
expected: expected,
operator: "!="
});
}
}
/**
* @description Inverse of `equal(actual, expected, [message: string | Error]);`.
*
* @param {unknown} actual The actual value to check.
* @param {unknown} expected The expected value to check.
* @param {unknown} [message] - Optional message or Error to throw.
* @returns {void}
* @throws {assert.AssertionError} If assertion is failed.
*/
function notEqual (actual: unknown, expected: unknown, message?: unknown): void {
if (actual == expected) {
_errorCheck(message, notEqual);
let errorMessage =
`[notEqual] Assertion failed: ${_toSafeString(actual)} and ${_toSafeString(expected)} should be equal${message ? " - " + _toSafeString(message) : ""}`;
throw new assert.AssertionError(errorMessage, {
message: errorMessage,
cause: errorMessage,
actual: actual,
expected: expected,
operator: "=="
});
}
}
/**
* @description Strict equality (`Object.is();`).
*
* @param {unknown} actual The actual value to check.
* @param {unknown} expected The expected value to check.
* @param {unknown} [message] - Optional message or Error to throw.
* @returns {void}
* @throws {assert.AssertionError} If assertion is failed.
*/
function strictEqual (actual: unknown, expected: unknown, message?: unknown): void {
if (!Object.is(actual, expected)) {
_errorCheck(message, strictEqual);
let errorMessage =
`[strictEqual] Assertion failed: ${_toSafeString(actual)} and ${_toSafeString(expected)} should be strictly equal${message ? " - " + _toSafeString(message) : ""}`;
throw new assert.AssertionError(errorMessage, {
message: errorMessage,
cause: errorMessage,
actual: actual,
expected: expected,
operator: "strictEqual"
});
}
}
/**
* @description Inverse of `strictEqual(actual, expected, [message: string | Error]);`.
*
* @param {unknown} actual The actual value to check.
* @param {unknown} expected The expected value to check.
* @param {unknown} [message] - Optional message or Error to throw.
* @returns {void}
* @throws {assert.AssertionError} If assertion is failed.
*/
function notStrictEqual (actual: unknown, expected: unknown, message?: unknown): void {
if (Object.is(actual, expected)) {
_errorCheck(message, notStrictEqual);
let errorMessage =
`[notStrictEqual] Assertion failed: ${_toSafeString(actual)} and ${_toSafeString(expected)} should not be strictly equal${message ? " - " + _toSafeString(message) : ""}`;
throw new assert.AssertionError(errorMessage, {
message: errorMessage,
cause: errorMessage,
actual: actual,
expected: expected,
operator: "notStrictEqual"
});
}
}
/**
* @description Deep equality check.
*
* @param {unknown} actual The actual value to check.
* @param {unknown} expected The expected value to check.
* @param {unknown} [message] - Optional message or Error to throw.
* @returns {void}
* @throws {assert.AssertionError} If assertion is failed.
*/
function deepEqual (actual: unknown, expected: unknown, message?: unknown): void {
if (!_isDeepStrictEqual(actual, expected)) {
_errorCheck(message, deepEqual);
let errorMessage =
`[deepEqual] Assertion failed: ${_toSafeString(actual)} and ${_toSafeString(expected)} should be deep equal${message ? " - " + _toSafeString(message) : ""}`;
throw new assert.AssertionError(errorMessage, {
message: errorMessage,
cause: errorMessage,
actual: actual,
expected: expected,
operator: "deepEqual"
});
}
}
/**
* @description Inverse of `deepEqual(actual, expected, [message: string | Error]);`.
*
* @param {unknown} actual The actual value to check.
* @param {unknown} expected The expected value to check.
* @param {unknown} [message] - Optional message or Error to throw.
* @returns {void}
* @throws {assert.AssertionError} If assertion is failed.
*/
function notDeepEqual (actual: unknown, expected: unknown, message?: unknown): void {
if (_isDeepStrictEqual(actual, expected)) {
_errorCheck(message, notDeepEqual);
let errorMessage =
`[notDeepEqual] Assertion failed: ${_toSafeString(actual)} and ${_toSafeString(expected)} should not be deep equal${message ? " - " + _toSafeString(message) : ""}`;
throw new assert.AssertionError(errorMessage, {
message: errorMessage,
cause: errorMessage,
actual: actual,
expected: expected,
operator: "notDeepEqual"
});
}
}
/**
* @description Ensures that a function throws.
*
* @param {Function} block
* @param {unknown} Error_opt
* @param {unknown} [message] - Optional message or Error to throw.
* @returns {Error | undefined}
* @throws {assert.AssertionError} If assertion is failed.
*/
function throws (block: Function, Error_opt?: unknown, message?: unknown): Error | undefined {
let thrownError: any = undefined;
try {
block();
} catch (catchedError) {
thrownError = catchedError as Error;
}
if (!thrownError) {
let errorMessage =
`[throws] Assertion failed: function did not throw${message ? " - " + _toSafeString(message) : ""}`;
throw new assert.AssertionError(errorMessage, {
message: errorMessage,
cause: errorMessage,
operator: "throws"
});
}
/* If Error_opt is provided, check the thrown error */
if (Error_opt) {
const errorMatches =
(typeof Error_opt === "function" && thrownError instanceof Error_opt)
|| (typeof Error_opt === "string" && thrownError?.message?.includes(Error_opt))
|| (Error_opt instanceof RegExp && Error_opt.test(thrownError?.message));
if (!errorMatches) {
let errorMessage =
`[throws] Assertion failed: function threw unexpected error: ${_toSafeString(thrownError)}${message ? " - " + _toSafeString(message) : ""}`;
throw new assert.AssertionError(errorMessage, {
message: errorMessage,
cause: thrownError,
actual: thrownError,
expected: Error_opt,
operator: "throws"
});
}
}
return thrownError;
}
/**
* @description Asserts that an async function or Promise rejects.
*
* @param {(() => Promise<unknown>) | Promise<unknown>} block - Async function or promise expected to reject.
* @param {ErrorConstructor | string | RegExp} [Error_opt] - Expected error type, substring, or pattern.
* @param {unknown} [message] - Optional custom message or Error.
* @returns {Promise<unknown>} - Resolves with the rejection reason if assertion passes.
* @throws {assert.AssertionError} If assertion is failed.
*/
async function rejects (block: Function | Promise<unknown>, Error_opt?: unknown, message?: unknown): Promise<unknown> {
let rejectedError: any;
try {
const result = typeof block === "function" ? await block() : await block;
/* If we reach here, it resolved successfully */
let errorMessage =
`[rejects] Assertion failed: function/promise did not reject${message ? " - " + _toSafeString(message) : ""}`;
throw new assert.AssertionError(errorMessage, {
message: errorMessage,
cause: result,
expected: Error_opt,
operator: "rejects"
});
} catch (catchedError) {
rejectedError = catchedError;