@commonshost/cli
Version:
Commons Host command line interface
81 lines (75 loc) • 2.29 kB
JavaScript
const { URL } = require('url')
const {
domainToASCII: toASCII,
domainToUnicode: toUnicode
} = require('url')
const { prompt } = require('inquirer')
const { animals } = require('human-readable-ids/lists')
const { loadingCredentials } = require('../helpers/loadingCredentials')
const { fetch } = require('../helpers/fetch')
const { parseError } = require('../helpers/parseError')
const chalk = require('chalk')
module.exports.command = ['delete']
module.exports.aliases = ['rm', 'destroy', 'del', 'unpublish']
module.exports.desc = 'Stop hosting a site'
module.exports.builder = {
domain: {
type: 'string',
describe: 'Site URL or hostname'
},
confirm: {
type: 'boolean',
describe: 'Override manual safety procedure'
}
}
module.exports.handler = async function handler (argv) {
const { accessToken, origin } = await loadingCredentials()
const questions = []
const animal = animals[Math.floor(Math.random() * animals.length)]
if (typeof argv.domain !== 'string') {
questions.push({
name: 'domain',
message: 'Site URL or hostname:'
})
}
if (argv.confirm !== true) {
questions.push({
name: 'confirmation',
message: `To confirm, type "${chalk.bold(animal)}":`
})
}
if (questions.length > 0) {
console.log(chalk.bgRed.white('🚨 Danger Zone 🚨'))
console.log(`Press ${chalk.bold('Ctrl+C')} to cancel. Deleting a site can not be undone.`)
const answers = await prompt(questions)
if ('domain' in answers) {
argv.domain = answers.domain
}
if (animal === answers.confirmation) {
argv.confirm = true
}
}
let domain
try {
domain = new URL(argv.domain).hostname
} catch (error) {
domain = toASCII(argv.domain)
}
if (domain === undefined || domain === '') {
throw new Error('Invalid domain')
}
if (argv.confirm !== true) {
throw new Error('Confirmation failed')
}
const url = `${origin}/v2/sites/${domain}`
const options = {
method: 'DELETE',
headers: {
authorization: `Bearer ${accessToken}`
}
}
const response = await fetch(url, options)
if (!response.ok) throw await parseError(response)
const location = `https://${toUnicode(domain)}`
console.log(`💥 Deleted: ${chalk.underline.red(location)}`)
}