-
-
Notifications
You must be signed in to change notification settings - Fork 173
/
Copy pathutil.ts
187 lines (154 loc) · 4.33 KB
/
util.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import debug from 'debug'
import colors from 'colors'
import { createInterface } from 'readline'
import { v4 as generateRandomUuid, v5 as generateUuidFromNamespace } from 'uuid'
import { uuid as getSystemUuid } from 'systeminformation'
import pushReceiverLogger from '@eneris/push-receiver/dist/utils/logger.js'
const debugLogger = debug('ring'),
uuidNamespace = 'e53ffdc0-e91d-4ce1-bec2-df939d94739d'
interface Logger {
logInfo: (...message: string[]) => void
logError: (message: string) => void
}
let logger: Logger = {
logInfo(message) {
debugLogger(message)
},
logError(message) {
debugLogger(colors.red(message))
},
},
debugEnabled = false
const timeouts = new Set<ReturnType<typeof setTimeout>>()
export function clearTimeouts() {
timeouts.forEach((timeout) => {
clearTimeout(timeout)
})
}
export function delay(milliseconds: number) {
return new Promise((resolve) => {
const timeout = setTimeout(() => {
timeouts.delete(timeout)
resolve(undefined)
}, milliseconds)
timeouts.add(timeout)
})
}
export function logDebug(message: any) {
if (debugEnabled) {
logger.logInfo(message)
}
}
export function logInfo(...message: any[]) {
logger.logInfo(...message)
}
export function logError(message: any) {
logger.logError(message)
}
export function useLogger(newLogger: Logger) {
logger = newLogger
}
export function enableDebug() {
debugEnabled = true
}
export function generateUuid(seed?: string) {
if (seed) {
return generateUuidFromNamespace(seed, uuidNamespace)
}
return generateRandomUuid()
}
export async function getHardwareId(systemId?: string) {
if (systemId) {
return generateUuid(systemId)
}
const timeoutValue = '-1',
{ os: id } = await Promise.race([
getSystemUuid(),
delay(5000).then(() => ({ os: timeoutValue })),
])
if (id === timeoutValue) {
logError(
'Request for system uuid timed out. Falling back to random session id',
)
return generateRandomUuid()
}
if (id === '-') {
// default value set by systeminformation if it can't find a real value
logError('Unable to get system uuid. Falling back to random session id')
return generateRandomUuid()
}
return generateUuid(id)
}
export async function requestInput(question: string) {
const lineReader = createInterface({
input: process.stdin,
output: process.stdout,
}),
answer = await new Promise<string>((resolve) => {
lineReader.question(question, resolve)
})
lineReader.close()
return answer.trim()
}
export function stringify(data: any) {
if (typeof data === 'string') {
return data
}
if (typeof data === 'object' && Buffer.isBuffer(data)) {
return data.toString()
}
return JSON.stringify(data) + ''
}
export function mapAsync<T, U>(
records: T[],
asyncMapper: (record: T) => Promise<U>,
): Promise<U[]> {
return Promise.all(records.map((record) => asyncMapper(record)))
}
export function randomInteger() {
return Math.floor(Math.random() * 99999999) + 100000
}
export function randomString(length: number) {
const uuid = generateUuid()
return uuid.replace(/-/g, '').substring(0, length).toLowerCase()
}
export type DeepPartial<T> = {
[K in keyof T]?: T[K] extends Array<infer U>
? Array<DeepPartial<U>>
: T[K] extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: DeepPartial<T[K]>
}
// Override push receiver logging to avoid ECONNRESET errors leaking
function logPushReceiver(...args: any) {
try {
if (args[0].toString().includes('ECONNRESET')) {
// don't log ECONNRESET errors
return
}
} catch (_) {
// proceed to log error
}
logDebug('[Push Receiver]')
logDebug(args[0])
}
const pushReceiverLoggerDefault =
pushReceiverLogger.default || pushReceiverLogger // fix for vitest
pushReceiverLoggerDefault.error = logPushReceiver
export function fromBase64(encodedInput: string) {
const buff = Buffer.from(encodedInput, 'base64')
return buff.toString('ascii')
}
export function toBase64(input: string) {
const buff = Buffer.from(input)
return buff.toString('base64')
}
export function buildSearchString(search: Record<string, any>) {
return (
'?' +
Object.entries(search)
.filter(([, value]) => value !== undefined && value !== null)
.map(([key, value]) => `${key}=${value}`)
.join('&')
)
}