1 import { getRandomValues
, randomBytes
, randomInt
, randomUUID
} from
'node:crypto'
2 import { env
, nextTick
} from
'node:process'
10 millisecondsToMinutes
,
11 millisecondsToSeconds
,
21 WebSocketCloseEventStatusString
22 } from
'../types/index.js'
23 import { Constants
} from
'./Constants.js'
25 export const logPrefix
= (prefixString
= ''): string => {
26 return `${new Date().toLocaleString()}${prefixString}`
29 export const generateUUID
= (): `${string}-${string}-${string}-${string}-${string}` => {
33 export const validateUUID
= (
34 uuid
: `${string}-${string}-${string}-${string}-${string}`
35 ): uuid
is `${string}-${string}-${string}-${string}-${string}` => {
36 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
)
39 export const sleep
= async (milliSeconds
: number): Promise
<NodeJS
.Timeout
> => {
40 return await new Promise
<NodeJS
.Timeout
>(resolve
=>
41 setTimeout(resolve
as () => void, milliSeconds
)
45 export const formatDurationMilliSeconds
= (duration
: number): string => {
46 duration
= convertToInt(duration
)
48 throw new RangeError('Duration cannot be negative')
50 const days
= Math.floor(duration
/ (24 * 3600 * 1000))
51 const hours
= Math.floor(millisecondsToHours(duration
) - days
* 24)
52 const minutes
= Math.floor(
53 millisecondsToMinutes(duration
) - days
* 24 * 60 - hoursToMinutes(hours
)
55 const seconds
= Math.floor(
56 millisecondsToSeconds(duration
) -
58 hoursToSeconds(hours
) -
59 minutesToSeconds(minutes
)
61 if (days
=== 0 && hours
=== 0 && minutes
=== 0 && seconds
=== 0) {
62 return formatDuration({ seconds
}, { zero
: true })
64 return formatDuration({
72 export const formatDurationSeconds
= (duration
: number): string => {
73 return formatDurationMilliSeconds(secondsToMilliseconds(duration
))
76 // More efficient time validation function than the one provided by date-fns
77 export const isValidDate
= (date
: Date | number | undefined): date
is Date | number => {
78 if (typeof date
=== 'number') {
80 } else if (isDate(date
)) {
81 return !isNaN(date
.getTime())
86 export const convertToDate
= (
87 value
: Date | string | number | undefined | null
88 ): Date | undefined => {
95 if (isString(value
) || typeof value
=== 'number') {
96 const valueToDate
= new Date(value
)
97 if (isNaN(valueToDate
.getTime())) {
98 throw new Error(`Cannot convert to date: '${value}'`)
104 export const convertToInt
= (value
: unknown
): number => {
108 if (Number.isSafeInteger(value
)) {
109 return value
as number
111 if (typeof value
=== 'number') {
112 return Math.trunc(value
)
114 let changedValue
: number = value
as number
115 if (isString(value
)) {
116 changedValue
= parseInt(value
)
118 if (isNaN(changedValue
)) {
119 throw new Error(`Cannot convert to integer: '${String(value)}'`)
124 export const convertToFloat
= (value
: unknown
): number => {
128 let changedValue
: number = value
as number
129 if (isString(value
)) {
130 changedValue
= parseFloat(value
)
132 if (isNaN(changedValue
)) {
133 throw new Error(`Cannot convert to float: '${String(value)}'`)
138 export const convertToBoolean
= (value
: unknown
): boolean => {
142 if (typeof value
=== 'boolean') {
144 } else if (isString(value
) && (value
.toLowerCase() === 'true' || value
=== '1')) {
146 } else if (typeof value
=== 'number' && value
=== 1) {
153 export const getRandomFloat
= (max
= Number.MAX_VALUE
, min
= 0): number => {
155 throw new RangeError('Invalid interval')
157 if (max
- min
=== Infinity) {
158 throw new RangeError('Invalid interval')
160 return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max
- min
) + min
163 export const getRandomInteger
= (max
= Constants
.MAX_RANDOM_INTEGER
, min
= 0): number => {
164 max
= Math.floor(max
)
167 return Math.floor(randomInt(min
, max
+ 1))
169 return Math.floor(randomInt(max
+ 1))
173 * Rounds the given number to the given scale.
174 * The rounding is done using the "round half away from zero" method.
176 * @param numberValue - The number to round.
177 * @param scale - The scale to round to.
178 * @returns The rounded number.
180 export const roundTo
= (numberValue
: number, scale
: number): number => {
181 const roundPower
= Math.pow(10, scale
)
182 return Math.round(numberValue
* roundPower
* (1 + Number.EPSILON
)) / roundPower
185 export const getRandomFloatRounded
= (max
= Number.MAX_VALUE
, min
= 0, scale
= 2): number => {
187 return roundTo(getRandomFloat(max
, min
), scale
)
189 return roundTo(getRandomFloat(max
), scale
)
192 export const getRandomFloatFluctuatedRounded
= (
194 fluctuationPercent
: number,
197 if (fluctuationPercent
< 0 || fluctuationPercent
> 100) {
198 throw new RangeError(
199 `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}`
202 if (fluctuationPercent
=== 0) {
203 return roundTo(staticValue
, scale
)
205 const fluctuationRatio
= fluctuationPercent
/ 100
206 return getRandomFloatRounded(
207 staticValue
* (1 + fluctuationRatio
),
208 staticValue
* (1 - fluctuationRatio
),
213 export const extractTimeSeriesValues
= (timeSeries
: TimestampedData
[]): number[] => {
214 return timeSeries
.map(timeSeriesItem
=> timeSeriesItem
.value
)
217 export const clone
= <T
>(object
: T
): T
=> {
218 return structuredClone
<T
>(object
)
222 * Detects whether the given value is an asynchronous function or not.
224 * @param fn - Unknown value.
225 * @returns `true` if `fn` was an asynchronous function, otherwise `false`.
228 export const isAsyncFunction
= (fn
: unknown
): fn
is (...args
: unknown
[]) => Promise
<unknown
> => {
229 return typeof fn
=== 'function' && fn
.constructor
.name
=== 'AsyncFunction'
232 export const isObject
= (value
: unknown
): value
is object
=> {
233 return value
!= null && typeof value
=== 'object' && !Array.isArray(value
)
236 export const isEmptyObject
= (object
: object
): object
is EmptyObject
=> {
237 if (object
.constructor
!== Object) {
240 // Iterates over the keys of an object, if
241 // any exist, return false.
242 // eslint-disable-next-line no-unreachable-loop
243 for (const _
in object
) {
249 export const hasOwnProp
= (value
: unknown
, property
: PropertyKey
): boolean => {
250 return isObject(value
) && Object.hasOwn(value
, property
)
253 export const isCFEnvironment
= (): boolean => {
254 return env
.VCAP_APPLICATION
!= null
257 const isString
= (value
: unknown
): value
is string => {
258 return typeof value
=== 'string'
261 export const isEmptyString
= (value
: unknown
): value
is '' | undefined | null => {
262 return value
== null || (isString(value
) && value
.trim().length
=== 0)
265 export const isNotEmptyString
= (value
: unknown
): value
is string => {
266 return isString(value
) && value
.trim().length
> 0
269 export const isEmptyArray
= (value
: unknown
): value
is [] => {
270 return Array.isArray(value
) && value
.length
=== 0
273 export const isNotEmptyArray
= (value
: unknown
): value
is unknown
[] => {
274 return Array.isArray(value
) && value
.length
> 0
277 export const insertAt
= (str
: string, subStr
: string, pos
: number): string =>
278 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`
281 * Computes the retry delay in milliseconds using an exponential backoff algorithm.
283 * @param retryNumber - the number of retries that have already been attempted
284 * @param delayFactor - the base delay factor in milliseconds
285 * @returns delay in milliseconds
287 export const exponentialDelay
= (retryNumber
= 0, delayFactor
= 100): number => {
288 const delay
= Math.pow(2, retryNumber
) * delayFactor
289 const randomSum
= delay
* 0.2 * secureRandom() // 0-20% of the delay
290 return delay
+ randomSum
294 * Generates a cryptographically secure random number in the [0,1[ range
296 * @returns A number in the [0,1[ range
298 export const secureRandom
= (): number => {
299 return getRandomValues(new Uint32Array(1))[0] / 0x100000000
302 export const JSONStringify
= <
305 | Array<Record
<string, unknown
>>
306 | Set
<Record
<string, unknown
>>
307 | Map
<string, Record
<string, unknown
>>
310 space
?: string | number,
311 mapFormat
?: MapStringifyFormat
313 return JSON
.stringify(
315 (_
, value
: Record
<string, unknown
>) => {
316 if (value
instanceof Map
) {
318 case MapStringifyFormat
.object
:
319 return { ...Object.fromEntries
<Map
<string, Record
<string, unknown
>>>(value
.entries()) }
320 case MapStringifyFormat
.array
:
324 } else if (value
instanceof Set
) {
325 return [...value
] as JsonType
[]
334 * Converts websocket error code to human readable string message
336 * @param code - websocket error code
337 * @returns human readable string message
339 export const getWebSocketCloseEventStatusString
= (code
: number): string => {
340 if (code
>= 0 && code
<= 999) {
342 } else if (code
>= 1016) {
344 return '(For WebSocket standard)'
345 } else if (code
<= 2999) {
346 return '(For WebSocket extensions)'
347 } else if (code
<= 3999) {
348 return '(For libraries and frameworks)'
349 } else if (code
<= 4999) {
350 return '(For applications)'
354 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
355 WebSocketCloseEventStatusString
[code
as keyof
typeof WebSocketCloseEventStatusString
] != null
357 return WebSocketCloseEventStatusString
[code
as keyof
typeof WebSocketCloseEventStatusString
]
362 export const isArraySorted
= <T
>(array
: T
[], compareFn
: (a
: T
, b
: T
) => number): boolean => {
363 for (let index
= 0; index
< array
.length
- 1; ++index
) {
364 if (compareFn(array
[index
], array
[index
+ 1]) > 0) {
371 // eslint-disable-next-line @typescript-eslint/no-explicit-any
372 export const once
= <T
, A
extends any[], R
>(
373 fn
: (...args
: A
) => R
,
375 ): ((...args
: A
) => R
) => {
377 return (...args
: A
) => {
378 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
380 result
= fn
.apply
<T
, A
, R
>(context
, args
)
381 ;(fn
as unknown
as undefined) = (context
as unknown
as undefined) = undefined
387 export const min
= (...args
: number[]): number =>
388 args
.reduce((minimum
, num
) => (minimum
< num
? minimum
: num
), Infinity)
390 export const max
= (...args
: number[]): number =>
391 args
.reduce((maximum
, num
) => (maximum
> num
? maximum
: num
), -Infinity)
393 export const throwErrorInNextTick
= (error
: Error): void => {