aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/lib/plugins/yarn.ts
blob: 9cf6ec9e90e53be6f281c312130f1ab7654109bb (plain) (blame)
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
import { outputJSON, pathExists } from 'fs-extra'
import { join } from 'path'
import { execShell } from '../../helpers/core-utils'
import { isNpmPluginNameValid, isPluginStableOrUnstableVersionValid } from '../../helpers/custom-validators/plugins'
import { logger } from '../../helpers/logger'
import { CONFIG } from '../../initializers/config'
import { getLatestPluginVersion } from './plugin-index'

async function installNpmPlugin (npmName: string, versionArg?: string) {
  // Security check
  checkNpmPluginNameOrThrow(npmName)
  if (versionArg) checkPluginVersionOrThrow(versionArg)

  const version = versionArg || await getLatestPluginVersion(npmName)

  let toInstall = npmName
  if (version) toInstall += `@${version}`

  const { stdout } = await execYarn('add ' + toInstall)

  logger.debug('Added a yarn package.', { yarnStdout: stdout })
}

async function installNpmPluginFromDisk (path: string) {
  await execYarn('add file:' + path)
}

async function removeNpmPlugin (name: string) {
  checkNpmPluginNameOrThrow(name)

  await execYarn('remove ' + name)
}

async function rebuildNativePlugins () {
  await execYarn('install --pure-lockfile')
}

// ############################################################################

export {
  installNpmPlugin,
  installNpmPluginFromDisk,
  rebuildNativePlugins,
  removeNpmPlugin
}

// ############################################################################

async function execYarn (command: string) {
  try {
    const pluginDirectory = CONFIG.STORAGE.PLUGINS_DIR
    const pluginPackageJSON = join(pluginDirectory, 'package.json')

    // Create empty package.json file if needed
    if (!await pathExists(pluginPackageJSON)) {
      await outputJSON(pluginPackageJSON, {})
    }

    return execShell(`yarn ${command}`, { cwd: pluginDirectory })
  } catch (result) {
    logger.error('Cannot exec yarn.', { command, err: result.err, stderr: result.stderr })

    throw result.err
  }
}

function checkNpmPluginNameOrThrow (name: string) {
  if (!isNpmPluginNameValid(name)) throw new Error('Invalid NPM plugin name to install')
}

function checkPluginVersionOrThrow (name: string) {
  if (!isPluginStableOrUnstableVersionValid(name)) throw new Error('Invalid NPM plugin version to install')
}