Commit | Line | Data |
---|---|---|
66a7748d JB |
1 | import { getRandomValues, randomBytes, randomInt, randomUUID } from 'node:crypto' |
2 | import { env, nextTick } from 'node:process' | |
8114d10e | 3 | |
f0c6601c JB |
4 | import { |
5 | formatDuration, | |
be4c6702 JB |
6 | hoursToMinutes, |
7 | hoursToSeconds, | |
b5c19509 | 8 | isDate, |
f0c6601c JB |
9 | millisecondsToHours, |
10 | millisecondsToMinutes, | |
11 | millisecondsToSeconds, | |
be4c6702 | 12 | minutesToSeconds, |
66a7748d JB |
13 | secondsToMilliseconds |
14 | } from 'date-fns' | |
088ee3c1 | 15 | |
4ccf551d JB |
16 | import { |
17 | type EmptyObject, | |
a66bbcfe | 18 | type ProtocolResponse, |
4ccf551d JB |
19 | type TimestampedData, |
20 | WebSocketCloseEventStatusString | |
21 | } from '../types/index.js' | |
4c3f6c20 | 22 | import { Constants } from './Constants.js' |
5e3cb728 | 23 | |
9bf0ef23 | 24 | export const logPrefix = (prefixString = ''): string => { |
66a7748d JB |
25 | return `${new Date().toLocaleString()}${prefixString}` |
26 | } | |
d5bd1c00 | 27 | |
2c5c7443 | 28 | export const generateUUID = (): `${string}-${string}-${string}-${string}-${string}` => { |
66a7748d JB |
29 | return randomUUID() |
30 | } | |
147d0e0f | 31 | |
2c5c7443 JB |
32 | export const validateUUID = ( |
33 | uuid: `${string}-${string}-${string}-${string}-${string}` | |
34 | ): uuid is `${string}-${string}-${string}-${string}-${string}` => { | |
66a7748d JB |
35 | 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) |
36 | } | |
03eacbe5 | 37 | |
9bf0ef23 | 38 | export const sleep = async (milliSeconds: number): Promise<NodeJS.Timeout> => { |
a974c8e4 | 39 | return await new Promise<NodeJS.Timeout>(resolve => |
66a7748d JB |
40 | setTimeout(resolve as () => void, milliSeconds) |
41 | ) | |
42 | } | |
7dde0b73 | 43 | |
9bf0ef23 | 44 | export const formatDurationMilliSeconds = (duration: number): string => { |
66a7748d | 45 | duration = convertToInt(duration) |
17b07e47 | 46 | if (duration < 0) { |
66a7748d | 47 | throw new RangeError('Duration cannot be negative') |
17b07e47 | 48 | } |
66a7748d JB |
49 | const days = Math.floor(duration / (24 * 3600 * 1000)) |
50 | const hours = Math.floor(millisecondsToHours(duration) - days * 24) | |
be4c6702 | 51 | const minutes = Math.floor( |
66a7748d JB |
52 | millisecondsToMinutes(duration) - days * 24 * 60 - hoursToMinutes(hours) |
53 | ) | |
f0c6601c | 54 | const seconds = Math.floor( |
be4c6702 JB |
55 | millisecondsToSeconds(duration) - |
56 | days * 24 * 3600 - | |
57 | hoursToSeconds(hours) - | |
66a7748d JB |
58 | minutesToSeconds(minutes) |
59 | ) | |
d7ceb0f0 | 60 | if (days === 0 && hours === 0 && minutes === 0 && seconds === 0) { |
66a7748d | 61 | return formatDuration({ seconds }, { zero: true }) |
d7ceb0f0 JB |
62 | } |
63 | return formatDuration({ | |
64 | days, | |
65 | hours, | |
66 | minutes, | |
66a7748d JB |
67 | seconds |
68 | }) | |
69 | } | |
7dde0b73 | 70 | |
9bf0ef23 | 71 | export const formatDurationSeconds = (duration: number): string => { |
66a7748d JB |
72 | return formatDurationMilliSeconds(secondsToMilliseconds(duration)) |
73 | } | |
7dde0b73 | 74 | |
0bd926c1 | 75 | // More efficient time validation function than the one provided by date-fns |
5dc7c990 | 76 | export const isValidDate = (date: Date | number | undefined): date is Date | number => { |
b5c19509 | 77 | if (typeof date === 'number') { |
66a7748d | 78 | return !isNaN(date) |
b5c19509 | 79 | } else if (isDate(date)) { |
66a7748d | 80 | return !isNaN(date.getTime()) |
b5c19509 | 81 | } |
66a7748d JB |
82 | return false |
83 | } | |
b5c19509 | 84 | |
a78c196b | 85 | export const convertToDate = ( |
5dc7c990 | 86 | value: Date | string | number | undefined | null |
79fd697f | 87 | ): Date | undefined => { |
66a7748d | 88 | if (value == null) { |
79fd697f | 89 | return undefined |
7dde0b73 | 90 | } |
0bd926c1 | 91 | if (isDate(value)) { |
66a7748d | 92 | return value |
a6e68f34 | 93 | } |
9bf0ef23 | 94 | if (isString(value) || typeof value === 'number') { |
66a7748d | 95 | const valueToDate = new Date(value) |
85cce27f | 96 | if (isNaN(valueToDate.getTime())) { |
66a7748d | 97 | throw new Error(`Cannot convert to date: '${value}'`) |
43ff25b8 | 98 | } |
66a7748d | 99 | return valueToDate |
560bcf5b | 100 | } |
66a7748d | 101 | } |
560bcf5b | 102 | |
9bf0ef23 | 103 | export const convertToInt = (value: unknown): number => { |
66a7748d JB |
104 | if (value == null) { |
105 | return 0 | |
560bcf5b | 106 | } |
9bf0ef23 | 107 | if (Number.isSafeInteger(value)) { |
66a7748d | 108 | return value as number |
6d3a11a0 | 109 | } |
9bf0ef23 | 110 | if (typeof value === 'number') { |
66a7748d | 111 | return Math.trunc(value) |
7dde0b73 | 112 | } |
f5ee1403 | 113 | let changedValue: number = value as number |
9bf0ef23 | 114 | if (isString(value)) { |
5dc7c990 | 115 | changedValue = parseInt(value) |
9ccca265 | 116 | } |
9bf0ef23 | 117 | if (isNaN(changedValue)) { |
66a7748d | 118 | throw new Error(`Cannot convert to integer: '${String(value)}'`) |
dada83ec | 119 | } |
66a7748d JB |
120 | return changedValue |
121 | } | |
dada83ec | 122 | |
9bf0ef23 | 123 | export const convertToFloat = (value: unknown): number => { |
66a7748d JB |
124 | if (value == null) { |
125 | return 0 | |
dada83ec | 126 | } |
66a7748d | 127 | let changedValue: number = value as number |
9bf0ef23 | 128 | if (isString(value)) { |
5dc7c990 | 129 | changedValue = parseFloat(value) |
560bcf5b | 130 | } |
9bf0ef23 | 131 | if (isNaN(changedValue)) { |
66a7748d | 132 | throw new Error(`Cannot convert to float: '${String(value)}'`) |
5a2a53cf | 133 | } |
66a7748d JB |
134 | return changedValue |
135 | } | |
5a2a53cf | 136 | |
9bf0ef23 | 137 | export const convertToBoolean = (value: unknown): boolean => { |
66a7748d | 138 | let result = false |
a78c196b | 139 | if (value != null) { |
9bf0ef23 JB |
140 | // Check the type |
141 | if (typeof value === 'boolean') { | |
66a7748d | 142 | return value |
5dc7c990 | 143 | } else if (isString(value) && (value.toLowerCase() === 'true' || value === '1')) { |
66a7748d | 144 | result = true |
9bf0ef23 | 145 | } else if (typeof value === 'number' && value === 1) { |
66a7748d | 146 | result = true |
e7aeea18 | 147 | } |
c37528f1 | 148 | } |
66a7748d JB |
149 | return result |
150 | } | |
9bf0ef23 JB |
151 | |
152 | export const getRandomFloat = (max = Number.MAX_VALUE, min = 0): number => { | |
153 | if (max < min) { | |
66a7748d | 154 | throw new RangeError('Invalid interval') |
9bf0ef23 JB |
155 | } |
156 | if (max - min === Infinity) { | |
66a7748d | 157 | throw new RangeError('Invalid interval') |
9bf0ef23 | 158 | } |
66a7748d JB |
159 | return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max - min) + min |
160 | } | |
9bf0ef23 JB |
161 | |
162 | export const getRandomInteger = (max = Constants.MAX_RANDOM_INTEGER, min = 0): number => { | |
66a7748d | 163 | max = Math.floor(max) |
5199f9fd | 164 | if (min !== 0) { |
66a7748d JB |
165 | min = Math.ceil(min) |
166 | return Math.floor(randomInt(min, max + 1)) | |
9bf0ef23 | 167 | } |
66a7748d JB |
168 | return Math.floor(randomInt(max + 1)) |
169 | } | |
9bf0ef23 JB |
170 | |
171 | /** | |
172 | * Rounds the given number to the given scale. | |
173 | * The rounding is done using the "round half away from zero" method. | |
174 | * | |
175 | * @param numberValue - The number to round. | |
176 | * @param scale - The scale to round to. | |
177 | * @returns The rounded number. | |
178 | */ | |
179 | export const roundTo = (numberValue: number, scale: number): number => { | |
66a7748d JB |
180 | const roundPower = Math.pow(10, scale) |
181 | return Math.round(numberValue * roundPower * (1 + Number.EPSILON)) / roundPower | |
182 | } | |
9bf0ef23 JB |
183 | |
184 | export const getRandomFloatRounded = (max = Number.MAX_VALUE, min = 0, scale = 2): number => { | |
5199f9fd | 185 | if (min !== 0) { |
66a7748d | 186 | return roundTo(getRandomFloat(max, min), scale) |
9bf0ef23 | 187 | } |
66a7748d JB |
188 | return roundTo(getRandomFloat(max), scale) |
189 | } | |
9bf0ef23 JB |
190 | |
191 | export const getRandomFloatFluctuatedRounded = ( | |
192 | staticValue: number, | |
193 | fluctuationPercent: number, | |
66a7748d | 194 | scale = 2 |
9bf0ef23 JB |
195 | ): number => { |
196 | if (fluctuationPercent < 0 || fluctuationPercent > 100) { | |
197 | throw new RangeError( | |
66a7748d JB |
198 | `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}` |
199 | ) | |
fe791818 | 200 | } |
9bf0ef23 | 201 | if (fluctuationPercent === 0) { |
66a7748d | 202 | return roundTo(staticValue, scale) |
9bf0ef23 | 203 | } |
66a7748d | 204 | const fluctuationRatio = fluctuationPercent / 100 |
9bf0ef23 JB |
205 | return getRandomFloatRounded( |
206 | staticValue * (1 + fluctuationRatio), | |
207 | staticValue * (1 - fluctuationRatio), | |
66a7748d JB |
208 | scale |
209 | ) | |
210 | } | |
9bf0ef23 | 211 | |
66a7748d | 212 | export const extractTimeSeriesValues = (timeSeries: TimestampedData[]): number[] => { |
a974c8e4 | 213 | return timeSeries.map(timeSeriesItem => timeSeriesItem.value) |
66a7748d | 214 | } |
da55bd34 | 215 | |
40615072 | 216 | export const clone = <T>(object: T): T => { |
3fad0dec | 217 | return structuredClone<T>(object) |
66a7748d | 218 | } |
9bf0ef23 | 219 | |
be0a4d4d JB |
220 | /** |
221 | * Detects whether the given value is an asynchronous function or not. | |
222 | * | |
223 | * @param fn - Unknown value. | |
224 | * @returns `true` if `fn` was an asynchronous function, otherwise `false`. | |
225 | * @internal | |
226 | */ | |
227 | export const isAsyncFunction = (fn: unknown): fn is (...args: unknown[]) => Promise<unknown> => { | |
228 | return typeof fn === 'function' && fn.constructor.name === 'AsyncFunction' | |
229 | } | |
230 | ||
bfcd3a87 JB |
231 | export const isObject = (value: unknown): value is object => { |
232 | return value != null && typeof value === 'object' && !Array.isArray(value) | |
233 | } | |
234 | ||
4ccf551d | 235 | export const isEmptyObject = (object: object): object is EmptyObject => { |
bfcd3a87 JB |
236 | if (object.constructor !== Object) { |
237 | return false | |
238 | } | |
239 | // Iterates over the keys of an object, if | |
240 | // any exist, return false. | |
241 | // eslint-disable-next-line no-unreachable-loop | |
242 | for (const _ in object) { | |
243 | return false | |
244 | } | |
245 | return true | |
246 | } | |
247 | ||
248 | export const hasOwnProp = (value: unknown, property: PropertyKey): boolean => { | |
249 | return isObject(value) && Object.hasOwn(value, property) | |
66a7748d | 250 | } |
9bf0ef23 JB |
251 | |
252 | export const isCFEnvironment = (): boolean => { | |
aa63c9b7 | 253 | return env.VCAP_APPLICATION != null |
66a7748d | 254 | } |
9bf0ef23 | 255 | |
5dc7c990 | 256 | const isString = (value: unknown): value is string => { |
66a7748d JB |
257 | return typeof value === 'string' |
258 | } | |
9bf0ef23 | 259 | |
bfcd3a87 | 260 | export const isEmptyString = (value: unknown): value is '' | undefined | null => { |
5dc7c990 | 261 | return value == null || (isString(value) && value.trim().length === 0) |
66a7748d | 262 | } |
9bf0ef23 | 263 | |
5dc7c990 JB |
264 | export const isNotEmptyString = (value: unknown): value is string => { |
265 | return isString(value) && value.trim().length > 0 | |
66a7748d | 266 | } |
9bf0ef23 | 267 | |
2c5c7443 | 268 | export const isEmptyArray = (value: unknown): value is [] => { |
bfcd3a87 | 269 | return Array.isArray(value) && value.length === 0 |
66a7748d | 270 | } |
9bf0ef23 | 271 | |
bfcd3a87 JB |
272 | export const isNotEmptyArray = (value: unknown): value is unknown[] => { |
273 | return Array.isArray(value) && value.length > 0 | |
66a7748d | 274 | } |
9bf0ef23 JB |
275 | |
276 | export const insertAt = (str: string, subStr: string, pos: number): string => | |
66a7748d | 277 | `${str.slice(0, pos)}${subStr}${str.slice(pos)}` |
9bf0ef23 JB |
278 | |
279 | /** | |
280 | * Computes the retry delay in milliseconds using an exponential backoff algorithm. | |
281 | * | |
282 | * @param retryNumber - the number of retries that have already been attempted | |
45abd3c6 | 283 | * @param delayFactor - the base delay factor in milliseconds |
9bf0ef23 JB |
284 | * @returns delay in milliseconds |
285 | */ | |
45abd3c6 | 286 | export const exponentialDelay = (retryNumber = 0, delayFactor = 100): number => { |
66a7748d JB |
287 | const delay = Math.pow(2, retryNumber) * delayFactor |
288 | const randomSum = delay * 0.2 * secureRandom() // 0-20% of the delay | |
289 | return delay + randomSum | |
290 | } | |
9bf0ef23 | 291 | |
9bf0ef23 JB |
292 | /** |
293 | * Generates a cryptographically secure random number in the [0,1[ range | |
294 | * | |
ab93b184 | 295 | * @returns A number in the [0,1[ range |
9bf0ef23 JB |
296 | */ |
297 | export const secureRandom = (): number => { | |
66a7748d JB |
298 | return getRandomValues(new Uint32Array(1))[0] / 0x100000000 |
299 | } | |
9bf0ef23 JB |
300 | |
301 | export const JSONStringifyWithMapSupport = ( | |
a66bbcfe JB |
302 | object: |
303 | | Record<string, unknown> | |
304 | | Array<Record<string, unknown>> | |
305 | | Map<unknown, unknown> | |
306 | | ProtocolResponse, | |
307 | space?: string | number | |
9bf0ef23 JB |
308 | ): string => { |
309 | return JSON.stringify( | |
bfcd3a87 | 310 | object, |
58ddf341 | 311 | (_, value: Record<string, unknown>) => { |
9bf0ef23 JB |
312 | if (value instanceof Map) { |
313 | return { | |
314 | dataType: 'Map', | |
66a7748d JB |
315 | value: [...value] |
316 | } | |
9bf0ef23 | 317 | } |
66a7748d | 318 | return value |
9bf0ef23 | 319 | }, |
66a7748d JB |
320 | space |
321 | ) | |
322 | } | |
9bf0ef23 JB |
323 | |
324 | /** | |
325 | * Converts websocket error code to human readable string message | |
326 | * | |
327 | * @param code - websocket error code | |
328 | * @returns human readable string message | |
329 | */ | |
330 | export const getWebSocketCloseEventStatusString = (code: number): string => { | |
331 | if (code >= 0 && code <= 999) { | |
66a7748d | 332 | return '(Unused)' |
9bf0ef23 JB |
333 | } else if (code >= 1016) { |
334 | if (code <= 1999) { | |
66a7748d | 335 | return '(For WebSocket standard)' |
9bf0ef23 | 336 | } else if (code <= 2999) { |
66a7748d | 337 | return '(For WebSocket extensions)' |
9bf0ef23 | 338 | } else if (code <= 3999) { |
66a7748d | 339 | return '(For libraries and frameworks)' |
9bf0ef23 | 340 | } else if (code <= 4999) { |
66a7748d | 341 | return '(For applications)' |
5e3cb728 | 342 | } |
5e3cb728 | 343 | } |
a37fc6dc | 344 | if ( |
5199f9fd JB |
345 | // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition |
346 | WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString] != null | |
a37fc6dc | 347 | ) { |
66a7748d | 348 | return WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString] |
9bf0ef23 | 349 | } |
66a7748d JB |
350 | return '(Unknown)' |
351 | } | |
80c58041 | 352 | |
991fb26b JB |
353 | export const isArraySorted = <T>(array: T[], compareFn: (a: T, b: T) => number): boolean => { |
354 | for (let index = 0; index < array.length - 1; ++index) { | |
355 | if (compareFn(array[index], array[index + 1]) > 0) { | |
66a7748d | 356 | return false |
80c58041 JB |
357 | } |
358 | } | |
66a7748d JB |
359 | return true |
360 | } | |
5f742aac JB |
361 | |
362 | // eslint-disable-next-line @typescript-eslint/no-explicit-any | |
363 | export const once = <T, A extends any[], R>( | |
364 | fn: (...args: A) => R, | |
66a7748d | 365 | context: T |
5f742aac | 366 | ): ((...args: A) => R) => { |
66a7748d | 367 | let result: R |
5f742aac | 368 | return (...args: A) => { |
5199f9fd | 369 | // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition |
66a7748d JB |
370 | if (fn != null) { |
371 | result = fn.apply<T, A, R>(context, args) | |
372 | ;(fn as unknown as undefined) = (context as unknown as undefined) = undefined | |
5f742aac | 373 | } |
66a7748d JB |
374 | return result |
375 | } | |
376 | } | |
5adf6ca4 JB |
377 | |
378 | export const min = (...args: number[]): number => | |
66a7748d | 379 | args.reduce((minimum, num) => (minimum < num ? minimum : num), Infinity) |
5adf6ca4 JB |
380 | |
381 | export const max = (...args: number[]): number => | |
66a7748d | 382 | args.reduce((maximum, num) => (maximum > num ? maximum : num), -Infinity) |
29dff95e JB |
383 | |
384 | export const throwErrorInNextTick = (error: Error): void => { | |
385 | nextTick(() => { | |
66a7748d JB |
386 | throw error |
387 | }) | |
388 | } |