-
Notifications
You must be signed in to change notification settings - Fork 452
Expand file tree
/
Copy pathmain.ts
More file actions
309 lines (274 loc) · 11 KB
/
main.ts
File metadata and controls
309 lines (274 loc) · 11 KB
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
303
304
305
306
307
308
309
import process from 'process'
import { Option, CommanderError } from 'commander'
import envinfo from 'envinfo'
import { closest } from 'fastest-levenshtein'
import inquirer from 'inquirer'
import { getGlobalConfigStore } from '@netlify/dev-utils'
import {
BANG,
chalk,
logAndThrowError,
exit,
log,
NETLIFY_CYAN,
USER_AGENT,
warn,
logError,
} from '../utils/command-helpers.js'
import execa from '../utils/execa.js'
import getCLIPackageJson from '../utils/get-cli-package-json.js'
import { didEnableCompileCache } from '../utils/nodejs-compile-cache.js'
import { handleOptionError, isOptionError } from '../utils/command-error-handler.js'
import { isInteractive } from '../utils/scripted-commands.js'
import { track, reportError } from '../utils/telemetry/index.js'
import { createAgentsCommand } from './agents/index.js'
import { createApiCommand } from './api/index.js'
import BaseCommand from './base-command.js'
import { createClaimCommand } from './claim/index.js'
import { createBlobsCommand } from './blobs/blobs.js'
import { createBuildCommand } from './build/index.js'
import { createCloneCommand } from './clone/index.js'
import { createCreateCommand } from './create/index.js'
import { createCompletionCommand } from './completion/index.js'
import { createDeployCommand } from './deploy/index.js'
import { createDevCommand } from './dev/index.js'
import { createDevExecCommand } from './dev-exec/index.js'
import { createEnvCommand } from './env/index.js'
import { createFunctionsCommand } from './functions/index.js'
import { createInitCommand } from './init/index.js'
import { createLinkCommand } from './link/index.js'
import { createLoginCommand } from './login/index.js'
import { createLogoutCommand } from './logout/index.js'
import { createLogsCommand } from './logs/index.js'
import { createOpenCommand } from './open/index.js'
import { createRecipesCommand } from './recipes/index.js'
import { createServeCommand } from './serve/index.js'
import { createSitesCommand } from './sites/index.js'
import { createStatusCommand } from './status/index.js'
import { createSwitchCommand } from './switch/index.js'
import { createTeamsCommand } from './teams/index.js'
import { AddressInUseError } from './types.js'
import { createUnlinkCommand } from './unlink/index.js'
import { createWatchCommand } from './watch/index.js'
import terminalLink from 'terminal-link'
import { createDatabaseCommand } from './database/index.js'
const SUGGESTION_TIMEOUT = 1e4
// These commands run with the --force flag in non-interactive and CI environments
export const CI_FORCED_COMMANDS = {
'env:set': { options: '--force', description: 'Bypasses prompts & Force the command to run.' },
'env:unset': { options: '--force', description: 'Bypasses prompts & Force the command to run.' },
'env:clone': { options: '--force', description: 'Bypasses prompts & Force the command to run.' },
'blobs:set': { options: '--force', description: 'Bypasses prompts & Force the command to run.' },
'blobs:delete': { options: '--force', description: 'Bypasses prompts & Force the command to run.' },
init: {
options: '--force',
description: 'Reinitialize CI hooks if the linked project is already configured to use CI',
},
'sites:delete': { options: '-f, --force', description: 'Delete without prompting (useful for CI).' },
}
process.on('uncaughtException', async (err: AddressInUseError | Error) => {
if ('code' in err && err.code === 'EADDRINUSE') {
logError(
`${chalk.red(`Port ${err.port} is already in use`)}\n\n` +
`Your serverless functions might be initializing a server\n` +
`to listen on specific port without properly closing it.\n\n` +
`This behavior is generally not advised\n` +
`To resolve this issue, try the following:\n` +
`1. If you NEED your serverless function to listen on a specific port,\n` +
`use a randomly assigned port as we do not officially support this.\n` +
`2. Review your serverless functions for lingering server connections, close them\n` +
`3. Check if any other applications are using port ${err.port}\n`,
)
} else {
logError(
`${chalk.red(
'Netlify CLI has terminated unexpectedly.',
)}\n\nPlease report this problem with reproduction steps at ${chalk.underline(
'https://ntl.fyi/cli-error',
)} including the error details below.\n`,
)
const systemInfo = await getSystemInfo()
console.log(chalk.dim(err.stack || err))
console.log(chalk.dim(systemInfo))
reportError(err, { severity: 'error' })
}
process.exit(1)
})
const pkg = await getCLIPackageJson()
const getSystemInfo = () =>
envinfo.run({
System: ['OS', 'CPU'],
Binaries: ['Node', 'Yarn', 'npm'],
Browsers: ['Chrome', 'Edge', 'Firefox', 'Safari'],
npmGlobalPackages: ['netlify-cli'],
})
const getVersionPage = async () => {
const data = await getSystemInfo()
return `
────────────────────┐
Environment Info │
────────────────────┘
${data}
${USER_AGENT}
`
}
/**
* The main CLI command without any command (root action)
* @param {import('commander').OptionValues} options
* @param {import('./base-command.js').default} command
*/
// @ts-expect-error TS(7006) FIXME: Parameter 'options' implicitly has an 'any' type.
const mainCommand = async function (options, command) {
const globalConfig = await getGlobalConfigStore()
if (options.telemetryDisable) {
globalConfig.set('telemetryDisabled', true)
console.log('Netlify telemetry has been disabled')
console.log('You can re-enable it anytime with the --telemetry-enable flag')
exit()
}
if (options.telemetryEnable) {
globalConfig.set('telemetryDisabled', false)
console.log('Netlify telemetry has been enabled')
console.log('You can disable it anytime with the --telemetry-disable flag')
await track('user_telemetryEnabled')
exit()
}
if (command.args[0] === 'version' || options.version) {
if (options.verbose) {
const versionPage = await getVersionPage()
log(versionPage)
}
log(USER_AGENT)
exit()
}
// if no command show help
if (command.args.length === 0) {
command.help()
}
if (command.args[0] === 'help') {
if (command.args[1]) {
// @ts-expect-error TS(7006) FIXME: Parameter 'cmd' implicitly has an 'any' type.
const subCommand = command.commands.find((cmd) => cmd.name() === command.args[1])
if (!subCommand) {
return logAndThrowError(`command ${command.args[1]} not found`)
}
subCommand.help()
}
command.help()
}
warn(`${chalk.yellow(command.args[0])} is not a ${command.name()} command.`)
// @ts-expect-error TS(7006) FIXME: Parameter 'cmd' implicitly has an 'any' type.
const allCommands = command.commands.map((cmd) => cmd.name())
const suggestion = closest(command.args[0], allCommands)
// In non-interactive environments (CI/CD, scripts), show the suggestion
// without prompting, and display full help for available commands
if (!isInteractive()) {
log(`\nDid you mean ${chalk.blue(suggestion)}?`)
log()
command.outputHelp({ error: true })
log()
return logAndThrowError(`Run ${NETLIFY_CYAN(`${command.name()} help`)} for a list of available commands.`)
}
const applySuggestion = await new Promise((resolve) => {
const prompt = inquirer.prompt({
type: 'confirm',
name: 'suggestion',
message: `Did you mean ${chalk.blue(suggestion)}`,
default: false,
})
setTimeout(() => {
// @ts-expect-error TS(2445) FIXME: Property 'close' is protected and only accessible ... Remove this comment to see the full error message
prompt.ui.close()
resolve(false)
}, SUGGESTION_TIMEOUT)
prompt.then((value) => {
resolve(value.suggestion)
})
})
// create new log line
log()
if (!applySuggestion) {
return logAndThrowError(`Run ${NETLIFY_CYAN(`${command.name()} help`)} for a list of available commands.`)
}
await execa(process.argv[0], [process.argv[1], suggestion], { stdio: 'inherit' })
}
/**
* Creates the `netlify-cli` command
*/
export const createMainCommand = (): BaseCommand => {
const program = new BaseCommand('netlify')
// register all the commands
createApiCommand(program)
createBlobsCommand(program)
createBuildCommand(program)
createClaimCommand(program)
createCompletionCommand(program)
createDeployCommand(program)
createDevExecCommand(program)
createDevCommand(program)
createEnvCommand(program)
createFunctionsCommand(program)
createRecipesCommand(program)
createInitCommand(program)
createCloneCommand(program)
createCreateCommand(program)
createLinkCommand(program)
createLoginCommand(program)
createLogoutCommand(program)
createOpenCommand(program)
createServeCommand(program)
createSitesCommand(program)
createStatusCommand(program)
createSwitchCommand(program)
createTeamsCommand(program)
createUnlinkCommand(program)
createWatchCommand(program)
createLogsCommand(program)
createDatabaseCommand(program)
createAgentsCommand(program)
program.setAnalyticsPayload({ didEnableCompileCache })
program
.version(USER_AGENT, '-V')
.showSuggestionAfterError(true)
.option('--telemetry-disable', 'Disable telemetry')
.option('--telemetry-enable', 'Enables telemetry')
// needed for custom version output as we display further environment information
// commanders version output is set to uppercase -V
.addOption(new Option('-v, --version').hideHelp())
.addOption(new Option('--verbose').hideHelp())
.noHelpOptions()
.addHelpText('before', () => NETLIFY_CYAN('\n⬥ Netlify CLI\n'))
.addHelpText('after', () => {
const cliDocsEntrypointUrl = 'https://developers.netlify.com/cli'
const docsUrl = 'https://docs.netlify.com'
const bugsUrl = pkg.bugs?.url ?? ''
return `To get started run: ${NETLIFY_CYAN('netlify login')}
To ask a human for credentials: ${NETLIFY_CYAN('netlify login --request <msg>')}
→ For more help with the CLI, visit ${NETLIFY_CYAN(
terminalLink(cliDocsEntrypointUrl, cliDocsEntrypointUrl, { fallback: false }),
)}
→ For help with Netlify, visit ${NETLIFY_CYAN(terminalLink(docsUrl, docsUrl, { fallback: false }))}
→ To report a CLI bug, visit ${NETLIFY_CYAN(terminalLink(bugsUrl, bugsUrl, { fallback: false }))}\n`
})
.configureOutput({
outputError: (message, write) => {
write(` ${chalk.red(BANG)} Error: ${message.replace(/^error:\s/g, '')}`)
write(` ${chalk.red(BANG)} See more help with --help\n`)
},
})
.exitOverride(function (this: BaseCommand, error: CommanderError) {
if (isOptionError(error)) {
handleOptionError(this)
}
throw error
})
.action(mainCommand)
program.commands.forEach((cmd) => {
const cmdName = cmd.name()
if (cmdName in CI_FORCED_COMMANDS) {
const { description, options } = CI_FORCED_COMMANDS[cmdName as keyof typeof CI_FORCED_COMMANDS]
cmd.option(options, description)
}
})
return program
}