shouldUseTaobao.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. const {
  2. chalk,
  3. execa,
  4. request,
  5. hasYarn
  6. } = require('@vue/cli-shared-utils')
  7. const inquirer = require('inquirer')
  8. const registries = require('./registries')
  9. const { loadOptions, saveOptions } = require('../options')
  10. async function ping (registry) {
  11. await request.get(`${registry}/vue-cli-version-marker/latest`)
  12. return registry
  13. }
  14. function removeSlash (url) {
  15. return url.replace(/\/$/, '')
  16. }
  17. let checked
  18. let result
  19. module.exports = async function shouldUseTaobao (command) {
  20. if (!command) {
  21. command = hasYarn() ? 'yarn' : 'npm'
  22. }
  23. // ensure this only gets called once.
  24. if (checked) return result
  25. checked = true
  26. // previously saved preference
  27. const saved = loadOptions().useTaobaoRegistry
  28. if (typeof saved === 'boolean') {
  29. return (result = saved)
  30. }
  31. const save = val => {
  32. result = val
  33. saveOptions({ useTaobaoRegistry: val })
  34. return val
  35. }
  36. let userCurrent
  37. try {
  38. userCurrent = (await execa(command, ['config', 'get', 'registry'])).stdout
  39. } catch (registryError) {
  40. try {
  41. // Yarn 2 uses `npmRegistryServer` instead of `registry`
  42. userCurrent = (await execa(command, ['config', 'get', 'npmRegistryServer'])).stdout
  43. } catch (npmRegistryServerError) {
  44. return save(false)
  45. }
  46. }
  47. const defaultRegistry = registries[command]
  48. if (removeSlash(userCurrent) !== removeSlash(defaultRegistry)) {
  49. // user has configured custom registry, respect that
  50. return save(false)
  51. }
  52. let faster
  53. try {
  54. faster = await Promise.race([
  55. ping(defaultRegistry),
  56. ping(registries.taobao)
  57. ])
  58. } catch (e) {
  59. return save(false)
  60. }
  61. if (faster !== registries.taobao) {
  62. // default is already faster
  63. return save(false)
  64. }
  65. if (process.env.VUE_CLI_API_MODE) {
  66. return save(true)
  67. }
  68. // ask and save preference
  69. const { useTaobaoRegistry } = await inquirer.prompt([
  70. {
  71. name: 'useTaobaoRegistry',
  72. type: 'confirm',
  73. message: chalk.yellow(
  74. ` Your connection to the default ${command} registry seems to be slow.\n` +
  75. ` Use ${chalk.cyan(registries.taobao)} for faster installation?`
  76. )
  77. }
  78. ])
  79. return save(useTaobaoRegistry)
  80. }