-
Notifications
You must be signed in to change notification settings - Fork 366
/
command-helpers.ts
302 lines (262 loc) · 9.85 KB
/
command-helpers.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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
import { once } from 'events'
import os from 'os'
import process from 'process'
import { format, inspect } from 'util'
import { Chalk } from 'chalk'
import chokidar from 'chokidar'
import decache from 'decache'
import WSL from 'is-wsl'
import debounce from 'lodash/debounce.js'
import terminalLink from 'terminal-link'
import { clearSpinner, startSpinner } from '../lib/spinner.js'
import getGlobalConfig from './get-global-config.js'
import getPackageJson from './get-package-json.js'
import { reportError } from './telemetry/report-error.js'
/** The parsed process argv without the binary only arguments and flags */
const argv = process.argv.slice(2)
/**
* Chalk instance for CLI that can be initialized with no colors mode
* needed for json outputs where we don't want to have colors
* @param {boolean} noColors - disable chalk colors
* @return {import('chalk').ChalkInstance} - default or custom chalk instance
*/
// @ts-expect-error TS(7006) FIXME: Parameter 'noColors' implicitly has an 'any' type.
const safeChalk = function (noColors) {
if (noColors) {
const colorlessChalk = new Chalk({ level: 0 })
return colorlessChalk
}
return new Chalk()
}
export const chalk = safeChalk(argv.includes('--json'))
/**
* Adds the filler to the start of the string
* @param {string} str
* @param {number} count
* @param {string} [filler]
* @returns {string}
*/
// @ts-expect-error TS(7006) FIXME: Parameter 'str' implicitly has an 'any' type.
export const padLeft = (str, count, filler = ' ') => str.padStart(str.length + count, filler)
const platform = WSL ? 'wsl' : os.platform()
const arch = os.arch() === 'ia32' ? 'x86' : os.arch()
const { name, version: packageVersion } = await getPackageJson()
export const version = packageVersion
export const USER_AGENT = `${name}/${version} ${platform}-${arch} node-${process.version}`
/** A list of base command flags that needs to be sorted down on documentation and on help pages */
const BASE_FLAGS = new Set(['--debug', '--httpProxy', '--httpProxyCertificateFilename'])
export const NETLIFY_CYAN = chalk.rgb(40, 180, 170)
export const NETLIFYDEV = `${chalk.greenBright('◈')} ${NETLIFY_CYAN('Netlify Dev')} ${chalk.greenBright('◈')}`
export const NETLIFYDEVLOG = `${chalk.greenBright('◈')}`
export const NETLIFYDEVWARN = `${chalk.yellowBright('◈')}`
export const NETLIFYDEVERR = `${chalk.redBright('◈')}`
export const BANG = process.platform === 'win32' ? '»' : '›'
/**
* Sorts two options so that the base flags are at the bottom of the list
* @param {import('commander').Option} optionA
* @param {import('commander').Option} optionB
* @returns {number}
* @example
* options.sort(sortOptions)
*/
// @ts-expect-error TS(7006) FIXME: Parameter 'optionA' implicitly has an 'any' type.
export const sortOptions = (optionA, optionB) => {
// base flags should be always at the bottom
if (BASE_FLAGS.has(optionA.long) || BASE_FLAGS.has(optionB.long)) {
return -1
}
return optionA.long.localeCompare(optionB.long)
}
// Poll Token timeout 5 Minutes
const TOKEN_TIMEOUT = 3e5
/**
*
* @param {object} config
* @param {import('netlify').NetlifyAPI} config.api
* @param {object} config.ticket
* @returns
*/
// @ts-expect-error TS(7031) FIXME: Binding element 'api' implicitly has an 'any' type... Remove this comment to see the full error message
export const pollForToken = async ({ api, ticket }) => {
const spinner = startSpinner({ text: 'Waiting for authorization...' })
try {
const accessToken = await api.getAccessToken(ticket, { timeout: TOKEN_TIMEOUT })
if (!accessToken) {
error('Could not retrieve access token')
}
return accessToken
} catch (error_) {
// @ts-expect-error TS(2571) FIXME: Object is of type 'unknown'.
if (error_.name === 'TimeoutError') {
error(
`Timed out waiting for authorization. If you do not have a ${chalk.bold.greenBright(
'Netlify',
)} account, please create one at ${chalk.magenta(
'https://app.netlify.com/signup',
)}, then run ${chalk.cyanBright('netlify login')} again.`,
)
} else {
// @ts-expect-error TS(2345) FIXME: Argument of type 'unknown' is not assignable to pa... Remove this comment to see the full error message
error(error_)
}
} finally {
clearSpinner({ spinner })
}
}
/**
* Get a netlify token
* @param {string} [tokenFromOptions] optional token from the provided --auth options
* @returns {Promise<[null|string, 'flag' | 'env' |'config' |'not found']>}
*/
// @ts-expect-error TS(7006) FIXME: Parameter 'tokenFromOptions' implicitly has an 'an... Remove this comment to see the full error message
export const getToken = async (tokenFromOptions) => {
// 1. First honor command flag --auth
if (tokenFromOptions) {
return [tokenFromOptions, 'flag']
}
// 2. then Check ENV var
const { NETLIFY_AUTH_TOKEN } = process.env
if (NETLIFY_AUTH_TOKEN && NETLIFY_AUTH_TOKEN !== 'null') {
return [NETLIFY_AUTH_TOKEN, 'env']
}
// 3. If no env var use global user setting
const globalConfig = await getGlobalConfig()
const userId = globalConfig.get('userId')
const tokenFromConfig = globalConfig.get(`users.${userId}.auth.token`)
if (tokenFromConfig) {
return [tokenFromConfig, 'config']
}
return [null, 'not found']
}
// 'api' command uses JSON output by default
// 'functions:invoke' need to return the data from the function as is
const isDefaultJson = () => argv[0] === 'functions:invoke' || (argv[0] === 'api' && !argv.includes('--list'))
/**
* logs a json message
*/
export const logJson = (message: unknown = '') => {
if (argv.includes('--json') || isDefaultJson()) {
process.stdout.write(JSON.stringify(message, null, 2))
}
}
// @ts-expect-error TS(7019) FIXME: Rest parameter 'args' implicitly has an 'any[]' ty... Remove this comment to see the full error message
export const log = (message = '', ...args) => {
// If --silent or --json flag passed disable logger
if (argv.includes('--json') || argv.includes('--silent') || isDefaultJson()) {
return
}
message = typeof message === 'string' ? message : inspect(message)
process.stdout.write(`${format(message, ...args)}\n`)
}
// @ts-expect-error TS(7019) FIXME: Rest parameter 'args' implicitly has an 'any[]' ty... Remove this comment to see the full error message
export const logPadded = (message = '', ...args) => {
log('')
log(message, ...args)
log('')
}
/**
* logs a warning message
* @param {string} message
*/
export const warn = (message = '') => {
const bang = chalk.yellow(BANG)
log(` ${bang} Warning: ${message}`)
}
/** Throws an error or logs it */
export const error = (message: Error | string = '', options: { exit?: boolean } = {}) => {
const err =
message instanceof Error
? message
: // eslint-disable-next-line unicorn/no-nested-ternary
typeof message === 'string'
? new Error(message)
: { message, stack: undefined, name: 'Error' }
if (options.exit === false) {
const bang = chalk.red(BANG)
if (process.env.DEBUG) {
process.stderr.write(` ${bang} Warning: ${err.stack?.split('\n').join(`\n ${bang} `)}\n`)
} else {
process.stderr.write(` ${bang} ${chalk.red(`${err.name}:`)} ${err.message}\n`)
}
} else {
reportError(err, { severity: 'error' })
throw err
}
}
export const exit = (code = 0) => {
process.exit(code)
}
/**
* When `build.publish` is not set by the user, the CLI behavior differs in
* several ways. It detects it by checking if `build.publish` is `undefined`.
* However, `@netlify/config` adds a default value to `build.publish`.
* This removes 'publish' and 'publishOrigin' in this case.
* @param {*} config
*/
// @ts-expect-error TS(7006) FIXME: Parameter 'config' implicitly has an 'any' type.
export const normalizeConfig = (config) => {
// Unused var here is in order to omit 'publish' from build config
const { publish, publishOrigin, ...build } = config.build
return publishOrigin === 'default' ? { ...config, build } : config
}
const DEBOUNCE_WAIT = 100
interface WatchDebouncedOptions {
depth?: number
ignored?: (string | RegExp)[]
onAdd?: (paths: string[]) => void
onChange?: (paths: string[]) => void
onUnlink?: (paths: string[]) => void
}
/**
* Adds a file watcher to a path or set of paths and debounces the events.
*/
export const watchDebounced = async (
target: string | string[],
{ depth, ignored = [], onAdd = noOp, onChange = noOp, onUnlink = noOp }: WatchDebouncedOptions,
) => {
const baseIgnores = [/\/(node_modules|.git)\//]
const watcher = chokidar.watch(target, { depth, ignored: [...baseIgnores, ...ignored], ignoreInitial: true })
await once(watcher, 'ready')
let onChangeQueue: string[] = []
let onAddQueue: string[] = []
let onUnlinkQueue: string[] = []
const debouncedOnChange = debounce(() => {
onChange(onChangeQueue)
onChangeQueue = []
}, DEBOUNCE_WAIT)
const debouncedOnAdd = debounce(() => {
onAdd(onAddQueue)
onAddQueue = []
}, DEBOUNCE_WAIT)
const debouncedOnUnlink = debounce(() => {
onUnlink(onUnlinkQueue)
onUnlinkQueue = []
}, DEBOUNCE_WAIT)
watcher
.on('change', (path) => {
// @ts-expect-error
decache(path)
onChangeQueue.push(path)
debouncedOnChange()
})
.on('unlink', (path) => {
// @ts-expect-error
decache(path)
onUnlinkQueue.push(path)
debouncedOnUnlink()
})
.on('add', (path) => {
// @ts-expect-error
decache(path)
onAddQueue.push(path)
debouncedOnAdd()
})
return watcher
}
// @ts-expect-error TS(7006) FIXME: Parameter 'text' implicitly has an 'any' type.
export const getTerminalLink = (text, url) => terminalLink(text, url, { fallback: () => `${text} (${url})` })
export const isNodeError = (err: unknown): err is NodeJS.ErrnoException => error instanceof Error
export const nonNullable = <T>(value: T): value is NonNullable<T> => value !== null && value !== undefined
export const noOp = () => {
// no-op
}