1 import { randomBytes
, randomInt
, randomUUID
} from
'node:crypto';
2 import { inspect
} from
'node:util';
10 millisecondsToMinutes
,
11 millisecondsToSeconds
,
13 secondsToMilliseconds
,
16 import { Constants
} from
'./Constants';
17 import { type TimestampedData
, WebSocketCloseEventStatusString
} from
'../types';
19 export const logPrefix
= (prefixString
= ''): string => {
20 return `${new Date().toLocaleString()}${prefixString}`;
23 export const generateUUID
= (): string => {
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(
33 export const sleep
= async (milliSeconds
: number): Promise
<NodeJS
.Timeout
> => {
34 return new Promise
<NodeJS
.Timeout
>((resolve
) => setTimeout(resolve
as () => void, milliSeconds
));
37 export const formatDurationMilliSeconds
= (duration
: number): string => {
38 duration
= convertToInt(duration
);
39 const days
= Math.floor(duration
/ (24 * 3600 * 1000));
40 const hours
= Math.floor(millisecondsToHours(duration
) - days
* 24);
41 const minutes
= Math.floor(
42 millisecondsToMinutes(duration
) - days
* 24 * 60 - hoursToMinutes(hours
),
44 const seconds
= Math.floor(
45 millisecondsToSeconds(duration
) -
47 hoursToSeconds(hours
) -
48 minutesToSeconds(minutes
),
50 return formatDuration({
58 export const formatDurationSeconds
= (duration
: number): string => {
59 return formatDurationMilliSeconds(secondsToMilliseconds(duration
));
62 // More efficient time validation function than the one provided by date-fns
63 export const isValidTime
= (date
: unknown
): boolean => {
64 if (typeof date
=== 'number') {
66 } else if (isDate(date
)) {
67 return !isNaN((date
as Date).getTime());
72 export const convertToDate
= (value
: Date | string | number | undefined): Date | undefined => {
73 if (isNullOrUndefined(value
)) {
74 return value
as undefined;
79 if (isString(value
) || typeof value
=== 'number') {
80 const valueToDate
= new Date(value
as string | number);
81 if (isNaN(valueToDate
.getTime())) {
82 throw new Error(`Cannot convert to date: '${value as string | number}'`);
88 export const convertToInt
= (value
: unknown
): number => {
92 let changedValue
: number = value
as number;
93 if (Number.isSafeInteger(value
)) {
94 return value
as number;
96 if (typeof value
=== 'number') {
97 return Math.trunc(value
);
99 if (isString(value
)) {
100 changedValue
= parseInt(value
as string);
102 if (isNaN(changedValue
)) {
103 throw new Error(`Cannot convert to integer: '${String(value)}'`);
108 export const convertToFloat
= (value
: unknown
): number => {
112 let changedValue
: number = value
as number;
113 if (isString(value
)) {
114 changedValue
= parseFloat(value
as string);
116 if (isNaN(changedValue
)) {
117 throw new Error(`Cannot convert to float: '${String(value)}'`);
122 export const convertToBoolean
= (value
: unknown
): boolean => {
126 if (typeof value
=== 'boolean') {
128 } else if (isString(value
) && ((value
as string).toLowerCase() === 'true' || value
=== '1')) {
130 } else if (typeof value
=== 'number' && value
=== 1) {
137 export const getRandomFloat
= (max
= Number.MAX_VALUE
, min
= 0): number => {
139 throw new RangeError('Invalid interval');
141 if (max
- min
=== Infinity) {
142 throw new RangeError('Invalid interval');
144 return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max
- min
) + min
;
147 export const getRandomInteger
= (max
= Constants
.MAX_RANDOM_INTEGER
, min
= 0): number => {
148 max
= Math.floor(max
);
149 if (!isNullOrUndefined(min
) && min
!== 0) {
150 min
= Math.ceil(min
);
151 return Math.floor(randomInt(min
, max
+ 1));
153 return Math.floor(randomInt(max
+ 1));
157 * Rounds the given number to the given scale.
158 * The rounding is done using the "round half away from zero" method.
160 * @param numberValue - The number to round.
161 * @param scale - The scale to round to.
162 * @returns The rounded number.
164 export const roundTo
= (numberValue
: number, scale
: number): number => {
165 const roundPower
= Math.pow(10, scale
);
166 return Math.round(numberValue
* roundPower
* (1 + Number.EPSILON
)) / roundPower
;
169 export const getRandomFloatRounded
= (max
= Number.MAX_VALUE
, min
= 0, scale
= 2): number => {
171 return roundTo(getRandomFloat(max
, min
), scale
);
173 return roundTo(getRandomFloat(max
), scale
);
176 export const getRandomFloatFluctuatedRounded
= (
178 fluctuationPercent
: number,
181 if (fluctuationPercent
< 0 || fluctuationPercent
> 100) {
182 throw new RangeError(
183 `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}`,
186 if (fluctuationPercent
=== 0) {
187 return roundTo(staticValue
, scale
);
189 const fluctuationRatio
= fluctuationPercent
/ 100;
190 return getRandomFloatRounded(
191 staticValue
* (1 + fluctuationRatio
),
192 staticValue
* (1 - fluctuationRatio
),
197 export const extractTimeSeriesValues
= (timeSeries
: Array<TimestampedData
>): number[] => {
198 return timeSeries
.map((timeSeriesItem
) => timeSeriesItem
.value
);
201 export const isObject
= (item
: unknown
): boolean => {
203 isNullOrUndefined(item
) === false && typeof item
=== 'object' && Array.isArray(item
) === false
215 | { [key
: string]: CloneableData
};
217 type FormatKey
= (key
: string) => string;
219 const deepClone
= <I
extends CloneableData
, O
extends CloneableData
= I
>(
221 formatKey
?: FormatKey
,
222 refs
: Map
<I
, O
> = new Map
<I
, O
>(),
224 const ref
= refs
.get(value
);
225 if (ref
!== undefined) {
228 if (Array.isArray(value
)) {
229 const clone
: CloneableData
[] = [];
230 refs
.set(value
, clone
as O
);
231 for (let i
= 0; i
< value
.length
; i
++) {
232 clone
[i
] = deepClone(value
[i
], formatKey
, refs
);
236 if (value
instanceof Date) {
237 return new Date(value
.valueOf()) as O
;
239 if (typeof value
!== 'object' || value
=== null) {
240 return value
as unknown
as O
;
242 const clone
: Record
<string, CloneableData
> = {};
243 refs
.set(value
, clone
as O
);
244 for (const key
of Object.keys(value
)) {
245 clone
[typeof formatKey
=== 'function' ? formatKey(key
) : key
] = deepClone(
254 export const cloneObject
= <T
>(object
: T
): T
=> {
255 return deepClone(object
as CloneableData
) as T
;
258 export const hasOwnProp
= (object
: unknown
, property
: PropertyKey
): boolean => {
259 return isObject(object
) && Object.hasOwn(object
as object
, property
);
262 export const isCFEnvironment
= (): boolean => {
263 return !isNullOrUndefined(process
.env
.VCAP_APPLICATION
);
266 export const isIterable
= <T
>(obj
: T
): boolean => {
267 return !isNullOrUndefined(obj
) ? typeof obj
[Symbol
.iterator
as keyof T
] === 'function' : false;
270 const isString
= (value
: unknown
): boolean => {
271 return typeof value
=== 'string';
274 export const isEmptyString
= (value
: unknown
): boolean => {
275 return isNullOrUndefined(value
) || (isString(value
) && (value
as string).trim().length
=== 0);
278 export const isNotEmptyString
= (value
: unknown
): boolean => {
279 return isString(value
) && (value
as string).trim().length
> 0;
282 export const isUndefined
= (value
: unknown
): boolean => {
283 return value
=== undefined;
286 export const isNullOrUndefined
= (value
: unknown
): boolean => {
287 // eslint-disable-next-line eqeqeq, no-eq-null
288 return value
== null;
291 export const isEmptyArray
= (object
: unknown
): boolean => {
292 return Array.isArray(object
) && object
.length
=== 0;
295 export const isNotEmptyArray
= (object
: unknown
): boolean => {
296 return Array.isArray(object
) && object
.length
> 0;
299 export const isEmptyObject
= (obj
: object
): boolean => {
300 if (obj
?.constructor
!== Object) {
303 // Iterates over the keys of an object, if
304 // any exist, return false.
305 for (const _
in obj
) {
311 export const insertAt
= (str
: string, subStr
: string, pos
: number): string =>
312 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
315 * Computes the retry delay in milliseconds using an exponential backoff algorithm.
317 * @param retryNumber - the number of retries that have already been attempted
318 * @param delayFactor - the base delay factor in milliseconds
319 * @returns delay in milliseconds
321 export const exponentialDelay
= (retryNumber
= 0, delayFactor
= 100): number => {
322 const delay
= Math.pow(2, retryNumber
) * delayFactor
;
323 const randomSum
= delay
* 0.2 * secureRandom(); // 0-20% of the delay
324 return delay
+ randomSum
;
327 const isPromisePending
= (promise
: Promise
<unknown
>): boolean => {
328 return inspect(promise
).includes('pending');
331 export const promiseWithTimeout
= async <T
>(
335 timeoutCallback
: () => void = () => {
336 /* This is intentional */
339 // Creates a timeout promise that rejects in timeout milliseconds
340 const timeoutPromise
= new Promise
<never>((_
, reject
) => {
342 if (isPromisePending(promise
)) {
344 // FIXME: The original promise shall be canceled
346 reject(timeoutError
);
350 // Returns a race between timeout promise and the passed promise
351 return Promise
.race
<T
>([promise
, timeoutPromise
]);
355 * Generates a cryptographically secure random number in the [0,1[ range
359 export const secureRandom
= (): number => {
360 return randomBytes(4).readUInt32LE() / 0x100000000;
363 export const JSONStringifyWithMapSupport
= (
364 obj
: Record
<string, unknown
> | Record
<string, unknown
>[] | Map
<unknown
, unknown
>,
367 return JSON
.stringify(
369 (_
, value
: Record
<string, unknown
>) => {
370 if (value
instanceof Map
) {
383 * Converts websocket error code to human readable string message
385 * @param code - websocket error code
386 * @returns human readable string message
388 export const getWebSocketCloseEventStatusString
= (code
: number): string => {
389 if (code
>= 0 && code
<= 999) {
391 } else if (code
>= 1016) {
393 return '(For WebSocket standard)';
394 } else if (code
<= 2999) {
395 return '(For WebSocket extensions)';
396 } else if (code
<= 3999) {
397 return '(For libraries and frameworks)';
398 } else if (code
<= 4999) {
399 return '(For applications)';
404 WebSocketCloseEventStatusString
[code
as keyof
typeof WebSocketCloseEventStatusString
],
407 return WebSocketCloseEventStatusString
[code
as keyof
typeof WebSocketCloseEventStatusString
];
412 export const isArraySorted
= <T
>(array
: T
[], compareFn
: (a
: T
, b
: T
) => number): boolean => {
413 for (let index
= 0; index
< array
.length
- 1; ++index
) {
414 if (compareFn(array
[index
], array
[index
+ 1]) > 0) {
421 // eslint-disable-next-line @typescript-eslint/no-explicit-any
422 export const once
= <T
, A
extends any[], R
>(
423 fn
: (...args
: A
) => R
,
425 ): ((...args
: A
) => R
) => {
427 return (...args
: A
) => {
429 result
= fn
.apply
<T
, A
, R
>(context
, args
);
430 (fn
as unknown
as undefined) = (context
as unknown
as undefined) = undefined;
436 export const min
= (...args
: number[]): number =>
437 args
.reduce((minimum
, num
) => (minimum
< num
? minimum
: num
), Infinity);
439 export const max
= (...args
: number[]): number =>
440 args
.reduce((maximum
, num
) => (maximum
> num
? maximum
: num
), -Infinity);