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