1 import { randomBytes
, randomInt
, randomUUID
} from
'node:crypto';
2 import { inspect
} from
'node:util';
4 import { formatDuration
, secondsToMilliseconds
} from
'date-fns';
5 import clone from
'just-clone';
7 import { Constants
} from
'./Constants';
8 import { type TimestampedData
, WebSocketCloseEventStatusString
} from
'../types';
10 export const logPrefix
= (prefixString
= ''): string => {
11 return `${new Date().toLocaleString()}${prefixString}`;
14 export const generateUUID
= (): string => {
18 export const validateUUID
= (uuid
: string): boolean => {
19 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 export const sleep
= async (milliSeconds
: number): Promise
<NodeJS
.Timeout
> => {
25 return new Promise
<NodeJS
.Timeout
>((resolve
) => setTimeout(resolve
as () => void, milliSeconds
));
28 export const formatDurationMilliSeconds
= (duration
: number): string => {
29 duration
= convertToInt(duration
);
30 const days
= Math.floor(duration
/ (24 * 3600 * 1000));
31 const hours
= Math.floor(duration
/ (3600 * 1000) - days
* 24);
32 const minutes
= Math.floor(duration
/ (60 * 1000) - days
* 24 * 60 - hours
* 60);
33 const seconds
= Math.floor(duration
/ 1000 - days
* 24 * 3600 - hours
* 3600 - minutes
* 60);
34 return formatDuration({
42 export const formatDurationSeconds
= (duration
: number): string => {
43 return formatDurationMilliSeconds(secondsToMilliseconds(duration
));
46 export const convertToDate
= (
47 value
: Date | string | number | null | undefined,
48 ): Date | null | undefined => {
49 if (isNullOrUndefined(value
)) {
50 return value
as null | undefined;
52 if (value
instanceof Date) {
55 if (isString(value
) || typeof value
=== 'number') {
56 return new Date(value
!);
61 export const convertToInt
= (value
: unknown
): number => {
65 let changedValue
: number = value
as number;
66 if (Number.isSafeInteger(value
)) {
67 return value
as number;
69 if (typeof value
=== 'number') {
70 return Math.trunc(value
);
72 if (isString(value
)) {
73 changedValue
= parseInt(value
as string);
75 if (isNaN(changedValue
)) {
76 // eslint-disable-next-line @typescript-eslint/no-base-to-string
77 throw new Error(`Cannot convert to integer: ${value.toString()}`);
82 export const convertToFloat
= (value
: unknown
): number => {
86 let changedValue
: number = value
as number;
87 if (isString(value
)) {
88 changedValue
= parseFloat(value
as string);
90 if (isNaN(changedValue
)) {
91 // eslint-disable-next-line @typescript-eslint/no-base-to-string
92 throw new Error(`Cannot convert to float: ${value.toString()}`);
97 export const convertToBoolean
= (value
: unknown
): boolean => {
101 if (typeof value
=== 'boolean') {
103 } else if (isString(value
) && ((value
as string).toLowerCase() === 'true' || value
=== '1')) {
105 } else if (typeof value
=== 'number' && value
=== 1) {
112 export const getRandomFloat
= (max
= Number.MAX_VALUE
, min
= 0): number => {
114 throw new RangeError('Invalid interval');
116 if (max
- min
=== Infinity) {
117 throw new RangeError('Invalid interval');
119 return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max
- min
) + min
;
122 export const getRandomInteger
= (max
= Constants
.MAX_RANDOM_INTEGER
, min
= 0): number => {
123 max
= Math.floor(max
);
124 if (!isNullOrUndefined(min
) && min
!== 0) {
125 min
= Math.ceil(min
);
126 return Math.floor(randomInt(min
, max
+ 1));
128 return Math.floor(randomInt(max
+ 1));
132 * Rounds the given number to the given scale.
133 * The rounding is done using the "round half away from zero" method.
135 * @param numberValue - The number to round.
136 * @param scale - The scale to round to.
137 * @returns The rounded number.
139 export const roundTo
= (numberValue
: number, scale
: number): number => {
140 const roundPower
= Math.pow(10, scale
);
141 return Math.round(numberValue
* roundPower
* (1 + Number.EPSILON
)) / roundPower
;
144 export const getRandomFloatRounded
= (max
= Number.MAX_VALUE
, min
= 0, scale
= 2): number => {
146 return roundTo(getRandomFloat(max
, min
), scale
);
148 return roundTo(getRandomFloat(max
), scale
);
151 export const getRandomFloatFluctuatedRounded
= (
153 fluctuationPercent
: number,
156 if (fluctuationPercent
< 0 || fluctuationPercent
> 100) {
157 throw new RangeError(
158 `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}`,
161 if (fluctuationPercent
=== 0) {
162 return roundTo(staticValue
, scale
);
164 const fluctuationRatio
= fluctuationPercent
/ 100;
165 return getRandomFloatRounded(
166 staticValue
* (1 + fluctuationRatio
),
167 staticValue
* (1 - fluctuationRatio
),
172 export const extractTimeSeriesValues
= (timeSeries
: Array<TimestampedData
>): number[] => {
173 return timeSeries
.map((timeSeriesItem
) => timeSeriesItem
.value
);
176 export const isObject
= (item
: unknown
): boolean => {
178 isNullOrUndefined(item
) === false && typeof item
=== 'object' && Array.isArray(item
) === false
182 export const cloneObject
= <T
extends object
>(object
: T
): T
=> {
183 return clone
<T
>(object
);
186 export const hasOwnProp
= (object
: unknown
, property
: PropertyKey
): boolean => {
187 return isObject(object
) && Object.hasOwn(object
as object
, property
);
190 export const isCFEnvironment
= (): boolean => {
191 return !isNullOrUndefined(process
.env
.VCAP_APPLICATION
);
194 export const isIterable
= <T
>(obj
: T
): boolean => {
195 return !isNullOrUndefined(obj
) ? typeof obj
[Symbol
.iterator
as keyof T
] === 'function' : false;
198 const isString
= (value
: unknown
): boolean => {
199 return typeof value
=== 'string';
202 export const isEmptyString
= (value
: unknown
): boolean => {
203 return isNullOrUndefined(value
) || (isString(value
) && (value
as string).trim().length
=== 0);
206 export const isNotEmptyString
= (value
: unknown
): boolean => {
207 return isString(value
) && (value
as string).trim().length
> 0;
210 export const isUndefined
= (value
: unknown
): boolean => {
211 return value
=== undefined;
214 export const isNullOrUndefined
= (value
: unknown
): boolean => {
215 // eslint-disable-next-line eqeqeq, no-eq-null
216 return value
== null;
219 export const isEmptyArray
= (object
: unknown
): boolean => {
220 return Array.isArray(object
) && object
.length
=== 0;
223 export const isNotEmptyArray
= (object
: unknown
): boolean => {
224 return Array.isArray(object
) && object
.length
> 0;
227 export const isEmptyObject
= (obj
: object
): boolean => {
228 if (obj
?.constructor
!== Object) {
231 // Iterates over the keys of an object, if
232 // any exist, return false.
233 for (const _
in obj
) {
239 export const insertAt
= (str
: string, subStr
: string, pos
: number): string =>
240 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
243 * Computes the retry delay in milliseconds using an exponential backoff algorithm.
245 * @param retryNumber - the number of retries that have already been attempted
246 * @returns delay in milliseconds
248 export const exponentialDelay
= (retryNumber
= 0, maxDelayRatio
= 0.2): number => {
249 const delay
= Math.pow(2, retryNumber
) * 100;
250 const randomSum
= delay
* maxDelayRatio
* secureRandom(); // 0-20% of the delay
251 return delay
+ randomSum
;
254 const isPromisePending
= (promise
: Promise
<unknown
>): boolean => {
255 return inspect(promise
).includes('pending');
258 export const promiseWithTimeout
= async <T
>(
262 timeoutCallback
: () => void = () => {
263 /* This is intentional */
266 // Create a timeout promise that rejects in timeout milliseconds
267 const timeoutPromise
= new Promise
<never>((_
, reject
) => {
269 if (isPromisePending(promise
)) {
271 // FIXME: The original promise shall be canceled
273 reject(timeoutError
);
277 // Returns a race between timeout promise and the passed promise
278 return Promise
.race
<T
>([promise
, timeoutPromise
]);
282 * Generates a cryptographically secure random number in the [0,1[ range
286 export const secureRandom
= (): number => {
287 return randomBytes(4).readUInt32LE() / 0x100000000;
290 export const JSONStringifyWithMapSupport
= (
291 obj
: Record
<string, unknown
> | Record
<string, unknown
>[] | Map
<unknown
, unknown
>,
294 return JSON
.stringify(
296 (_
, value
: Record
<string, unknown
>) => {
297 if (value
instanceof Map
) {
310 * Converts websocket error code to human readable string message
312 * @param code - websocket error code
313 * @returns human readable string message
315 export const getWebSocketCloseEventStatusString
= (code
: number): string => {
316 if (code
>= 0 && code
<= 999) {
318 } else if (code
>= 1016) {
320 return '(For WebSocket standard)';
321 } else if (code
<= 2999) {
322 return '(For WebSocket extensions)';
323 } else if (code
<= 3999) {
324 return '(For libraries and frameworks)';
325 } else if (code
<= 4999) {
326 return '(For applications)';
331 WebSocketCloseEventStatusString
[code
as keyof
typeof WebSocketCloseEventStatusString
],
334 return WebSocketCloseEventStatusString
[code
as keyof
typeof WebSocketCloseEventStatusString
];