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