Commit | Line | Data |
---|---|---|
7cd0a621 | 1 | import { getRandomValues, randomBytes, randomInt, randomUUID } from 'node:crypto'; |
29dff95e | 2 | import { env, nextTick } from 'node:process'; |
8114d10e | 3 | |
f0c6601c JB |
4 | import { |
5 | formatDuration, | |
be4c6702 JB |
6 | hoursToMinutes, |
7 | hoursToSeconds, | |
b5c19509 | 8 | isDate, |
f0c6601c JB |
9 | millisecondsToHours, |
10 | millisecondsToMinutes, | |
11 | millisecondsToSeconds, | |
be4c6702 | 12 | minutesToSeconds, |
f0c6601c JB |
13 | secondsToMilliseconds, |
14 | } from 'date-fns'; | |
088ee3c1 | 15 | |
a6ef1ece JB |
16 | import { Constants } from './Constants.js'; |
17 | import { type TimestampedData, WebSocketCloseEventStatusString } from '../types/index.js'; | |
5e3cb728 | 18 | |
9bf0ef23 JB |
19 | export const logPrefix = (prefixString = ''): string => { |
20 | return `${new Date().toLocaleString()}${prefixString}`; | |
21 | }; | |
d5bd1c00 | 22 | |
9bf0ef23 JB |
23 | export const generateUUID = (): string => { |
24 | return randomUUID(); | |
25 | }; | |
147d0e0f | 26 | |
9bf0ef23 JB |
27 | export const validateUUID = (uuid: string): boolean => { |
28 | 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( | |
5edd8ba0 | 29 | uuid, |
9bf0ef23 JB |
30 | ); |
31 | }; | |
03eacbe5 | 32 | |
9bf0ef23 | 33 | export const sleep = async (milliSeconds: number): Promise<NodeJS.Timeout> => { |
474d4ffc | 34 | return new Promise<NodeJS.Timeout>((resolve) => setTimeout(resolve as () => void, milliSeconds)); |
9bf0ef23 | 35 | }; |
7dde0b73 | 36 | |
9bf0ef23 JB |
37 | export const formatDurationMilliSeconds = (duration: number): string => { |
38 | duration = convertToInt(duration); | |
17b07e47 JB |
39 | if (duration < 0) { |
40 | throw new RangeError('Duration cannot be negative'); | |
41 | } | |
a675e34b | 42 | const days = Math.floor(duration / (24 * 3600 * 1000)); |
f0c6601c | 43 | const hours = Math.floor(millisecondsToHours(duration) - days * 24); |
be4c6702 JB |
44 | const minutes = Math.floor( |
45 | millisecondsToMinutes(duration) - days * 24 * 60 - hoursToMinutes(hours), | |
46 | ); | |
f0c6601c | 47 | const seconds = Math.floor( |
be4c6702 JB |
48 | millisecondsToSeconds(duration) - |
49 | days * 24 * 3600 - | |
50 | hoursToSeconds(hours) - | |
51 | minutesToSeconds(minutes), | |
f0c6601c | 52 | ); |
d7ceb0f0 JB |
53 | if (days === 0 && hours === 0 && minutes === 0 && seconds === 0) { |
54 | return formatDuration({ seconds }, { zero: true }); | |
55 | } | |
56 | return formatDuration({ | |
57 | days, | |
58 | hours, | |
59 | minutes, | |
60 | seconds, | |
61 | }); | |
9bf0ef23 | 62 | }; |
7dde0b73 | 63 | |
9bf0ef23 | 64 | export const formatDurationSeconds = (duration: number): string => { |
a675e34b | 65 | return formatDurationMilliSeconds(secondsToMilliseconds(duration)); |
9bf0ef23 | 66 | }; |
7dde0b73 | 67 | |
0bd926c1 JB |
68 | // More efficient time validation function than the one provided by date-fns |
69 | export const isValidTime = (date: unknown): boolean => { | |
b5c19509 JB |
70 | if (typeof date === 'number') { |
71 | return !isNaN(date); | |
72 | } else if (isDate(date)) { | |
f1e3871b | 73 | return !isNaN(date.getTime()); |
b5c19509 JB |
74 | } |
75 | return false; | |
76 | }; | |
77 | ||
a78c196b JB |
78 | export const convertToDate = ( |
79 | value: Date | string | number | null | undefined, | |
80 | ): Date | null | undefined => { | |
9bf0ef23 | 81 | if (isNullOrUndefined(value)) { |
a0f6a472 | 82 | return value as null | undefined; |
7dde0b73 | 83 | } |
0bd926c1 | 84 | if (isDate(value)) { |
f1e3871b | 85 | return value; |
a6e68f34 | 86 | } |
9bf0ef23 | 87 | if (isString(value) || typeof value === 'number') { |
f1e3871b | 88 | const valueToDate = new Date(value!); |
85cce27f | 89 | if (isNaN(valueToDate.getTime())) { |
f1e3871b | 90 | throw new Error(`Cannot convert to date: '${value!}'`); |
43ff25b8 | 91 | } |
85cce27f | 92 | return valueToDate; |
560bcf5b | 93 | } |
9bf0ef23 | 94 | }; |
560bcf5b | 95 | |
9bf0ef23 JB |
96 | export const convertToInt = (value: unknown): number => { |
97 | if (!value) { | |
98 | return 0; | |
560bcf5b | 99 | } |
9bf0ef23 JB |
100 | let changedValue: number = value as number; |
101 | if (Number.isSafeInteger(value)) { | |
102 | return value as number; | |
6d3a11a0 | 103 | } |
9bf0ef23 JB |
104 | if (typeof value === 'number') { |
105 | return Math.trunc(value); | |
7dde0b73 | 106 | } |
9bf0ef23 JB |
107 | if (isString(value)) { |
108 | changedValue = parseInt(value as string); | |
9ccca265 | 109 | } |
9bf0ef23 | 110 | if (isNaN(changedValue)) { |
85cce27f | 111 | throw new Error(`Cannot convert to integer: '${String(value)}'`); |
dada83ec | 112 | } |
9bf0ef23 JB |
113 | return changedValue; |
114 | }; | |
dada83ec | 115 | |
9bf0ef23 JB |
116 | export const convertToFloat = (value: unknown): number => { |
117 | if (!value) { | |
118 | return 0; | |
dada83ec | 119 | } |
9bf0ef23 JB |
120 | let changedValue: number = value as number; |
121 | if (isString(value)) { | |
122 | changedValue = parseFloat(value as string); | |
560bcf5b | 123 | } |
9bf0ef23 | 124 | if (isNaN(changedValue)) { |
85cce27f | 125 | throw new Error(`Cannot convert to float: '${String(value)}'`); |
5a2a53cf | 126 | } |
9bf0ef23 JB |
127 | return changedValue; |
128 | }; | |
5a2a53cf | 129 | |
9bf0ef23 JB |
130 | export const convertToBoolean = (value: unknown): boolean => { |
131 | let result = false; | |
a78c196b | 132 | if (value != null) { |
9bf0ef23 JB |
133 | // Check the type |
134 | if (typeof value === 'boolean') { | |
135 | return value; | |
136 | } else if (isString(value) && ((value as string).toLowerCase() === 'true' || value === '1')) { | |
137 | result = true; | |
138 | } else if (typeof value === 'number' && value === 1) { | |
139 | result = true; | |
e7aeea18 | 140 | } |
c37528f1 | 141 | } |
9bf0ef23 JB |
142 | return result; |
143 | }; | |
144 | ||
145 | export const getRandomFloat = (max = Number.MAX_VALUE, min = 0): number => { | |
146 | if (max < min) { | |
147 | throw new RangeError('Invalid interval'); | |
148 | } | |
149 | if (max - min === Infinity) { | |
150 | throw new RangeError('Invalid interval'); | |
151 | } | |
152 | return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max - min) + min; | |
153 | }; | |
154 | ||
155 | export const getRandomInteger = (max = Constants.MAX_RANDOM_INTEGER, min = 0): number => { | |
156 | max = Math.floor(max); | |
157 | if (!isNullOrUndefined(min) && min !== 0) { | |
158 | min = Math.ceil(min); | |
159 | return Math.floor(randomInt(min, max + 1)); | |
160 | } | |
161 | return Math.floor(randomInt(max + 1)); | |
162 | }; | |
163 | ||
164 | /** | |
165 | * Rounds the given number to the given scale. | |
166 | * The rounding is done using the "round half away from zero" method. | |
167 | * | |
168 | * @param numberValue - The number to round. | |
169 | * @param scale - The scale to round to. | |
170 | * @returns The rounded number. | |
171 | */ | |
172 | export const roundTo = (numberValue: number, scale: number): number => { | |
173 | const roundPower = Math.pow(10, scale); | |
174 | return Math.round(numberValue * roundPower * (1 + Number.EPSILON)) / roundPower; | |
175 | }; | |
176 | ||
177 | export const getRandomFloatRounded = (max = Number.MAX_VALUE, min = 0, scale = 2): number => { | |
178 | if (min) { | |
179 | return roundTo(getRandomFloat(max, min), scale); | |
180 | } | |
181 | return roundTo(getRandomFloat(max), scale); | |
182 | }; | |
183 | ||
184 | export const getRandomFloatFluctuatedRounded = ( | |
185 | staticValue: number, | |
186 | fluctuationPercent: number, | |
5edd8ba0 | 187 | scale = 2, |
9bf0ef23 JB |
188 | ): number => { |
189 | if (fluctuationPercent < 0 || fluctuationPercent > 100) { | |
190 | throw new RangeError( | |
5edd8ba0 | 191 | `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}`, |
fe791818 JB |
192 | ); |
193 | } | |
9bf0ef23 JB |
194 | if (fluctuationPercent === 0) { |
195 | return roundTo(staticValue, scale); | |
196 | } | |
197 | const fluctuationRatio = fluctuationPercent / 100; | |
198 | return getRandomFloatRounded( | |
199 | staticValue * (1 + fluctuationRatio), | |
200 | staticValue * (1 - fluctuationRatio), | |
5edd8ba0 | 201 | scale, |
9bf0ef23 JB |
202 | ); |
203 | }; | |
204 | ||
da55bd34 JB |
205 | export const extractTimeSeriesValues = (timeSeries: Array<TimestampedData>): number[] => { |
206 | return timeSeries.map((timeSeriesItem) => timeSeriesItem.value); | |
207 | }; | |
208 | ||
9bf0ef23 JB |
209 | export const isObject = (item: unknown): boolean => { |
210 | return ( | |
211 | isNullOrUndefined(item) === false && typeof item === 'object' && Array.isArray(item) === false | |
212 | ); | |
213 | }; | |
214 | ||
32f5e42d JB |
215 | type CloneableData = |
216 | | number | |
217 | | string | |
218 | | boolean | |
219 | | null | |
220 | | undefined | |
221 | | Date | |
222 | | CloneableData[] | |
223 | | { [key: string]: CloneableData }; | |
224 | ||
661ac64b JB |
225 | type FormatKey = (key: string) => string; |
226 | ||
015f3404 | 227 | const deepClone = <I extends CloneableData, O extends CloneableData = I>( |
661ac64b JB |
228 | value: I, |
229 | formatKey?: FormatKey, | |
230 | refs: Map<I, O> = new Map<I, O>(), | |
015f3404 | 231 | ): O => { |
661ac64b JB |
232 | const ref = refs.get(value); |
233 | if (ref !== undefined) { | |
234 | return ref; | |
235 | } | |
236 | if (Array.isArray(value)) { | |
237 | const clone: CloneableData[] = []; | |
238 | refs.set(value, clone as O); | |
239 | for (let i = 0; i < value.length; i++) { | |
240 | clone[i] = deepClone(value[i], formatKey, refs); | |
241 | } | |
242 | return clone as O; | |
243 | } | |
244 | if (value instanceof Date) { | |
245 | return new Date(value.valueOf()) as O; | |
246 | } | |
247 | if (typeof value !== 'object' || value === null) { | |
248 | return value as unknown as O; | |
249 | } | |
250 | const clone: Record<string, CloneableData> = {}; | |
251 | refs.set(value, clone as O); | |
252 | for (const key of Object.keys(value)) { | |
253 | clone[typeof formatKey === 'function' ? formatKey(key) : key] = deepClone( | |
254 | value[key], | |
255 | formatKey, | |
256 | refs, | |
257 | ); | |
258 | } | |
259 | return clone as O; | |
015f3404 | 260 | }; |
661ac64b | 261 | |
32f5e42d | 262 | export const cloneObject = <T>(object: T): T => { |
32f5e42d | 263 | return deepClone(object as CloneableData) as T; |
9bf0ef23 JB |
264 | }; |
265 | ||
266 | export const hasOwnProp = (object: unknown, property: PropertyKey): boolean => { | |
267 | return isObject(object) && Object.hasOwn(object as object, property); | |
268 | }; | |
269 | ||
270 | export const isCFEnvironment = (): boolean => { | |
10687422 | 271 | return !isNullOrUndefined(env.VCAP_APPLICATION); |
9bf0ef23 JB |
272 | }; |
273 | ||
274 | export const isIterable = <T>(obj: T): boolean => { | |
a37fc6dc | 275 | return !isNullOrUndefined(obj) ? typeof obj[Symbol.iterator as keyof T] === 'function' : false; |
9bf0ef23 JB |
276 | }; |
277 | ||
278 | const isString = (value: unknown): boolean => { | |
279 | return typeof value === 'string'; | |
280 | }; | |
281 | ||
282 | export const isEmptyString = (value: unknown): boolean => { | |
283 | return isNullOrUndefined(value) || (isString(value) && (value as string).trim().length === 0); | |
284 | }; | |
285 | ||
286 | export const isNotEmptyString = (value: unknown): boolean => { | |
287 | return isString(value) && (value as string).trim().length > 0; | |
288 | }; | |
289 | ||
290 | export const isUndefined = (value: unknown): boolean => { | |
291 | return value === undefined; | |
292 | }; | |
293 | ||
294 | export const isNullOrUndefined = (value: unknown): boolean => { | |
9bf0ef23 JB |
295 | return value == null; |
296 | }; | |
297 | ||
298 | export const isEmptyArray = (object: unknown): boolean => { | |
299 | return Array.isArray(object) && object.length === 0; | |
300 | }; | |
301 | ||
302 | export const isNotEmptyArray = (object: unknown): boolean => { | |
303 | return Array.isArray(object) && object.length > 0; | |
304 | }; | |
305 | ||
306 | export const isEmptyObject = (obj: object): boolean => { | |
307 | if (obj?.constructor !== Object) { | |
308 | return false; | |
309 | } | |
310 | // Iterates over the keys of an object, if | |
311 | // any exist, return false. | |
312 | for (const _ in obj) { | |
313 | return false; | |
314 | } | |
315 | return true; | |
316 | }; | |
317 | ||
318 | export const insertAt = (str: string, subStr: string, pos: number): string => | |
319 | `${str.slice(0, pos)}${subStr}${str.slice(pos)}`; | |
320 | ||
321 | /** | |
322 | * Computes the retry delay in milliseconds using an exponential backoff algorithm. | |
323 | * | |
324 | * @param retryNumber - the number of retries that have already been attempted | |
45abd3c6 | 325 | * @param delayFactor - the base delay factor in milliseconds |
9bf0ef23 JB |
326 | * @returns delay in milliseconds |
327 | */ | |
45abd3c6 JB |
328 | export const exponentialDelay = (retryNumber = 0, delayFactor = 100): number => { |
329 | const delay = Math.pow(2, retryNumber) * delayFactor; | |
330 | const randomSum = delay * 0.2 * secureRandom(); // 0-20% of the delay | |
9bf0ef23 JB |
331 | return delay + randomSum; |
332 | }; | |
333 | ||
9bf0ef23 JB |
334 | /** |
335 | * Generates a cryptographically secure random number in the [0,1[ range | |
336 | * | |
ab93b184 | 337 | * @returns A number in the [0,1[ range |
9bf0ef23 JB |
338 | */ |
339 | export const secureRandom = (): number => { | |
7cd0a621 | 340 | return getRandomValues(new Uint32Array(1))[0] / 0x100000000; |
9bf0ef23 JB |
341 | }; |
342 | ||
343 | export const JSONStringifyWithMapSupport = ( | |
344 | obj: Record<string, unknown> | Record<string, unknown>[] | Map<unknown, unknown>, | |
5edd8ba0 | 345 | space?: number, |
9bf0ef23 JB |
346 | ): string => { |
347 | return JSON.stringify( | |
348 | obj, | |
58ddf341 | 349 | (_, value: Record<string, unknown>) => { |
9bf0ef23 JB |
350 | if (value instanceof Map) { |
351 | return { | |
352 | dataType: 'Map', | |
353 | value: [...value], | |
354 | }; | |
355 | } | |
356 | return value; | |
357 | }, | |
5edd8ba0 | 358 | space, |
9bf0ef23 JB |
359 | ); |
360 | }; | |
361 | ||
362 | /** | |
363 | * Converts websocket error code to human readable string message | |
364 | * | |
365 | * @param code - websocket error code | |
366 | * @returns human readable string message | |
367 | */ | |
368 | export const getWebSocketCloseEventStatusString = (code: number): string => { | |
369 | if (code >= 0 && code <= 999) { | |
370 | return '(Unused)'; | |
371 | } else if (code >= 1016) { | |
372 | if (code <= 1999) { | |
373 | return '(For WebSocket standard)'; | |
374 | } else if (code <= 2999) { | |
375 | return '(For WebSocket extensions)'; | |
376 | } else if (code <= 3999) { | |
377 | return '(For libraries and frameworks)'; | |
378 | } else if (code <= 4999) { | |
379 | return '(For applications)'; | |
5e3cb728 | 380 | } |
5e3cb728 | 381 | } |
a37fc6dc JB |
382 | if ( |
383 | !isUndefined( | |
384 | WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString], | |
385 | ) | |
386 | ) { | |
387 | return WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString]; | |
9bf0ef23 JB |
388 | } |
389 | return '(Unknown)'; | |
390 | }; | |
80c58041 | 391 | |
991fb26b JB |
392 | export const isArraySorted = <T>(array: T[], compareFn: (a: T, b: T) => number): boolean => { |
393 | for (let index = 0; index < array.length - 1; ++index) { | |
394 | if (compareFn(array[index], array[index + 1]) > 0) { | |
80c58041 JB |
395 | return false; |
396 | } | |
397 | } | |
398 | return true; | |
399 | }; | |
5f742aac JB |
400 | |
401 | // eslint-disable-next-line @typescript-eslint/no-explicit-any | |
402 | export const once = <T, A extends any[], R>( | |
403 | fn: (...args: A) => R, | |
404 | context: T, | |
405 | ): ((...args: A) => R) => { | |
406 | let result: R; | |
407 | return (...args: A) => { | |
408 | if (fn) { | |
409 | result = fn.apply<T, A, R>(context, args); | |
410 | (fn as unknown as undefined) = (context as unknown as undefined) = undefined; | |
411 | } | |
412 | return result; | |
413 | }; | |
414 | }; | |
5adf6ca4 JB |
415 | |
416 | export const min = (...args: number[]): number => | |
417 | args.reduce((minimum, num) => (minimum < num ? minimum : num), Infinity); | |
418 | ||
419 | export const max = (...args: number[]): number => | |
420 | args.reduce((maximum, num) => (maximum > num ? maximum : num), -Infinity); | |
29dff95e JB |
421 | |
422 | export const throwErrorInNextTick = (error: Error): void => { | |
423 | nextTick(() => { | |
424 | throw error; | |
425 | }); | |
426 | }; |