1 import { randomBytes
, randomInt
, randomUUID
, webcrypto
} from
'node:crypto';
2 import { env
, nextTick
} from
'node:process';
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
);
40 throw new RangeError('Duration cannot be negative');
42 const days
= Math.floor(duration
/ (24 * 3600 * 1000));
43 const hours
= Math.floor(millisecondsToHours(duration
) - days
* 24);
44 const minutes
= Math.floor(
45 millisecondsToMinutes(duration
) - days
* 24 * 60 - hoursToMinutes(hours
),
47 const seconds
= Math.floor(
48 millisecondsToSeconds(duration
) -
50 hoursToSeconds(hours
) -
51 minutesToSeconds(minutes
),
53 if (days
=== 0 && hours
=== 0 && minutes
=== 0 && seconds
=== 0) {
54 return formatDuration({ seconds
}, { zero
: true });
56 return formatDuration({
64 export const formatDurationSeconds
= (duration
: number): string => {
65 return formatDurationMilliSeconds(secondsToMilliseconds(duration
));
68 // More efficient time validation function than the one provided by date-fns
69 export const isValidTime
= (date
: unknown
): boolean => {
70 if (typeof date
=== 'number') {
72 } else if (isDate(date
)) {
73 return !isNaN((date
as Date).getTime());
78 export const convertToDate
= (value
: Date | string | number | undefined): Date | undefined => {
79 if (isNullOrUndefined(value
)) {
80 return value
as undefined;
85 if (isString(value
) || typeof value
=== 'number') {
86 const valueToDate
= new Date(value
as string | number);
87 if (isNaN(valueToDate
.getTime())) {
88 throw new Error(`Cannot convert to date: '${value as string | number}'`);
94 export const convertToInt
= (value
: unknown
): number => {
98 let changedValue
: number = value
as number;
99 if (Number.isSafeInteger(value
)) {
100 return value
as number;
102 if (typeof value
=== 'number') {
103 return Math.trunc(value
);
105 if (isString(value
)) {
106 changedValue
= parseInt(value
as string);
108 if (isNaN(changedValue
)) {
109 throw new Error(`Cannot convert to integer: '${String(value)}'`);
114 export const convertToFloat
= (value
: unknown
): number => {
118 let changedValue
: number = value
as number;
119 if (isString(value
)) {
120 changedValue
= parseFloat(value
as string);
122 if (isNaN(changedValue
)) {
123 throw new Error(`Cannot convert to float: '${String(value)}'`);
128 export const convertToBoolean
= (value
: unknown
): boolean => {
132 if (typeof value
=== 'boolean') {
134 } else if (isString(value
) && ((value
as string).toLowerCase() === 'true' || value
=== '1')) {
136 } else if (typeof value
=== 'number' && value
=== 1) {
143 export const getRandomFloat
= (max
= Number.MAX_VALUE
, min
= 0): number => {
145 throw new RangeError('Invalid interval');
147 if (max
- min
=== Infinity) {
148 throw new RangeError('Invalid interval');
150 return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max
- min
) + min
;
153 export const getRandomInteger
= (max
= Constants
.MAX_RANDOM_INTEGER
, min
= 0): number => {
154 max
= Math.floor(max
);
155 if (!isNullOrUndefined(min
) && min
!== 0) {
156 min
= Math.ceil(min
);
157 return Math.floor(randomInt(min
, max
+ 1));
159 return Math.floor(randomInt(max
+ 1));
163 * Rounds the given number to the given scale.
164 * The rounding is done using the "round half away from zero" method.
166 * @param numberValue - The number to round.
167 * @param scale - The scale to round to.
168 * @returns The rounded number.
170 export const roundTo
= (numberValue
: number, scale
: number): number => {
171 const roundPower
= Math.pow(10, scale
);
172 return Math.round(numberValue
* roundPower
* (1 + Number.EPSILON
)) / roundPower
;
175 export const getRandomFloatRounded
= (max
= Number.MAX_VALUE
, min
= 0, scale
= 2): number => {
177 return roundTo(getRandomFloat(max
, min
), scale
);
179 return roundTo(getRandomFloat(max
), scale
);
182 export const getRandomFloatFluctuatedRounded
= (
184 fluctuationPercent
: number,
187 if (fluctuationPercent
< 0 || fluctuationPercent
> 100) {
188 throw new RangeError(
189 `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}`,
192 if (fluctuationPercent
=== 0) {
193 return roundTo(staticValue
, scale
);
195 const fluctuationRatio
= fluctuationPercent
/ 100;
196 return getRandomFloatRounded(
197 staticValue
* (1 + fluctuationRatio
),
198 staticValue
* (1 - fluctuationRatio
),
203 export const extractTimeSeriesValues
= (timeSeries
: Array<TimestampedData
>): number[] => {
204 return timeSeries
.map((timeSeriesItem
) => timeSeriesItem
.value
);
207 export const isObject
= (item
: unknown
): boolean => {
209 isNullOrUndefined(item
) === false && typeof item
=== 'object' && Array.isArray(item
) === false
221 | { [key
: string]: CloneableData
};
223 type FormatKey
= (key
: string) => string;
225 const deepClone
= <I
extends CloneableData
, O
extends CloneableData
= I
>(
227 formatKey
?: FormatKey
,
228 refs
: Map
<I
, O
> = new Map
<I
, O
>(),
230 const ref
= refs
.get(value
);
231 if (ref
!== undefined) {
234 if (Array.isArray(value
)) {
235 const clone
: CloneableData
[] = [];
236 refs
.set(value
, clone
as O
);
237 for (let i
= 0; i
< value
.length
; i
++) {
238 clone
[i
] = deepClone(value
[i
], formatKey
, refs
);
242 if (value
instanceof Date) {
243 return new Date(value
.valueOf()) as O
;
245 if (typeof value
!== 'object' || value
=== null) {
246 return value
as unknown
as O
;
248 const clone
: Record
<string, CloneableData
> = {};
249 refs
.set(value
, clone
as O
);
250 for (const key
of Object.keys(value
)) {
251 clone
[typeof formatKey
=== 'function' ? formatKey(key
) : key
] = deepClone(
260 export const cloneObject
= <T
>(object
: T
): T
=> {
261 return deepClone(object
as CloneableData
) as T
;
264 export const hasOwnProp
= (object
: unknown
, property
: PropertyKey
): boolean => {
265 return isObject(object
) && Object.hasOwn(object
as object
, property
);
268 export const isCFEnvironment
= (): boolean => {
269 return !isNullOrUndefined(env
.VCAP_APPLICATION
);
272 export const isIterable
= <T
>(obj
: T
): boolean => {
273 return !isNullOrUndefined(obj
) ? typeof obj
[Symbol
.iterator
as keyof T
] === 'function' : false;
276 const isString
= (value
: unknown
): boolean => {
277 return typeof value
=== 'string';
280 export const isEmptyString
= (value
: unknown
): boolean => {
281 return isNullOrUndefined(value
) || (isString(value
) && (value
as string).trim().length
=== 0);
284 export const isNotEmptyString
= (value
: unknown
): boolean => {
285 return isString(value
) && (value
as string).trim().length
> 0;
288 export const isUndefined
= (value
: unknown
): boolean => {
289 return value
=== undefined;
292 export const isNullOrUndefined
= (value
: unknown
): boolean => {
293 // eslint-disable-next-line eqeqeq, no-eq-null
294 return value
== null;
297 export const isEmptyArray
= (object
: unknown
): boolean => {
298 return Array.isArray(object
) && object
.length
=== 0;
301 export const isNotEmptyArray
= (object
: unknown
): boolean => {
302 return Array.isArray(object
) && object
.length
> 0;
305 export const isEmptyObject
= (obj
: object
): boolean => {
306 if (obj
?.constructor
!== Object) {
309 // Iterates over the keys of an object, if
310 // any exist, return false.
311 for (const _
in obj
) {
317 export const insertAt
= (str
: string, subStr
: string, pos
: number): string =>
318 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
321 * Computes the retry delay in milliseconds using an exponential backoff algorithm.
323 * @param retryNumber - the number of retries that have already been attempted
324 * @param delayFactor - the base delay factor in milliseconds
325 * @returns delay in milliseconds
327 export const exponentialDelay
= (retryNumber
= 0, delayFactor
= 100): number => {
328 const delay
= Math.pow(2, retryNumber
) * delayFactor
;
329 const randomSum
= delay
* 0.2 * secureRandom(); // 0-20% of the delay
330 return delay
+ randomSum
;
334 * Generates a cryptographically secure random number in the [0,1[ range
336 * @returns A number in the [0,1[ range
338 export const secureRandom
= (): number => {
339 return webcrypto
.getRandomValues(new Uint32Array(1))[0] / 0x100000000;
342 export const JSONStringifyWithMapSupport
= (
343 obj
: Record
<string, unknown
> | Record
<string, unknown
>[] | Map
<unknown
, unknown
>,
346 return JSON
.stringify(
348 (_
, value
: Record
<string, unknown
>) => {
349 if (value
instanceof Map
) {
362 * Converts websocket error code to human readable string message
364 * @param code - websocket error code
365 * @returns human readable string message
367 export const getWebSocketCloseEventStatusString
= (code
: number): string => {
368 if (code
>= 0 && code
<= 999) {
370 } else if (code
>= 1016) {
372 return '(For WebSocket standard)';
373 } else if (code
<= 2999) {
374 return '(For WebSocket extensions)';
375 } else if (code
<= 3999) {
376 return '(For libraries and frameworks)';
377 } else if (code
<= 4999) {
378 return '(For applications)';
383 WebSocketCloseEventStatusString
[code
as keyof
typeof WebSocketCloseEventStatusString
],
386 return WebSocketCloseEventStatusString
[code
as keyof
typeof WebSocketCloseEventStatusString
];
391 export const isArraySorted
= <T
>(array
: T
[], compareFn
: (a
: T
, b
: T
) => number): boolean => {
392 for (let index
= 0; index
< array
.length
- 1; ++index
) {
393 if (compareFn(array
[index
], array
[index
+ 1]) > 0) {
400 // eslint-disable-next-line @typescript-eslint/no-explicit-any
401 export const once
= <T
, A
extends any[], R
>(
402 fn
: (...args
: A
) => R
,
404 ): ((...args
: A
) => R
) => {
406 return (...args
: A
) => {
408 result
= fn
.apply
<T
, A
, R
>(context
, args
);
409 (fn
as unknown
as undefined) = (context
as unknown
as undefined) = undefined;
415 export const min
= (...args
: number[]): number =>
416 args
.reduce((minimum
, num
) => (minimum
< num
? minimum
: num
), Infinity);
418 export const max
= (...args
: number[]): number =>
419 args
.reduce((maximum
, num
) => (maximum
> num
? maximum
: num
), -Infinity);
421 export const throwErrorInNextTick
= (error
: Error): void => {