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'
8 async function installNpmPlugin (name: string, version?: string) {
10 checkNpmPluginNameOrThrow(name)
11 if (version) checkPluginVersionOrThrow(version)
14 if (version) toInstall += `@${version}`
16 await execYarn('add ' + toInstall)
19 async function installNpmPluginFromDisk (path: string) {
20 await execYarn('add file:' + path)
23 async function removeNpmPlugin (name: string) {
24 checkNpmPluginNameOrThrow(name)
26 await execYarn('remove ' + name)
29 // ############################################################################
33 installNpmPluginFromDisk,
37 // ############################################################################
39 async function execYarn (command: string) {
41 const pluginDirectory = CONFIG.STORAGE.PLUGINS_DIR
42 const pluginPackageJSON = join(pluginDirectory, 'package.json')
44 // Create empty package.json file if needed
45 if (!await pathExists(pluginPackageJSON)) {
46 await outputJSON(pluginPackageJSON, {})
49 await execShell(`yarn ${command}`, { cwd: pluginDirectory })
51 logger.error('Cannot exec yarn.', { command, err: result.err, stderr: result.stderr })
57 function checkNpmPluginNameOrThrow (name: string) {
58 if (!isNpmPluginNameValid(name)) throw new Error('Invalid NPM plugin name to install')
61 function checkPluginVersionOrThrow (name: string) {
62 if (!isPluginVersionValid(name)) throw new Error('Invalid NPM plugin version to install')