Commit | Line | Data |
---|---|---|
c37528f1 | 1 | import crypto from 'crypto'; |
8114d10e | 2 | |
5e3cb728 JB |
3 | import { WebSocketCloseEventStatusString } from '../types/WebSocket'; |
4 | ||
3f40bc9c | 5 | export default class Utils { |
d5bd1c00 JB |
6 | private constructor() { |
7 | // This is intentional | |
8 | } | |
9 | ||
0f16a662 | 10 | public static logPrefix(prefixString = ''): string { |
147d0e0f JB |
11 | return new Date().toLocaleString() + prefixString; |
12 | } | |
13 | ||
0f16a662 | 14 | public static generateUUID(): string { |
03eacbe5 JB |
15 | return crypto.randomUUID(); |
16 | } | |
17 | ||
18 | public static validateUUID(uuid: string): boolean { | |
8bd02502 JB |
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( |
20 | uuid | |
21 | ); | |
7dde0b73 JB |
22 | } |
23 | ||
0f16a662 | 24 | public static async sleep(milliSeconds: number): Promise<NodeJS.Timeout> { |
5f8a4fd6 | 25 | return new Promise((resolve) => setTimeout(resolve as () => void, milliSeconds)); |
7dde0b73 JB |
26 | } |
27 | ||
d7d1db72 JB |
28 | public static formatDurationMilliSeconds(duration: number): string { |
29 | duration = Utils.convertToInt(duration); | |
30 | const hours = Math.floor(duration / (3600 * 1000)); | |
e7aeea18 JB |
31 | const minutes = Math.floor((duration / 1000 - hours * 3600) / 60); |
32 | const seconds = duration / 1000 - hours * 3600 - minutes * 60; | |
a3868ec4 JB |
33 | let hoursStr = hours.toString(); |
34 | let minutesStr = minutes.toString(); | |
35 | let secondsStr = seconds.toString(); | |
d7d1db72 JB |
36 | |
37 | if (hours < 10) { | |
38 | hoursStr = '0' + hours.toString(); | |
39 | } | |
40 | if (minutes < 10) { | |
41 | minutesStr = '0' + minutes.toString(); | |
42 | } | |
43 | if (seconds < 10) { | |
b322b8b4 | 44 | secondsStr = '0' + seconds.toString(); |
d7d1db72 | 45 | } |
b322b8b4 | 46 | return hoursStr + ':' + minutesStr + ':' + secondsStr.substring(0, 6); |
9ac86a7e JB |
47 | } |
48 | ||
d7d1db72 JB |
49 | public static formatDurationSeconds(duration: number): string { |
50 | return Utils.formatDurationMilliSeconds(duration * 1000); | |
7dde0b73 JB |
51 | } |
52 | ||
0f16a662 | 53 | public static convertToDate(value: unknown): Date { |
560bcf5b | 54 | // Check |
6af9012e | 55 | if (!value) { |
73d09045 | 56 | return value as Date; |
560bcf5b JB |
57 | } |
58 | // Check Type | |
6af9012e | 59 | if (!(value instanceof Date)) { |
73d09045 | 60 | return new Date(value as string); |
7dde0b73 | 61 | } |
6af9012e | 62 | return value; |
7dde0b73 JB |
63 | } |
64 | ||
0f16a662 | 65 | public static convertToInt(value: unknown): number { |
73d09045 | 66 | let changedValue: number = value as number; |
72766a82 | 67 | if (!value) { |
7dde0b73 JB |
68 | return 0; |
69 | } | |
72766a82 | 70 | if (Number.isSafeInteger(value)) { |
95926c9b | 71 | return value as number; |
72766a82 | 72 | } |
7dde0b73 | 73 | // Check |
087a502d | 74 | if (Utils.isString(value)) { |
7dde0b73 | 75 | // Create Object |
73d09045 | 76 | changedValue = parseInt(value as string); |
7dde0b73 | 77 | } |
72766a82 | 78 | return changedValue; |
7dde0b73 JB |
79 | } |
80 | ||
0f16a662 | 81 | public static convertToFloat(value: unknown): number { |
73d09045 | 82 | let changedValue: number = value as number; |
72766a82 | 83 | if (!value) { |
7dde0b73 JB |
84 | return 0; |
85 | } | |
86 | // Check | |
087a502d | 87 | if (Utils.isString(value)) { |
7dde0b73 | 88 | // Create Object |
73d09045 | 89 | changedValue = parseFloat(value as string); |
7dde0b73 | 90 | } |
72766a82 | 91 | return changedValue; |
7dde0b73 JB |
92 | } |
93 | ||
0f16a662 | 94 | public static convertToBoolean(value: unknown): boolean { |
a6e68f34 JB |
95 | let result = false; |
96 | // Check boolean | |
97 | if (value) { | |
98 | // Check the type | |
99 | if (typeof value === 'boolean') { | |
100 | // Already a boolean | |
101 | result = value; | |
102 | } else { | |
103 | // Convert | |
e7aeea18 | 104 | result = value === 'true'; |
a6e68f34 JB |
105 | } |
106 | } | |
107 | return result; | |
108 | } | |
109 | ||
b5e5892d | 110 | public static getRandomFloat(max = Number.MAX_VALUE, min = 0, negative = false): number { |
b3aa9f53 | 111 | if (max < min || max < 0 || min < 0) { |
b322b8b4 JB |
112 | throw new RangeError('Invalid interval'); |
113 | } | |
fd00fa2e | 114 | const randomPositiveFloat = crypto.randomBytes(4).readUInt32LE() / 0xffffffff; |
e7aeea18 | 115 | const sign = negative && randomPositiveFloat < 0.5 ? -1 : 1; |
fd00fa2e | 116 | return sign * (randomPositiveFloat * (max - min) + min); |
560bcf5b JB |
117 | } |
118 | ||
b5e5892d | 119 | public static getRandomInteger(max = Number.MAX_SAFE_INTEGER, min = 0): number { |
b3aa9f53 | 120 | if (max < min || max < 0 || min < 0) { |
a3868ec4 JB |
121 | throw new RangeError('Invalid interval'); |
122 | } | |
fd00fa2e | 123 | max = Math.floor(max); |
1f86b121 | 124 | if (!Utils.isNullOrUndefined(min) && min !== 0) { |
fd00fa2e | 125 | min = Math.ceil(min); |
c37528f1 | 126 | return Math.floor(Utils.secureRandom() * (max - min + 1)) + min; |
7dde0b73 | 127 | } |
c37528f1 | 128 | return Math.floor(Utils.secureRandom() * (max + 1)); |
560bcf5b JB |
129 | } |
130 | ||
0f16a662 | 131 | public static roundTo(numberValue: number, scale: number): number { |
ad3de6c4 | 132 | const roundPower = Math.pow(10, scale); |
035742f7 | 133 | return Math.round(numberValue * roundPower) / roundPower; |
560bcf5b JB |
134 | } |
135 | ||
0f16a662 | 136 | public static truncTo(numberValue: number, scale: number): number { |
6d3a11a0 | 137 | const truncPower = Math.pow(10, scale); |
035742f7 | 138 | return Math.trunc(numberValue * truncPower) / truncPower; |
6d3a11a0 JB |
139 | } |
140 | ||
b5e5892d | 141 | public static getRandomFloatRounded(max = Number.MAX_VALUE, min = 0, scale = 2): number { |
560bcf5b JB |
142 | if (min) { |
143 | return Utils.roundTo(Utils.getRandomFloat(max, min), scale); | |
144 | } | |
145 | return Utils.roundTo(Utils.getRandomFloat(max), scale); | |
7dde0b73 JB |
146 | } |
147 | ||
e7aeea18 JB |
148 | public static getRandomFloatFluctuatedRounded( |
149 | staticValue: number, | |
150 | fluctuationPercent: number, | |
151 | scale = 2 | |
152 | ): number { | |
9ccca265 JB |
153 | if (fluctuationPercent === 0) { |
154 | return Utils.roundTo(staticValue, scale); | |
155 | } | |
97ef739c | 156 | const fluctuationRatio = fluctuationPercent / 100; |
e7aeea18 JB |
157 | return Utils.getRandomFloatRounded( |
158 | staticValue * (1 + fluctuationRatio), | |
159 | staticValue * (1 - fluctuationRatio), | |
160 | scale | |
161 | ); | |
9ccca265 JB |
162 | } |
163 | ||
0f16a662 | 164 | public static cloneObject<T>(object: T): T { |
e56aa9a4 | 165 | return JSON.parse(JSON.stringify(object)) as T; |
2e6f5966 | 166 | } |
facd8ebd | 167 | |
0f16a662 | 168 | public static isIterable<T>(obj: T): boolean { |
7558b3a6 | 169 | return obj ? typeof obj[Symbol.iterator] === 'function' : false; |
67e9cccf JB |
170 | } |
171 | ||
0f16a662 | 172 | public static isString(value: unknown): boolean { |
560bcf5b JB |
173 | return typeof value === 'string'; |
174 | } | |
175 | ||
e8191622 | 176 | public static isEmptyString(value: unknown): boolean { |
87f82a94 | 177 | return Utils.isString(value) && (value as string).trim().length === 0; |
e8191622 JB |
178 | } |
179 | ||
0f16a662 | 180 | public static isUndefined(value: unknown): boolean { |
ead548f2 JB |
181 | return typeof value === 'undefined'; |
182 | } | |
183 | ||
0f16a662 | 184 | public static isNullOrUndefined(value: unknown): boolean { |
7558b3a6 JB |
185 | // eslint-disable-next-line eqeqeq, no-eq-null |
186 | return value == null ? true : false; | |
facd8ebd | 187 | } |
4a56deef | 188 | |
45999aab | 189 | public static isEmptyArray(object: unknown | unknown[]): boolean { |
a2111e8d | 190 | if (!Array.isArray(object)) { |
30e27491 | 191 | return true; |
fd1ee77c | 192 | } |
45999aab | 193 | if (object.length > 0) { |
4a56deef JB |
194 | return false; |
195 | } | |
196 | return true; | |
197 | } | |
7abfea5f | 198 | |
94ec7e96 | 199 | public static isEmptyObject(obj: object): boolean { |
5e5ba121 | 200 | if (obj?.constructor !== Object) { |
d20581ee JB |
201 | return false; |
202 | } | |
87f82a94 JB |
203 | // Iterates over the keys of an object, if |
204 | // any exist, return false. | |
205 | for (const _ in obj) { | |
206 | return false; | |
207 | } | |
208 | return true; | |
7abfea5f | 209 | } |
7ec46a9a | 210 | |
e7aeea18 JB |
211 | public static insertAt = (str: string, subStr: string, pos: number): string => |
212 | `${str.slice(0, pos)}${subStr}${str.slice(pos)}`; | |
032d6efc JB |
213 | |
214 | /** | |
81797102 JB |
215 | * @param [retryNumber=0] |
216 | * @returns delay in milliseconds | |
032d6efc | 217 | */ |
0f16a662 | 218 | public static exponentialDelay(retryNumber = 0): number { |
032d6efc | 219 | const delay = Math.pow(2, retryNumber) * 100; |
c37528f1 | 220 | const randomSum = delay * 0.2 * Utils.secureRandom(); // 0-20% of the delay |
032d6efc JB |
221 | return delay + randomSum; |
222 | } | |
32a1eb7a | 223 | |
6d9abcc2 | 224 | public static async promiseWithTimeout<T>( |
e7aeea18 JB |
225 | promise: Promise<T>, |
226 | timeoutMs: number, | |
227 | timeoutError: Error, | |
228 | timeoutCallback: () => void = () => { | |
229 | /* This is intentional */ | |
230 | } | |
6d9abcc2 JB |
231 | ): Promise<T> { |
232 | // Create a timeout promise that rejects in timeout milliseconds | |
233 | const timeoutPromise = new Promise<never>((_, reject) => { | |
234 | setTimeout(() => { | |
ed0f8380 | 235 | timeoutCallback(); |
6d9abcc2 JB |
236 | reject(timeoutError); |
237 | }, timeoutMs); | |
238 | }); | |
239 | ||
240 | // Returns a race between timeout promise and the passed promise | |
241 | return Promise.race<T>([promise, timeoutPromise]); | |
242 | } | |
243 | ||
c37528f1 | 244 | /** |
0f16a662 | 245 | * Generate a cryptographically secure random number in the [0,1[ range |
c37528f1 JB |
246 | * |
247 | * @returns | |
248 | */ | |
0f16a662 | 249 | public static secureRandom(): number { |
c37528f1 JB |
250 | return crypto.randomBytes(4).readUInt32LE() / 0x100000000; |
251 | } | |
fe791818 JB |
252 | |
253 | public static JSONStringifyWithMapSupport( | |
254 | obj: Record<string, unknown> | Record<string, unknown>[], | |
255 | space?: number | |
256 | ): string { | |
257 | return JSON.stringify( | |
258 | obj, | |
259 | (key, value: Record<string, unknown>) => { | |
260 | if (value instanceof Map) { | |
261 | return { | |
262 | dataType: 'Map', | |
263 | value: [...value], | |
264 | }; | |
265 | } | |
266 | return value; | |
267 | }, | |
268 | space | |
269 | ); | |
270 | } | |
5e3cb728 JB |
271 | |
272 | /** | |
273 | * Convert websocket error code to human readable string message | |
274 | * | |
275 | * @param code websocket error code | |
276 | * @returns human readable string message | |
277 | */ | |
278 | public static getWebSocketCloseEventStatusString(code: number): string { | |
279 | if (code >= 0 && code <= 999) { | |
280 | return '(Unused)'; | |
281 | } else if (code >= 1016) { | |
282 | if (code <= 1999) { | |
283 | return '(For WebSocket standard)'; | |
284 | } else if (code <= 2999) { | |
285 | return '(For WebSocket extensions)'; | |
286 | } else if (code <= 3999) { | |
287 | return '(For libraries and frameworks)'; | |
288 | } else if (code <= 4999) { | |
289 | return '(For applications)'; | |
290 | } | |
291 | } | |
292 | if (!Utils.isUndefined(WebSocketCloseEventStatusString[code])) { | |
293 | return WebSocketCloseEventStatusString[code] as string; | |
294 | } | |
295 | return '(Unknown)'; | |
296 | } | |
7dde0b73 | 297 | } |