1 import crypto from
'node:crypto';
2 import util from
'node:util';
4 import clone from
'just-clone';
6 import Constants from
'./Constants';
7 import { WebSocketCloseEventStatusString
} from
'../types/WebSocket';
9 export default class Utils
{
10 private constructor() {
11 // This is intentional
14 public static logPrefix
= (prefixString
= ''): string => {
15 return `${new Date().toLocaleString()}${prefixString}`;
18 public static generateUUID(): string {
19 return crypto
.randomUUID();
22 public static validateUUID(uuid
: string): boolean {
23 return /^[0-9a
-fA
-F
]{8}-[0-9a
-fA
-F
]{4}-4[0-9a
-fA
-F
]{3}-[0-9a
-fA
-F
]{4}-[0-9a
-fA
-F
]{12}$
/.test(
28 public static async sleep(milliSeconds
: number): Promise
<NodeJS
.Timeout
> {
29 return new Promise((resolve
) => setTimeout(resolve
as () => void, milliSeconds
));
32 public static formatDurationMilliSeconds(duration
: number): string {
33 duration
= Utils
.convertToInt(duration
);
34 const hours
= Math.floor(duration
/ (3600 * 1000));
35 const minutes
= Math.floor((duration
/ 1000 - hours
* 3600) / 60);
36 const seconds
= duration
/ 1000 - hours
* 3600 - minutes
* 60;
37 let hoursStr
= hours
.toString();
38 let minutesStr
= minutes
.toString();
39 let secondsStr
= seconds
.toString();
42 hoursStr
= `0${hours.toString()}`;
45 minutesStr
= `0${minutes.toString()}`;
48 secondsStr
= `0${seconds.toString()}`;
50 return `${hoursStr}:${minutesStr}:${secondsStr.substring(0, 6)}`;
53 public static formatDurationSeconds(duration
: number): string {
54 return Utils
.formatDurationMilliSeconds(duration
* 1000);
57 public static convertToDate(
58 value
: Date | string | number | null | undefined
59 ): Date | null | undefined {
60 if (Utils
.isNullOrUndefined(value
)) {
61 return value
as null | undefined;
63 if (value
instanceof Date) {
66 if (Utils
.isString(value
) || typeof value
=== 'number') {
67 return new Date(value
);
72 public static convertToInt(value
: unknown
): number {
76 let changedValue
: number = value
as number;
77 if (Number.isSafeInteger(value
)) {
78 return value
as number;
80 if (typeof value
=== 'number') {
81 return Math.trunc(value
);
83 if (Utils
.isString(value
)) {
84 changedValue
= parseInt(value
as string);
86 if (isNaN(changedValue
)) {
87 throw new Error(`Cannot convert to integer: ${value.toString()}`);
92 public static convertToFloat(value
: unknown
): number {
96 let changedValue
: number = value
as number;
97 if (Utils
.isString(value
)) {
98 changedValue
= parseFloat(value
as string);
100 if (isNaN(changedValue
)) {
101 throw new Error(`Cannot convert to float: ${value.toString()}`);
106 public static convertToBoolean(value
: unknown
): boolean {
110 if (typeof value
=== 'boolean') {
113 Utils
.isString(value
) &&
114 ((value
as string).toLowerCase() === 'true' || value
=== '1')
117 } else if (typeof value
=== 'number' && value
=== 1) {
124 public static getRandomFloat(max
= Number.MAX_VALUE
, min
= 0, negative
= false): number {
125 if (max
< min
|| max
< 0 || min
< 0) {
126 throw new RangeError('Invalid interval');
128 const randomPositiveFloat
= crypto
.randomBytes(4).readUInt32LE() / 0xffffffff;
129 const sign
= negative
&& randomPositiveFloat
< 0.5 ? -1 : 1;
130 return sign
* (randomPositiveFloat
* (max
- min
) + min
);
133 public static getRandomInteger(max
= Constants
.MAX_RANDOM_INTEGER
, min
= 0): number {
134 max
= Math.floor(max
);
135 if (!Utils
.isNullOrUndefined(min
) && min
!== 0) {
136 min
= Math.ceil(min
);
137 return Math.floor(crypto
.randomInt(min
, max
+ 1));
139 return Math.floor(crypto
.randomInt(max
+ 1));
142 public static roundTo(numberValue
: number, scale
: number): number {
143 const roundPower
= Math.pow(10, scale
);
144 return Math.round(numberValue
* roundPower
) / roundPower
;
147 public static truncTo(numberValue
: number, scale
: number): number {
148 const truncPower
= Math.pow(10, scale
);
149 return Math.trunc(numberValue
* truncPower
) / truncPower
;
152 public static getRandomFloatRounded(max
= Number.MAX_VALUE
, min
= 0, scale
= 2): number {
154 return Utils
.roundTo(Utils
.getRandomFloat(max
, min
), scale
);
156 return Utils
.roundTo(Utils
.getRandomFloat(max
), scale
);
159 public static getRandomFloatFluctuatedRounded(
161 fluctuationPercent
: number,
164 if (fluctuationPercent
=== 0) {
165 return Utils
.roundTo(staticValue
, scale
);
167 const fluctuationRatio
= fluctuationPercent
/ 100;
168 return Utils
.getRandomFloatRounded(
169 staticValue
* (1 + fluctuationRatio
),
170 staticValue
* (1 - fluctuationRatio
),
175 public static isObject(item
: unknown
): boolean {
177 Utils
.isNullOrUndefined(item
) === false &&
178 typeof item
=== 'object' &&
179 Array.isArray(item
) === false
183 public static cloneObject
<T
extends object
>(object
: T
): T
{
184 return clone
<T
>(object
);
187 public static isIterable
<T
>(obj
: T
): boolean {
188 return !Utils
.isNullOrUndefined(obj
) ? typeof obj
[Symbol
.iterator
] === 'function' : false;
191 public static isString(value
: unknown
): boolean {
192 return typeof value
=== 'string';
195 public static isEmptyString(value
: unknown
): boolean {
196 return Utils
.isString(value
) && (value
as string).trim().length
=== 0;
199 public static isUndefined(value
: unknown
): boolean {
200 return value
=== undefined;
203 public static isNullOrUndefined(value
: unknown
): boolean {
204 // eslint-disable-next-line eqeqeq, no-eq-null
205 return value
== null ? true : false;
208 public static isEmptyArray(object
: unknown
| unknown
[]): boolean {
209 if (!Array.isArray(object
)) {
212 if (object
.length
> 0) {
218 public static isEmptyObject(obj
: object
): boolean {
219 if (obj
?.constructor
!== Object) {
222 // Iterates over the keys of an object, if
223 // any exist, return false.
224 for (const _
in obj
) {
230 public static insertAt
= (str
: string, subStr
: string, pos
: number): string =>
231 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
234 * @param retryNumber - the number of retries that have already been attempted
235 * @returns delay in milliseconds
237 public static exponentialDelay(retryNumber
= 0): number {
238 const delay
= Math.pow(2, retryNumber
) * 100;
239 const randomSum
= delay
* 0.2 * Utils
.secureRandom(); // 0-20% of the delay
240 return delay
+ randomSum
;
243 public static isPromisePending(promise
: Promise
<unknown
>): boolean {
244 return util
.inspect(promise
).includes('pending');
247 public static async promiseWithTimeout
<T
>(
251 timeoutCallback
: () => void = () => {
252 /* This is intentional */
255 // Create a timeout promise that rejects in timeout milliseconds
256 const timeoutPromise
= new Promise
<never>((_
, reject
) => {
258 if (Utils
.isPromisePending(promise
)) {
260 // FIXME: The original promise shall be canceled
262 reject(timeoutError
);
266 // Returns a race between timeout promise and the passed promise
267 return Promise
.race
<T
>([promise
, timeoutPromise
]);
271 * Generate a cryptographically secure random number in the [0,1[ range
275 public static secureRandom(): number {
276 return crypto
.randomBytes(4).readUInt32LE() / 0x100000000;
279 public static JSONStringifyWithMapSupport(
280 obj
: Record
<string, unknown
> | Record
<string, unknown
>[] | Map
<unknown
, unknown
>,
283 return JSON
.stringify(
285 (key
, value
: Record
<string, unknown
>) => {
286 if (value
instanceof Map
) {
299 * Convert websocket error code to human readable string message
301 * @param code - websocket error code
302 * @returns human readable string message
304 public static getWebSocketCloseEventStatusString(code
: number): string {
305 if (code
>= 0 && code
<= 999) {
307 } else if (code
>= 1016) {
309 return '(For WebSocket standard)';
310 } else if (code
<= 2999) {
311 return '(For WebSocket extensions)';
312 } else if (code
<= 3999) {
313 return '(For libraries and frameworks)';
314 } else if (code
<= 4999) {
315 return '(For applications)';
318 if (!Utils
.isUndefined(WebSocketCloseEventStatusString
[code
])) {
319 return WebSocketCloseEventStatusString
[code
] as string;