1 import crypto from
'crypto';
3 import { WebSocketCloseEventStatusString
} from
'../types/WebSocket';
5 export default class Utils
{
6 private constructor() {
10 public static logPrefix(prefixString
= ''): string {
11 return new Date().toLocaleString() + prefixString
;
14 public static generateUUID(): string {
15 return crypto
.randomUUID();
18 public static validateUUID(uuid
: string): boolean {
19 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(
24 public static async sleep(milliSeconds
: number): Promise
<NodeJS
.Timeout
> {
25 return new Promise((resolve
) => setTimeout(resolve
as () => void, milliSeconds
));
28 public static formatDurationMilliSeconds(duration
: number): string {
29 duration
= Utils
.convertToInt(duration
);
30 const hours
= Math.floor(duration
/ (3600 * 1000));
31 const minutes
= Math.floor((duration
/ 1000 - hours
* 3600) / 60);
32 const seconds
= duration
/ 1000 - hours
* 3600 - minutes
* 60;
33 let hoursStr
= hours
.toString();
34 let minutesStr
= minutes
.toString();
35 let secondsStr
= seconds
.toString();
38 hoursStr
= '0' + hours
.toString();
41 minutesStr
= '0' + minutes
.toString();
44 secondsStr
= '0' + seconds
.toString();
46 return hoursStr
+ ':' + minutesStr
+ ':' + secondsStr
.substring(0, 6);
49 public static formatDurationSeconds(duration
: number): string {
50 return Utils
.formatDurationMilliSeconds(duration
* 1000);
53 public static convertToDate(value
: unknown
): Date | null | undefined {
54 if (Utils
.isNullOrUndefined(value
)) {
55 return value
as null | undefined;
57 if (value
instanceof Date) {
60 if (Utils
.isString(value
) || typeof value
=== 'number') {
61 return new Date(value
as string | number);
66 public static convertToInt(value
: unknown
): number {
70 let changedValue
: number = value
as number;
71 if (Number.isSafeInteger(value
)) {
72 return value
as number;
74 if (typeof value
=== 'number') {
75 changedValue
= Math.trunc(value
);
77 if (Utils
.isString(value
)) {
78 changedValue
= parseInt(value
as string);
83 public static convertToFloat(value
: unknown
): number {
87 let changedValue
: number = value
as number;
88 if (Utils
.isString(value
)) {
89 changedValue
= parseFloat(value
as string);
94 public static convertToBoolean(value
: unknown
): boolean {
98 if (typeof value
=== 'boolean') {
101 Utils
.isString(value
) &&
102 ((value
as string).toLowerCase() === 'true' || value
=== '1')
105 } else if (typeof value
=== 'number' && value
=== 1) {
112 public static getRandomFloat(max
= Number.MAX_VALUE
, min
= 0, negative
= false): number {
113 if (max
< min
|| max
< 0 || min
< 0) {
114 throw new RangeError('Invalid interval');
116 const randomPositiveFloat
= crypto
.randomBytes(4).readUInt32LE() / 0xffffffff;
117 const sign
= negative
&& randomPositiveFloat
< 0.5 ? -1 : 1;
118 return sign
* (randomPositiveFloat
* (max
- min
) + min
);
121 public static getRandomInteger(max
= Number.MAX_SAFE_INTEGER
, min
= 0): number {
122 if (max
< min
|| max
< 0 || min
< 0) {
123 throw new RangeError('Invalid interval');
125 max
= Math.floor(max
);
126 if (!Utils
.isNullOrUndefined(min
) && min
!== 0) {
127 min
= Math.ceil(min
);
128 return Math.floor(Utils
.secureRandom() * (max
- min
+ 1)) + min
;
130 return Math.floor(Utils
.secureRandom() * (max
+ 1));
133 public static roundTo(numberValue
: number, scale
: number): number {
134 const roundPower
= Math.pow(10, scale
);
135 return Math.round(numberValue
* roundPower
) / roundPower
;
138 public static truncTo(numberValue
: number, scale
: number): number {
139 const truncPower
= Math.pow(10, scale
);
140 return Math.trunc(numberValue
* truncPower
) / truncPower
;
143 public static getRandomFloatRounded(max
= Number.MAX_VALUE
, min
= 0, scale
= 2): number {
145 return Utils
.roundTo(Utils
.getRandomFloat(max
, min
), scale
);
147 return Utils
.roundTo(Utils
.getRandomFloat(max
), scale
);
150 public static getRandomFloatFluctuatedRounded(
152 fluctuationPercent
: number,
155 if (fluctuationPercent
=== 0) {
156 return Utils
.roundTo(staticValue
, scale
);
158 const fluctuationRatio
= fluctuationPercent
/ 100;
159 return Utils
.getRandomFloatRounded(
160 staticValue
* (1 + fluctuationRatio
),
161 staticValue
* (1 - fluctuationRatio
),
166 public static cloneObject
<T
>(object
: T
): T
{
167 return JSON
.parse(JSON
.stringify(object
)) as T
;
170 public static isIterable
<T
>(obj
: T
): boolean {
171 return obj
? typeof obj
[Symbol
.iterator
] === 'function' : false;
174 public static isString(value
: unknown
): boolean {
175 return typeof value
=== 'string';
178 public static isEmptyString(value
: unknown
): boolean {
179 return Utils
.isString(value
) && (value
as string).trim().length
=== 0;
182 public static isUndefined(value
: unknown
): boolean {
183 return typeof value
=== 'undefined';
186 public static isNullOrUndefined(value
: unknown
): boolean {
187 // eslint-disable-next-line eqeqeq, no-eq-null
188 return value
== null ? true : false;
191 public static isEmptyArray(object
: unknown
| unknown
[]): boolean {
192 if (!Array.isArray(object
)) {
195 if (object
.length
> 0) {
201 public static isEmptyObject(obj
: object
): boolean {
202 if (obj
?.constructor
!== Object) {
205 // Iterates over the keys of an object, if
206 // any exist, return false.
207 for (const _
in obj
) {
213 public static insertAt
= (str
: string, subStr
: string, pos
: number): string =>
214 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
217 * @param [retryNumber=0]
218 * @returns delay in milliseconds
220 public static exponentialDelay(retryNumber
= 0): number {
221 const delay
= Math.pow(2, retryNumber
) * 100;
222 const randomSum
= delay
* 0.2 * Utils
.secureRandom(); // 0-20% of the delay
223 return delay
+ randomSum
;
226 public static async promiseWithTimeout
<T
>(
230 timeoutCallback
: () => void = () => {
231 /* This is intentional */
234 // Create a timeout promise that rejects in timeout milliseconds
235 const timeoutPromise
= new Promise
<never>((_
, reject
) => {
238 reject(timeoutError
);
242 // Returns a race between timeout promise and the passed promise
243 return Promise
.race
<T
>([promise
, timeoutPromise
]);
247 * Generate a cryptographically secure random number in the [0,1[ range
251 public static secureRandom(): number {
252 return crypto
.randomBytes(4).readUInt32LE() / 0x100000000;
255 public static JSONStringifyWithMapSupport(
256 obj
: Record
<string, unknown
> | Record
<string, unknown
>[],
259 return JSON
.stringify(
261 (key
, value
: Record
<string, unknown
>) => {
262 if (value
instanceof Map
) {
275 * Convert websocket error code to human readable string message
277 * @param code websocket error code
278 * @returns human readable string message
280 public static getWebSocketCloseEventStatusString(code
: number): string {
281 if (code
>= 0 && code
<= 999) {
283 } else if (code
>= 1016) {
285 return '(For WebSocket standard)';
286 } else if (code
<= 2999) {
287 return '(For WebSocket extensions)';
288 } else if (code
<= 3999) {
289 return '(For libraries and frameworks)';
290 } else if (code
<= 4999) {
291 return '(For applications)';
294 if (!Utils
.isUndefined(WebSocketCloseEventStatusString
[code
])) {
295 return WebSocketCloseEventStatusString
[code
] as string;