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