yarn.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { execShell } from '../../helpers/core-utils'
  2. import { logger } from '../../helpers/logger'
  3. import { isNpmPluginNameValid, isPluginVersionValid } from '../../helpers/custom-validators/plugins'
  4. import { CONFIG } from '../../initializers/config'
  5. import { outputJSON, pathExists } from 'fs-extra'
  6. import { join } from 'path'
  7. async function installNpmPlugin (npmName: string, version?: string) {
  8. // Security check
  9. checkNpmPluginNameOrThrow(npmName)
  10. if (version) checkPluginVersionOrThrow(version)
  11. let toInstall = npmName
  12. if (version) toInstall += `@${version}`
  13. const { stdout } = await execYarn('add ' + toInstall)
  14. logger.debug('Added a yarn package.', { yarnStdout: stdout })
  15. }
  16. async function installNpmPluginFromDisk (path: string) {
  17. await execYarn('add file:' + path)
  18. }
  19. async function removeNpmPlugin (name: string) {
  20. checkNpmPluginNameOrThrow(name)
  21. await execYarn('remove ' + name)
  22. }
  23. // ############################################################################
  24. export {
  25. installNpmPlugin,
  26. installNpmPluginFromDisk,
  27. removeNpmPlugin
  28. }
  29. // ############################################################################
  30. async function execYarn (command: string) {
  31. try {
  32. const pluginDirectory = CONFIG.STORAGE.PLUGINS_DIR
  33. const pluginPackageJSON = join(pluginDirectory, 'package.json')
  34. // Create empty package.json file if needed
  35. if (!await pathExists(pluginPackageJSON)) {
  36. await outputJSON(pluginPackageJSON, {})
  37. }
  38. return execShell(`yarn ${command}`, { cwd: pluginDirectory })
  39. } catch (result) {
  40. logger.error('Cannot exec yarn.', { command, err: result.err, stderr: result.stderr })
  41. throw result.err
  42. }
  43. }
  44. function checkNpmPluginNameOrThrow (name: string) {
  45. if (!isNpmPluginNameValid(name)) throw new Error('Invalid NPM plugin name to install')
  46. }
  47. function checkPluginVersionOrThrow (name: string) {
  48. if (!isPluginVersionValid(name)) throw new Error('Invalid NPM plugin version to install')
  49. }