Commit | Line | Data |
---|---|---|
52ed5cf0 | 1 | import crypto from 'node:crypto'; |
764d2c91 | 2 | import util from 'node:util'; |
8114d10e | 3 | |
088ee3c1 JB |
4 | import clone from 'just-clone'; |
5 | ||
878e026c | 6 | import { Constants } from './Constants'; |
268a74bb | 7 | import { WebSocketCloseEventStatusString } from '../types'; |
5e3cb728 | 8 | |
268a74bb | 9 | export class Utils { |
d5bd1c00 JB |
10 | private constructor() { |
11 | // This is intentional | |
12 | } | |
13 | ||
8b7072dc | 14 | public static logPrefix = (prefixString = ''): string => { |
a1e5fe4e | 15 | return `${new Date().toLocaleString()}${prefixString}`; |
8b7072dc | 16 | }; |
147d0e0f | 17 | |
0f16a662 | 18 | public static generateUUID(): string { |
03eacbe5 JB |
19 | return crypto.randomUUID(); |
20 | } | |
21 | ||
22 | public static validateUUID(uuid: string): boolean { | |
8bd02502 JB |
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( |
24 | uuid | |
25 | ); | |
7dde0b73 JB |
26 | } |
27 | ||
0f16a662 | 28 | public static async sleep(milliSeconds: number): Promise<NodeJS.Timeout> { |
72092cfc | 29 | return new Promise((resolve) => setTimeout(resolve as () => void, milliSeconds)); |
7dde0b73 JB |
30 | } |
31 | ||
d7d1db72 JB |
32 | public static formatDurationMilliSeconds(duration: number): string { |
33 | duration = Utils.convertToInt(duration); | |
34 | const hours = Math.floor(duration / (3600 * 1000)); | |
e7aeea18 JB |
35 | const minutes = Math.floor((duration / 1000 - hours * 3600) / 60); |
36 | const seconds = duration / 1000 - hours * 3600 - minutes * 60; | |
a3868ec4 JB |
37 | let hoursStr = hours.toString(); |
38 | let minutesStr = minutes.toString(); | |
39 | let secondsStr = seconds.toString(); | |
d7d1db72 JB |
40 | |
41 | if (hours < 10) { | |
44eb6026 | 42 | hoursStr = `0${hours.toString()}`; |
d7d1db72 JB |
43 | } |
44 | if (minutes < 10) { | |
44eb6026 | 45 | minutesStr = `0${minutes.toString()}`; |
d7d1db72 JB |
46 | } |
47 | if (seconds < 10) { | |
44eb6026 | 48 | secondsStr = `0${seconds.toString()}`; |
d7d1db72 | 49 | } |
44eb6026 | 50 | return `${hoursStr}:${minutesStr}:${secondsStr.substring(0, 6)}`; |
9ac86a7e JB |
51 | } |
52 | ||
d7d1db72 JB |
53 | public static formatDurationSeconds(duration: number): string { |
54 | return Utils.formatDurationMilliSeconds(duration * 1000); | |
7dde0b73 JB |
55 | } |
56 | ||
b1340ec1 JB |
57 | public static convertToDate( |
58 | value: Date | string | number | null | undefined | |
59 | ): Date | null | undefined { | |
d439da5c JB |
60 | if (Utils.isNullOrUndefined(value)) { |
61 | return value as null | undefined; | |
62 | } | |
63 | if (value instanceof Date) { | |
64 | return value; | |
560bcf5b | 65 | } |
d439da5c | 66 | if (Utils.isString(value) || typeof value === 'number') { |
b1340ec1 | 67 | return new Date(value); |
7dde0b73 | 68 | } |
d439da5c | 69 | return null; |
7dde0b73 JB |
70 | } |
71 | ||
0f16a662 | 72 | public static convertToInt(value: unknown): number { |
72766a82 | 73 | if (!value) { |
7dde0b73 JB |
74 | return 0; |
75 | } | |
69bafbed | 76 | let changedValue: number = value as number; |
72766a82 | 77 | if (Number.isSafeInteger(value)) { |
95926c9b | 78 | return value as number; |
72766a82 | 79 | } |
df645d8f | 80 | if (typeof value === 'number') { |
b1340ec1 | 81 | return Math.trunc(value); |
df645d8f | 82 | } |
3df786f9 JB |
83 | if (Utils.isString(value)) { |
84 | changedValue = parseInt(value as string); | |
85 | } | |
b1340ec1 JB |
86 | if (isNaN(changedValue)) { |
87 | throw new Error(`Cannot convert to integer: ${value.toString()}`); | |
88 | } | |
72766a82 | 89 | return changedValue; |
7dde0b73 JB |
90 | } |
91 | ||
0f16a662 | 92 | public static convertToFloat(value: unknown): number { |
72766a82 | 93 | if (!value) { |
7dde0b73 JB |
94 | return 0; |
95 | } | |
69bafbed | 96 | let changedValue: number = value as number; |
087a502d | 97 | if (Utils.isString(value)) { |
73d09045 | 98 | changedValue = parseFloat(value as string); |
7dde0b73 | 99 | } |
b1340ec1 JB |
100 | if (isNaN(changedValue)) { |
101 | throw new Error(`Cannot convert to float: ${value.toString()}`); | |
102 | } | |
72766a82 | 103 | return changedValue; |
7dde0b73 JB |
104 | } |
105 | ||
0f16a662 | 106 | public static convertToBoolean(value: unknown): boolean { |
a6e68f34 | 107 | let result = false; |
a6e68f34 JB |
108 | if (value) { |
109 | // Check the type | |
110 | if (typeof value === 'boolean') { | |
b1340ec1 | 111 | return value; |
df645d8f JB |
112 | } else if ( |
113 | Utils.isString(value) && | |
114 | ((value as string).toLowerCase() === 'true' || value === '1') | |
115 | ) { | |
116 | result = true; | |
117 | } else if (typeof value === 'number' && value === 1) { | |
118 | result = true; | |
a6e68f34 JB |
119 | } |
120 | } | |
121 | return result; | |
122 | } | |
123 | ||
2f45578b JB |
124 | public static getRandomFloat(max = Number.MAX_VALUE, min = 0): number { |
125 | if (max < min) { | |
126 | throw new RangeError('Invalid interval'); | |
127 | } | |
128 | if (max - min === Infinity) { | |
b322b8b4 JB |
129 | throw new RangeError('Invalid interval'); |
130 | } | |
602d810a | 131 | return (crypto.randomBytes(4).readUInt32LE() / 0xffffffff) * (max - min) + min; |
560bcf5b JB |
132 | } |
133 | ||
59395dc1 | 134 | public static getRandomInteger(max = Constants.MAX_RANDOM_INTEGER, min = 0): number { |
fd00fa2e | 135 | max = Math.floor(max); |
1f86b121 | 136 | if (!Utils.isNullOrUndefined(min) && min !== 0) { |
fd00fa2e | 137 | min = Math.ceil(min); |
59395dc1 | 138 | return Math.floor(crypto.randomInt(min, max + 1)); |
7dde0b73 | 139 | } |
59395dc1 | 140 | return Math.floor(crypto.randomInt(max + 1)); |
560bcf5b JB |
141 | } |
142 | ||
361c98f5 JB |
143 | /** |
144 | * Rounds the given number to the given scale. | |
145 | * The rounding is done using the "round half away from zero" method. | |
146 | * | |
147 | * @param numberValue - The number to round. | |
148 | * @param scale - The scale to round to. | |
149 | * @returns The rounded number. | |
150 | */ | |
0f16a662 | 151 | public static roundTo(numberValue: number, scale: number): number { |
ad3de6c4 | 152 | const roundPower = Math.pow(10, scale); |
316d1564 | 153 | return Math.round(numberValue * roundPower * (1 + Number.EPSILON)) / roundPower; |
6d3a11a0 JB |
154 | } |
155 | ||
b5e5892d | 156 | public static getRandomFloatRounded(max = Number.MAX_VALUE, min = 0, scale = 2): number { |
560bcf5b JB |
157 | if (min) { |
158 | return Utils.roundTo(Utils.getRandomFloat(max, min), scale); | |
159 | } | |
160 | return Utils.roundTo(Utils.getRandomFloat(max), scale); | |
7dde0b73 JB |
161 | } |
162 | ||
e7aeea18 JB |
163 | public static getRandomFloatFluctuatedRounded( |
164 | staticValue: number, | |
165 | fluctuationPercent: number, | |
166 | scale = 2 | |
167 | ): number { | |
8f3233c2 JB |
168 | if (fluctuationPercent < 0 || fluctuationPercent > 100) { |
169 | throw new Error( | |
170 | `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}` | |
171 | ); | |
172 | } | |
9ccca265 JB |
173 | if (fluctuationPercent === 0) { |
174 | return Utils.roundTo(staticValue, scale); | |
175 | } | |
97ef739c | 176 | const fluctuationRatio = fluctuationPercent / 100; |
e7aeea18 JB |
177 | return Utils.getRandomFloatRounded( |
178 | staticValue * (1 + fluctuationRatio), | |
179 | staticValue * (1 - fluctuationRatio), | |
180 | scale | |
181 | ); | |
9ccca265 JB |
182 | } |
183 | ||
91ecff2d | 184 | public static isObject(item: unknown): boolean { |
98fc1389 JB |
185 | return ( |
186 | Utils.isNullOrUndefined(item) === false && | |
187 | typeof item === 'object' && | |
188 | Array.isArray(item) === false | |
189 | ); | |
91ecff2d JB |
190 | } |
191 | ||
088ee3c1 JB |
192 | public static cloneObject<T extends object>(object: T): T { |
193 | return clone<T>(object); | |
2e6f5966 | 194 | } |
facd8ebd | 195 | |
ef4932d8 | 196 | public static hasOwnProp(object: unknown, property: PropertyKey): boolean { |
c5f2c258 | 197 | return Utils.isObject(object) && Object.hasOwn(object as object, property); |
dada83ec JB |
198 | } |
199 | ||
200 | public static isCFEnvironment(): boolean { | |
9bb1159e | 201 | return !Utils.isNullOrUndefined(process.env.VCAP_APPLICATION); |
dada83ec JB |
202 | } |
203 | ||
afb26ef1 | 204 | public static isIterable<T>(obj: T): boolean { |
1895299d | 205 | return !Utils.isNullOrUndefined(obj) ? typeof obj[Symbol.iterator] === 'function' : false; |
67e9cccf JB |
206 | } |
207 | ||
0f16a662 | 208 | public static isString(value: unknown): boolean { |
560bcf5b JB |
209 | return typeof value === 'string'; |
210 | } | |
211 | ||
e8191622 | 212 | public static isEmptyString(value: unknown): boolean { |
5a2a53cf JB |
213 | return ( |
214 | Utils.isNullOrUndefined(value) || | |
215 | (Utils.isString(value) && (value as string).trim().length === 0) | |
216 | ); | |
217 | } | |
218 | ||
219 | public static isNotEmptyString(value: unknown): boolean { | |
220 | return Utils.isString(value) && (value as string).trim().length > 0; | |
e8191622 JB |
221 | } |
222 | ||
0f16a662 | 223 | public static isUndefined(value: unknown): boolean { |
72092cfc | 224 | return value === undefined; |
ead548f2 JB |
225 | } |
226 | ||
0f16a662 | 227 | public static isNullOrUndefined(value: unknown): boolean { |
7558b3a6 | 228 | // eslint-disable-next-line eqeqeq, no-eq-null |
1732e614 | 229 | return value == null; |
facd8ebd | 230 | } |
4a56deef | 231 | |
bd5d98e0 | 232 | public static isEmptyArray(object: unknown): boolean { |
5d0b9ffc | 233 | return Array.isArray(object) && object.length === 0; |
53ac516c JB |
234 | } |
235 | ||
bd5d98e0 | 236 | public static isNotEmptyArray(object: unknown): boolean { |
5d0b9ffc | 237 | return Array.isArray(object) && object.length > 0; |
4a56deef | 238 | } |
7abfea5f | 239 | |
94ec7e96 | 240 | public static isEmptyObject(obj: object): boolean { |
5e5ba121 | 241 | if (obj?.constructor !== Object) { |
d20581ee JB |
242 | return false; |
243 | } | |
87f82a94 JB |
244 | // Iterates over the keys of an object, if |
245 | // any exist, return false. | |
246 | for (const _ in obj) { | |
247 | return false; | |
248 | } | |
249 | return true; | |
7abfea5f | 250 | } |
7ec46a9a | 251 | |
e7aeea18 JB |
252 | public static insertAt = (str: string, subStr: string, pos: number): string => |
253 | `${str.slice(0, pos)}${subStr}${str.slice(pos)}`; | |
032d6efc JB |
254 | |
255 | /** | |
361c98f5 JB |
256 | * Computes the retry delay in milliseconds using an exponential backoff algorithm. |
257 | * | |
0e4fa348 | 258 | * @param retryNumber - the number of retries that have already been attempted |
81797102 | 259 | * @returns delay in milliseconds |
032d6efc | 260 | */ |
517ffa58 | 261 | public static exponentialDelay(retryNumber = 0, maxDelayRatio = 0.2): number { |
032d6efc | 262 | const delay = Math.pow(2, retryNumber) * 100; |
517ffa58 | 263 | const randomSum = delay * maxDelayRatio * Utils.secureRandom(); // 0-20% of the delay |
032d6efc JB |
264 | return delay + randomSum; |
265 | } | |
32a1eb7a | 266 | |
764d2c91 JB |
267 | public static isPromisePending(promise: Promise<unknown>): boolean { |
268 | return util.inspect(promise).includes('pending'); | |
269 | } | |
270 | ||
6d9abcc2 | 271 | public static async promiseWithTimeout<T>( |
e7aeea18 JB |
272 | promise: Promise<T>, |
273 | timeoutMs: number, | |
274 | timeoutError: Error, | |
275 | timeoutCallback: () => void = () => { | |
276 | /* This is intentional */ | |
277 | } | |
6d9abcc2 JB |
278 | ): Promise<T> { |
279 | // Create a timeout promise that rejects in timeout milliseconds | |
280 | const timeoutPromise = new Promise<never>((_, reject) => { | |
281 | setTimeout(() => { | |
764d2c91 JB |
282 | if (Utils.isPromisePending(promise)) { |
283 | timeoutCallback(); | |
59395dc1 | 284 | // FIXME: The original promise shall be canceled |
764d2c91 | 285 | } |
6d9abcc2 JB |
286 | reject(timeoutError); |
287 | }, timeoutMs); | |
288 | }); | |
289 | ||
290 | // Returns a race between timeout promise and the passed promise | |
291 | return Promise.race<T>([promise, timeoutPromise]); | |
292 | } | |
293 | ||
c37528f1 | 294 | /** |
361c98f5 | 295 | * Generates a cryptographically secure random number in the [0,1[ range |
c37528f1 JB |
296 | * |
297 | * @returns | |
298 | */ | |
0f16a662 | 299 | public static secureRandom(): number { |
c37528f1 JB |
300 | return crypto.randomBytes(4).readUInt32LE() / 0x100000000; |
301 | } | |
fe791818 JB |
302 | |
303 | public static JSONStringifyWithMapSupport( | |
edd13439 | 304 | obj: Record<string, unknown> | Record<string, unknown>[] | Map<unknown, unknown>, |
fe791818 JB |
305 | space?: number |
306 | ): string { | |
307 | return JSON.stringify( | |
308 | obj, | |
309 | (key, value: Record<string, unknown>) => { | |
310 | if (value instanceof Map) { | |
311 | return { | |
312 | dataType: 'Map', | |
313 | value: [...value], | |
314 | }; | |
315 | } | |
316 | return value; | |
317 | }, | |
318 | space | |
319 | ); | |
320 | } | |
5e3cb728 JB |
321 | |
322 | /** | |
361c98f5 | 323 | * Converts websocket error code to human readable string message |
5e3cb728 | 324 | * |
0e4fa348 | 325 | * @param code - websocket error code |
5e3cb728 JB |
326 | * @returns human readable string message |
327 | */ | |
328 | public static getWebSocketCloseEventStatusString(code: number): string { | |
329 | if (code >= 0 && code <= 999) { | |
330 | return '(Unused)'; | |
331 | } else if (code >= 1016) { | |
332 | if (code <= 1999) { | |
333 | return '(For WebSocket standard)'; | |
334 | } else if (code <= 2999) { | |
335 | return '(For WebSocket extensions)'; | |
336 | } else if (code <= 3999) { | |
337 | return '(For libraries and frameworks)'; | |
338 | } else if (code <= 4999) { | |
339 | return '(For applications)'; | |
340 | } | |
341 | } | |
342 | if (!Utils.isUndefined(WebSocketCloseEventStatusString[code])) { | |
343 | return WebSocketCloseEventStatusString[code] as string; | |
344 | } | |
345 | return '(Unknown)'; | |
346 | } | |
7dde0b73 | 347 | } |