Commit | Line | Data |
---|---|---|
fcda9151 | 1 | import { getRandomValues, randomBytes, randomUUID } from 'node:crypto' |
66a7748d | 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' | |
8a4f882a | 15 | import { is } from 'rambda' |
088ee3c1 | 16 | |
4ccf551d | 17 | import { |
276e05ae JB |
18 | type JsonType, |
19 | MapStringifyFormat, | |
4ccf551d JB |
20 | type TimestampedData, |
21 | WebSocketCloseEventStatusString | |
22 | } from '../types/index.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 | } |
87bcd3b4 | 94 | if (typeof value === 'string' || 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 |
87bcd3b4 | 114 | if (typeof value === 'string') { |
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 |
87bcd3b4 | 128 | if (typeof value === 'string') { |
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 |
87bcd3b4 | 143 | } else if (typeof value === 'string' && (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 | 161 | |
9bf0ef23 JB |
162 | /** |
163 | * Rounds the given number to the given scale. | |
164 | * The rounding is done using the "round half away from zero" method. | |
165 | * | |
166 | * @param numberValue - The number to round. | |
167 | * @param scale - The scale to round to. | |
168 | * @returns The rounded number. | |
169 | */ | |
170 | export const roundTo = (numberValue: number, scale: number): number => { | |
66a7748d JB |
171 | const roundPower = Math.pow(10, scale) |
172 | return Math.round(numberValue * roundPower * (1 + Number.EPSILON)) / roundPower | |
173 | } | |
9bf0ef23 JB |
174 | |
175 | export const getRandomFloatRounded = (max = Number.MAX_VALUE, min = 0, scale = 2): number => { | |
5199f9fd | 176 | if (min !== 0) { |
66a7748d | 177 | return roundTo(getRandomFloat(max, min), scale) |
9bf0ef23 | 178 | } |
66a7748d JB |
179 | return roundTo(getRandomFloat(max), scale) |
180 | } | |
9bf0ef23 JB |
181 | |
182 | export const getRandomFloatFluctuatedRounded = ( | |
183 | staticValue: number, | |
184 | fluctuationPercent: number, | |
66a7748d | 185 | scale = 2 |
9bf0ef23 JB |
186 | ): number => { |
187 | if (fluctuationPercent < 0 || fluctuationPercent > 100) { | |
188 | throw new RangeError( | |
66a7748d JB |
189 | `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}` |
190 | ) | |
fe791818 | 191 | } |
9bf0ef23 | 192 | if (fluctuationPercent === 0) { |
66a7748d | 193 | return roundTo(staticValue, scale) |
9bf0ef23 | 194 | } |
66a7748d | 195 | const fluctuationRatio = fluctuationPercent / 100 |
9bf0ef23 JB |
196 | return getRandomFloatRounded( |
197 | staticValue * (1 + fluctuationRatio), | |
198 | staticValue * (1 - fluctuationRatio), | |
66a7748d JB |
199 | scale |
200 | ) | |
201 | } | |
9bf0ef23 | 202 | |
66a7748d | 203 | export const extractTimeSeriesValues = (timeSeries: TimestampedData[]): number[] => { |
a974c8e4 | 204 | return timeSeries.map(timeSeriesItem => timeSeriesItem.value) |
66a7748d | 205 | } |
da55bd34 | 206 | |
40615072 | 207 | export const clone = <T>(object: T): T => { |
3fad0dec | 208 | return structuredClone<T>(object) |
66a7748d | 209 | } |
9bf0ef23 | 210 | |
be0a4d4d JB |
211 | /** |
212 | * Detects whether the given value is an asynchronous function or not. | |
213 | * | |
214 | * @param fn - Unknown value. | |
215 | * @returns `true` if `fn` was an asynchronous function, otherwise `false`. | |
216 | * @internal | |
217 | */ | |
218 | export const isAsyncFunction = (fn: unknown): fn is (...args: unknown[]) => Promise<unknown> => { | |
8a4f882a | 219 | return is(Function, fn) && fn.constructor.name === 'AsyncFunction' |
be0a4d4d JB |
220 | } |
221 | ||
bfcd3a87 | 222 | export const isObject = (value: unknown): value is object => { |
8a4f882a | 223 | return value != null && !Array.isArray(value) && is(Object, value) |
bfcd3a87 JB |
224 | } |
225 | ||
bfcd3a87 JB |
226 | export const hasOwnProp = (value: unknown, property: PropertyKey): boolean => { |
227 | return isObject(value) && Object.hasOwn(value, property) | |
66a7748d | 228 | } |
9bf0ef23 JB |
229 | |
230 | export const isCFEnvironment = (): boolean => { | |
aa63c9b7 | 231 | return env.VCAP_APPLICATION != null |
66a7748d | 232 | } |
9bf0ef23 | 233 | |
5dc7c990 | 234 | export const isNotEmptyString = (value: unknown): value is string => { |
87bcd3b4 | 235 | return typeof value === 'string' && value.trim().length > 0 |
66a7748d | 236 | } |
9bf0ef23 | 237 | |
bfcd3a87 JB |
238 | export const isNotEmptyArray = (value: unknown): value is unknown[] => { |
239 | return Array.isArray(value) && value.length > 0 | |
66a7748d | 240 | } |
9bf0ef23 JB |
241 | |
242 | export const insertAt = (str: string, subStr: string, pos: number): string => | |
66a7748d | 243 | `${str.slice(0, pos)}${subStr}${str.slice(pos)}` |
9bf0ef23 JB |
244 | |
245 | /** | |
246 | * Computes the retry delay in milliseconds using an exponential backoff algorithm. | |
247 | * | |
248 | * @param retryNumber - the number of retries that have already been attempted | |
45abd3c6 | 249 | * @param delayFactor - the base delay factor in milliseconds |
9bf0ef23 JB |
250 | * @returns delay in milliseconds |
251 | */ | |
45abd3c6 | 252 | export const exponentialDelay = (retryNumber = 0, delayFactor = 100): number => { |
66a7748d JB |
253 | const delay = Math.pow(2, retryNumber) * delayFactor |
254 | const randomSum = delay * 0.2 * secureRandom() // 0-20% of the delay | |
255 | return delay + randomSum | |
256 | } | |
9bf0ef23 | 257 | |
9bf0ef23 JB |
258 | /** |
259 | * Generates a cryptographically secure random number in the [0,1[ range | |
260 | * | |
ab93b184 | 261 | * @returns A number in the [0,1[ range |
9bf0ef23 JB |
262 | */ |
263 | export const secureRandom = (): number => { | |
66a7748d JB |
264 | return getRandomValues(new Uint32Array(1))[0] / 0x100000000 |
265 | } | |
9bf0ef23 | 266 | |
276e05ae | 267 | export const JSONStringify = < |
28f384aa JB |
268 | T extends |
269 | | JsonType | |
270 | | Array<Record<string, unknown>> | |
271 | | Set<Record<string, unknown>> | |
272 | | Map<string, Record<string, unknown>> | |
276e05ae JB |
273 | >( |
274 | object: T, | |
275 | space?: string | number, | |
276 | mapFormat?: MapStringifyFormat | |
277 | ): string => { | |
9bf0ef23 | 278 | return JSON.stringify( |
bfcd3a87 | 279 | object, |
58ddf341 | 280 | (_, value: Record<string, unknown>) => { |
8a4f882a | 281 | if (is(Map, value)) { |
276e05ae JB |
282 | switch (mapFormat) { |
283 | case MapStringifyFormat.object: | |
61877a2e | 284 | return { ...Object.fromEntries<Map<string, Record<string, unknown>>>(value.entries()) } |
276e05ae JB |
285 | case MapStringifyFormat.array: |
286 | default: | |
287 | return [...value] | |
66a7748d | 288 | } |
8a4f882a | 289 | } else if (is(Set, value)) { |
61877a2e | 290 | return [...value] as JsonType[] |
9bf0ef23 | 291 | } |
66a7748d | 292 | return value |
9bf0ef23 | 293 | }, |
66a7748d JB |
294 | space |
295 | ) | |
296 | } | |
9bf0ef23 JB |
297 | |
298 | /** | |
299 | * Converts websocket error code to human readable string message | |
300 | * | |
301 | * @param code - websocket error code | |
302 | * @returns human readable string message | |
303 | */ | |
304 | export const getWebSocketCloseEventStatusString = (code: number): string => { | |
305 | if (code >= 0 && code <= 999) { | |
66a7748d | 306 | return '(Unused)' |
9bf0ef23 JB |
307 | } else if (code >= 1016) { |
308 | if (code <= 1999) { | |
66a7748d | 309 | return '(For WebSocket standard)' |
9bf0ef23 | 310 | } else if (code <= 2999) { |
66a7748d | 311 | return '(For WebSocket extensions)' |
9bf0ef23 | 312 | } else if (code <= 3999) { |
66a7748d | 313 | return '(For libraries and frameworks)' |
9bf0ef23 | 314 | } else if (code <= 4999) { |
66a7748d | 315 | return '(For applications)' |
5e3cb728 | 316 | } |
5e3cb728 | 317 | } |
a37fc6dc | 318 | if ( |
5199f9fd JB |
319 | // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition |
320 | WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString] != null | |
a37fc6dc | 321 | ) { |
66a7748d | 322 | return WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString] |
9bf0ef23 | 323 | } |
66a7748d JB |
324 | return '(Unknown)' |
325 | } | |
80c58041 | 326 | |
991fb26b JB |
327 | export const isArraySorted = <T>(array: T[], compareFn: (a: T, b: T) => number): boolean => { |
328 | for (let index = 0; index < array.length - 1; ++index) { | |
329 | if (compareFn(array[index], array[index + 1]) > 0) { | |
66a7748d | 330 | return false |
80c58041 JB |
331 | } |
332 | } | |
66a7748d JB |
333 | return true |
334 | } | |
5f742aac | 335 | |
29dff95e JB |
336 | export const throwErrorInNextTick = (error: Error): void => { |
337 | nextTick(() => { | |
66a7748d JB |
338 | throw error |
339 | }) | |
340 | } |