1 import { getRandomValues
, randomBytes
, randomInt
, randomUUID
} from
'node:crypto'
2 import { env
, nextTick
} from
'node:process'
10 millisecondsToMinutes
,
11 millisecondsToSeconds
,
15 import { clone
as cloneDeep
} from
'rambda'
17 import { Constants
} from
'./Constants.js'
20 type ProtocolResponse
,
22 WebSocketCloseEventStatusString
23 } from
'../types/index.js'
25 export const logPrefix
= (prefixString
= ''): string => {
26 return `${new Date().toLocaleString()}${prefixString}`
29 export const generateUUID
= (): string => {
33 export const validateUUID
= (uuid
: string): boolean => {
34 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(uuid
)
37 export const sleep
= async (milliSeconds
: number): Promise
<NodeJS
.Timeout
> => {
38 return await new Promise
<NodeJS
.Timeout
>(resolve
=>
39 setTimeout(resolve
as () => void, milliSeconds
)
43 export const formatDurationMilliSeconds
= (duration
: number): string => {
44 duration
= convertToInt(duration
)
46 throw new RangeError('Duration cannot be negative')
48 const days
= Math.floor(duration
/ (24 * 3600 * 1000))
49 const hours
= Math.floor(millisecondsToHours(duration
) - days
* 24)
50 const minutes
= Math.floor(
51 millisecondsToMinutes(duration
) - days
* 24 * 60 - hoursToMinutes(hours
)
53 const seconds
= Math.floor(
54 millisecondsToSeconds(duration
) -
56 hoursToSeconds(hours
) -
57 minutesToSeconds(minutes
)
59 if (days
=== 0 && hours
=== 0 && minutes
=== 0 && seconds
=== 0) {
60 return formatDuration({ seconds
}, { zero
: true })
62 return formatDuration({
70 export const formatDurationSeconds
= (duration
: number): string => {
71 return formatDurationMilliSeconds(secondsToMilliseconds(duration
))
74 // More efficient time validation function than the one provided by date-fns
75 export const isValidDate
= (date
: Date | number | undefined): date
is Date | number => {
76 if (typeof date
=== 'number') {
78 } else if (isDate(date
)) {
79 return !isNaN(date
.getTime())
84 export const convertToDate
= (
85 value
: Date | string | number | undefined | null
86 ): Date | undefined => {
93 if (isString(value
) || typeof value
=== 'number') {
94 const valueToDate
= new Date(value
)
95 if (isNaN(valueToDate
.getTime())) {
96 throw new Error(`Cannot convert to date: '${value}'`)
102 export const convertToInt
= (value
: unknown
): number => {
106 let changedValue
: number = value
as number
107 if (Number.isSafeInteger(value
)) {
108 return value
as number
110 if (typeof value
=== 'number') {
111 return Math.trunc(value
)
113 if (isString(value
)) {
114 changedValue
= parseInt(value
)
116 if (isNaN(changedValue
)) {
117 throw new Error(`Cannot convert to integer: '${String(value)}'`)
122 export const convertToFloat
= (value
: unknown
): number => {
126 let changedValue
: number = value
as number
127 if (isString(value
)) {
128 changedValue
= parseFloat(value
)
130 if (isNaN(changedValue
)) {
131 throw new Error(`Cannot convert to float: '${String(value)}'`)
136 export const convertToBoolean
= (value
: unknown
): boolean => {
140 if (typeof value
=== 'boolean') {
142 } else if (isString(value
) && (value
.toLowerCase() === 'true' || value
=== '1')) {
144 } else if (typeof value
=== 'number' && value
=== 1) {
151 export const getRandomFloat
= (max
= Number.MAX_VALUE
, min
= 0): number => {
153 throw new RangeError('Invalid interval')
155 if (max
- min
=== Infinity) {
156 throw new RangeError('Invalid interval')
158 return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max
- min
) + min
161 export const getRandomInteger
= (max
= Constants
.MAX_RANDOM_INTEGER
, min
= 0): number => {
162 max
= Math.floor(max
)
165 return Math.floor(randomInt(min
, max
+ 1))
167 return Math.floor(randomInt(max
+ 1))
171 * Rounds the given number to the given scale.
172 * The rounding is done using the "round half away from zero" method.
174 * @param numberValue - The number to round.
175 * @param scale - The scale to round to.
176 * @returns The rounded number.
178 export const roundTo
= (numberValue
: number, scale
: number): number => {
179 const roundPower
= Math.pow(10, scale
)
180 return Math.round(numberValue
* roundPower
* (1 + Number.EPSILON
)) / roundPower
183 export const getRandomFloatRounded
= (max
= Number.MAX_VALUE
, min
= 0, scale
= 2): number => {
185 return roundTo(getRandomFloat(max
, min
), scale
)
187 return roundTo(getRandomFloat(max
), scale
)
190 export const getRandomFloatFluctuatedRounded
= (
192 fluctuationPercent
: number,
195 if (fluctuationPercent
< 0 || fluctuationPercent
> 100) {
196 throw new RangeError(
197 `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}`
200 if (fluctuationPercent
=== 0) {
201 return roundTo(staticValue
, scale
)
203 const fluctuationRatio
= fluctuationPercent
/ 100
204 return getRandomFloatRounded(
205 staticValue
* (1 + fluctuationRatio
),
206 staticValue
* (1 - fluctuationRatio
),
211 export const extractTimeSeriesValues
= (timeSeries
: TimestampedData
[]): number[] => {
212 return timeSeries
.map(timeSeriesItem
=> timeSeriesItem
.value
)
215 export const clone
= <T
>(object
: T
): T
=> {
216 return cloneDeep
<T
>(object
)
220 * Detects whether the given value is an asynchronous function or not.
222 * @param fn - Unknown value.
223 * @returns `true` if `fn` was an asynchronous function, otherwise `false`.
226 export const isAsyncFunction
= (fn
: unknown
): fn
is (...args
: unknown
[]) => Promise
<unknown
> => {
227 return typeof fn
=== 'function' && fn
.constructor
.name
=== 'AsyncFunction'
230 export const isObject
= (value
: unknown
): value
is object
=> {
231 return value
!= null && typeof value
=== 'object' && !Array.isArray(value
)
234 export const isEmptyObject
= (object
: object
): object
is EmptyObject
=> {
235 if (object
.constructor
!== Object) {
238 // Iterates over the keys of an object, if
239 // any exist, return false.
240 // eslint-disable-next-line no-unreachable-loop
241 for (const _
in object
) {
247 export const hasOwnProp
= (value
: unknown
, property
: PropertyKey
): boolean => {
248 return isObject(value
) && Object.hasOwn(value
, property
)
251 export const isCFEnvironment
= (): boolean => {
252 return env
.VCAP_APPLICATION
!= null
255 const isString
= (value
: unknown
): value
is string => {
256 return typeof value
=== 'string'
259 export const isEmptyString
= (value
: unknown
): value
is '' | undefined | null => {
260 return value
== null || (isString(value
) && value
.trim().length
=== 0)
263 export const isNotEmptyString
= (value
: unknown
): value
is string => {
264 return isString(value
) && value
.trim().length
> 0
267 export const isEmptyArray
= (value
: unknown
): value
is never[] => {
268 return Array.isArray(value
) && value
.length
=== 0
271 export const isNotEmptyArray
= (value
: unknown
): value
is unknown
[] => {
272 return Array.isArray(value
) && value
.length
> 0
275 export const insertAt
= (str
: string, subStr
: string, pos
: number): string =>
276 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`
279 * Computes the retry delay in milliseconds using an exponential backoff algorithm.
281 * @param retryNumber - the number of retries that have already been attempted
282 * @param delayFactor - the base delay factor in milliseconds
283 * @returns delay in milliseconds
285 export const exponentialDelay
= (retryNumber
= 0, delayFactor
= 100): number => {
286 const delay
= Math.pow(2, retryNumber
) * delayFactor
287 const randomSum
= delay
* 0.2 * secureRandom() // 0-20% of the delay
288 return delay
+ randomSum
292 * Generates a cryptographically secure random number in the [0,1[ range
294 * @returns A number in the [0,1[ range
296 export const secureRandom
= (): number => {
297 return getRandomValues(new Uint32Array(1))[0] / 0x100000000
300 export const JSONStringifyWithMapSupport
= (
302 | Record
<string, unknown
>
303 | Array<Record
<string, unknown
>>
304 | Map
<unknown
, unknown
>
306 space
?: string | number
308 return JSON
.stringify(
310 (_
, value
: Record
<string, unknown
>) => {
311 if (value
instanceof Map
) {
324 * Converts websocket error code to human readable string message
326 * @param code - websocket error code
327 * @returns human readable string message
329 export const getWebSocketCloseEventStatusString
= (code
: number): string => {
330 if (code
>= 0 && code
<= 999) {
332 } else if (code
>= 1016) {
334 return '(For WebSocket standard)'
335 } else if (code
<= 2999) {
336 return '(For WebSocket extensions)'
337 } else if (code
<= 3999) {
338 return '(For libraries and frameworks)'
339 } else if (code
<= 4999) {
340 return '(For applications)'
344 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
345 WebSocketCloseEventStatusString
[code
as keyof
typeof WebSocketCloseEventStatusString
] != null
347 return WebSocketCloseEventStatusString
[code
as keyof
typeof WebSocketCloseEventStatusString
]
352 export const isArraySorted
= <T
>(array
: T
[], compareFn
: (a
: T
, b
: T
) => number): boolean => {
353 for (let index
= 0; index
< array
.length
- 1; ++index
) {
354 if (compareFn(array
[index
], array
[index
+ 1]) > 0) {
361 // eslint-disable-next-line @typescript-eslint/no-explicit-any
362 export const once
= <T
, A
extends any[], R
>(
363 fn
: (...args
: A
) => R
,
365 ): ((...args
: A
) => R
) => {
367 return (...args
: A
) => {
368 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
370 result
= fn
.apply
<T
, A
, R
>(context
, args
)
371 ;(fn
as unknown
as undefined) = (context
as unknown
as undefined) = undefined
377 export const min
= (...args
: number[]): number =>
378 args
.reduce((minimum
, num
) => (minimum
< num
? minimum
: num
), Infinity)
380 export const max
= (...args
: number[]): number =>
381 args
.reduce((maximum
, num
) => (maximum
> num
? maximum
: num
), -Infinity)
383 export const throwErrorInNextTick
= (error
: Error): void => {