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 {
59 if (!(value
instanceof Date)) {
60 return new Date(value
as string);
65 public static convertToInt(value
: unknown
): number {
66 let changedValue
: number = value
as number;
70 if (Number.isSafeInteger(value
)) {
71 return value
as number;
74 if (Utils
.isString(value
)) {
76 changedValue
= parseInt(value
as string);
78 if (typeof value
=== 'number') {
79 changedValue
= Math.trunc(value
);
84 public static convertToFloat(value
: unknown
): number {
85 let changedValue
: number = value
as number;
90 if (Utils
.isString(value
)) {
92 changedValue
= parseFloat(value
as string);
97 public static convertToBoolean(value
: unknown
): boolean {
101 if (typeof value
=== 'boolean') {
104 Utils
.isString(value
) &&
105 ((value
as string).toLowerCase() === 'true' || value
=== '1')
108 } else if (typeof value
=== 'number' && value
=== 1) {
115 public static getRandomFloat(max
= Number.MAX_VALUE
, min
= 0, negative
= false): number {
116 if (max
< min
|| max
< 0 || min
< 0) {
117 throw new RangeError('Invalid interval');
119 const randomPositiveFloat
= crypto
.randomBytes(4).readUInt32LE() / 0xffffffff;
120 const sign
= negative
&& randomPositiveFloat
< 0.5 ? -1 : 1;
121 return sign
* (randomPositiveFloat
* (max
- min
) + min
);
124 public static getRandomInteger(max
= Number.MAX_SAFE_INTEGER
, min
= 0): number {
125 if (max
< min
|| max
< 0 || min
< 0) {
126 throw new RangeError('Invalid interval');
128 max
= Math.floor(max
);
129 if (!Utils
.isNullOrUndefined(min
) && min
!== 0) {
130 min
= Math.ceil(min
);
131 return Math.floor(Utils
.secureRandom() * (max
- min
+ 1)) + min
;
133 return Math.floor(Utils
.secureRandom() * (max
+ 1));
136 public static roundTo(numberValue
: number, scale
: number): number {
137 const roundPower
= Math.pow(10, scale
);
138 return Math.round(numberValue
* roundPower
) / roundPower
;
141 public static truncTo(numberValue
: number, scale
: number): number {
142 const truncPower
= Math.pow(10, scale
);
143 return Math.trunc(numberValue
* truncPower
) / truncPower
;
146 public static getRandomFloatRounded(max
= Number.MAX_VALUE
, min
= 0, scale
= 2): number {
148 return Utils
.roundTo(Utils
.getRandomFloat(max
, min
), scale
);
150 return Utils
.roundTo(Utils
.getRandomFloat(max
), scale
);
153 public static getRandomFloatFluctuatedRounded(
155 fluctuationPercent
: number,
158 if (fluctuationPercent
=== 0) {
159 return Utils
.roundTo(staticValue
, scale
);
161 const fluctuationRatio
= fluctuationPercent
/ 100;
162 return Utils
.getRandomFloatRounded(
163 staticValue
* (1 + fluctuationRatio
),
164 staticValue
* (1 - fluctuationRatio
),
169 public static cloneObject
<T
>(object
: T
): T
{
170 return JSON
.parse(JSON
.stringify(object
)) as T
;
173 public static isIterable
<T
>(obj
: T
): boolean {
174 return obj
? typeof obj
[Symbol
.iterator
] === 'function' : false;
177 public static isString(value
: unknown
): boolean {
178 return typeof value
=== 'string';
181 public static isEmptyString(value
: unknown
): boolean {
182 return Utils
.isString(value
) && (value
as string).trim().length
=== 0;
185 public static isUndefined(value
: unknown
): boolean {
186 return typeof value
=== 'undefined';
189 public static isNullOrUndefined(value
: unknown
): boolean {
190 // eslint-disable-next-line eqeqeq, no-eq-null
191 return value
== null ? true : false;
194 public static isEmptyArray(object
: unknown
| unknown
[]): boolean {
195 if (!Array.isArray(object
)) {
198 if (object
.length
> 0) {
204 public static isEmptyObject(obj
: object
): boolean {
205 if (obj
?.constructor
!== Object) {
208 // Iterates over the keys of an object, if
209 // any exist, return false.
210 for (const _
in obj
) {
216 public static insertAt
= (str
: string, subStr
: string, pos
: number): string =>
217 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
220 * @param [retryNumber=0]
221 * @returns delay in milliseconds
223 public static exponentialDelay(retryNumber
= 0): number {
224 const delay
= Math.pow(2, retryNumber
) * 100;
225 const randomSum
= delay
* 0.2 * Utils
.secureRandom(); // 0-20% of the delay
226 return delay
+ randomSum
;
229 public static async promiseWithTimeout
<T
>(
233 timeoutCallback
: () => void = () => {
234 /* This is intentional */
237 // Create a timeout promise that rejects in timeout milliseconds
238 const timeoutPromise
= new Promise
<never>((_
, reject
) => {
241 reject(timeoutError
);
245 // Returns a race between timeout promise and the passed promise
246 return Promise
.race
<T
>([promise
, timeoutPromise
]);
250 * Generate a cryptographically secure random number in the [0,1[ range
254 public static secureRandom(): number {
255 return crypto
.randomBytes(4).readUInt32LE() / 0x100000000;
258 public static JSONStringifyWithMapSupport(
259 obj
: Record
<string, unknown
> | Record
<string, unknown
>[],
262 return JSON
.stringify(
264 (key
, value
: Record
<string, unknown
>) => {
265 if (value
instanceof Map
) {
278 * Convert websocket error code to human readable string message
280 * @param code websocket error code
281 * @returns human readable string message
283 public static getWebSocketCloseEventStatusString(code
: number): string {
284 if (code
>= 0 && code
<= 999) {
286 } else if (code
>= 1016) {
288 return '(For WebSocket standard)';
289 } else if (code
<= 2999) {
290 return '(For WebSocket extensions)';
291 } else if (code
<= 3999) {
292 return '(For libraries and frameworks)';
293 } else if (code
<= 4999) {
294 return '(For applications)';
297 if (!Utils
.isUndefined(WebSocketCloseEventStatusString
[code
])) {
298 return WebSocketCloseEventStatusString
[code
] as string;