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