@zowe/imperative
Version:
framework for building configurable CLIs
189 lines • 7.51 kB
JavaScript
;
/*
* This program and the accompanying materials are made available under the terms of the
* Eclipse Public License v2.0 which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v20.html
*
* SPDX-License-Identifier: EPL-2.0
*
* Copyright Contributors to the Zowe Project.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.NpmRegistryUtils = void 0;
exports.findNpmOnPath = findNpmOnPath;
exports.installPackages = installPackages;
exports.getPackageInfo = getPackageInfo;
const PMFConstants_1 = require("./PMFConstants");
const path = require("path");
const which = require("which");
const jsonfile_1 = require("jsonfile");
const npmPackageArg = require("npm-package-arg");
const utilities_1 = require("../../../../utilities");
const logger_1 = require("../../../../logger");
const error_1 = require("../../../../error");
const npmCmd = findNpmOnPath();
/**
* Common function that returns npm command as a string.
*
* @return {string} command with npm path
*/
function findNpmOnPath() {
return which.sync("npm");
}
/**
* Common function that installs a npm package using the local npm cli.
* @param {string} prefix Path where to install npm the npm package.
*
* @param {string} registry The npm registry to install from.
*
* @param {string} npmPackage The name of package to install.
*
* @return {string} command response
*
*/
function installPackages(npmPackage, npmArgs, verbose = false) {
var _a;
const pipe = ["pipe", "pipe", "pipe"];
const args = ["install", npmPackage, "-g", "--legacy-peer-deps"];
if (verbose) {
const logLevel = ((logger) => {
switch (logger.level) {
case "TRACE": return "silly";
case "DEBUG": return "verbose";
default: return "info";
}
})(logger_1.Logger.getAppLogger());
args.push(`--loglevel=${logLevel}`, "--foreground-scripts");
}
for (const [k, v] of Object.entries(npmArgs)) {
if (v != null) {
// If npm arg starts with @ like @zowe:registry, must use = as separator
args.push(...k.startsWith("@") ? [`--${k}=${v}`] : [`--${k}`, v]);
}
}
let execOutput = "";
const daemonStream = (_a = utilities_1.ImperativeConfig.instance.daemonContext) === null || _a === void 0 ? void 0 : _a.stream;
try {
if (verbose && daemonStream == null) {
utilities_1.ExecUtils.spawnWithInheritedStdio(npmCmd, args, {
cwd: PMFConstants_1.PMFConstants.instance.PMF_ROOT,
});
}
else {
execOutput = utilities_1.ExecUtils.spawnAndGetOutput(npmCmd, args, {
cwd: PMFConstants_1.PMFConstants.instance.PMF_ROOT,
stdio: pipe
}).toString();
if (verbose && daemonStream != null) {
daemonStream.write(utilities_1.DaemonRequest.create({ stdout: execOutput }));
}
}
}
catch (error) {
if (daemonStream != null) {
daemonStream.write(utilities_1.DaemonRequest.create({ stderr: error.message }));
}
else {
process.stderr.write(error.message);
}
}
return execOutput;
}
/**
* Fetch name and version of NPM package that was installed
* @param pkgSpec The package name as specified on NPM install
*/
function getPackageInfo(pkgSpec) {
const pkgInfo = npmPackageArg(pkgSpec);
let packageName = pkgInfo.name;
if (!pkgInfo.registry) {
// Package name is unknown, so fetch it with 'npm pack' command
let execOutput = "No Spawn output retrieved";
try {
execOutput = utilities_1.ExecUtils.spawnAndGetOutput(npmCmd, ["pack", pkgSpec, "--dry-run", "--json"]);
packageName = JSON.parse(execOutput.toString())[0].name;
}
catch (err) {
throw new error_1.ImperativeError({
msg: `Failed to fetch metadata for package: ${pkgSpec}`,
additionalDetails: "Error.message = " + err.message +
"\nSpawn output:\n" + execOutput
});
}
}
return (0, jsonfile_1.readFileSync)(path.join(PMFConstants_1.PMFConstants.instance.PLUGIN_HOME_LOCATION, packageName, "package.json"));
}
class NpmRegistryUtils {
/**
* Get the registry to install to.
* @param userRegistry Registry override specified on the command line
* @return {string}
*/
static getRegistry(userRegistry) {
if (userRegistry != null)
return userRegistry;
const execOutput = utilities_1.ExecUtils.spawnAndGetOutput(npmCmd, ["config", "get", "registry"]);
return execOutput.toString().replace("\n", "");
}
/**
* NPM login to be able to install from secure registry
* @param {string} registry The npm registry to install from.
*/
static npmLogin(registry) {
utilities_1.ExecUtils.spawnAndGetOutput(npmCmd, [
"login",
"--registry", registry,
"--always-auth",
"--auth-type=legacy"
], { stdio: "inherit" });
}
/**
* Get package location and npm registry args for installing it.
* @param packageInfo Plugin name or object from plugins.json
* @param userRegistry Registry override specified on the command line
* @returns Location info for npm package to be installed
*/
static buildRegistryInfo(packageInfo, userRegistry) {
const packageName = typeof packageInfo === "string" ? packageInfo : packageInfo.package;
const packageScope = packageName.startsWith("@") ? packageName.split("/")[0] : undefined;
if (userRegistry != null) {
// If --registry was passed on the command line, it takes precedence
return {
location: userRegistry,
npmArgs: this.buildRegistryNpmArgs(userRegistry, packageScope)
};
}
else if (typeof packageInfo === "string" || !packageInfo.location) {
// If installing a plug-in for the first time, get default registry
const defaultRegistry = this.getRegistry();
return {
location: npmPackageArg(packageName).registry ? defaultRegistry : packageName,
npmArgs: this.buildRegistryNpmArgs(defaultRegistry, packageScope)
};
}
else {
// If updating a plug-in, fetch registry info from plugins.json
const cachedRegistry = npmPackageArg(packageInfo.package).registry ? packageInfo.location : undefined;
return {
location: packageInfo.location,
npmArgs: this.buildRegistryNpmArgs(cachedRegistry !== null && cachedRegistry !== void 0 ? cachedRegistry : this.getRegistry(), packageScope)
};
}
}
static buildRegistryNpmArgs(registryUrl, scope) {
const npmArgs = { registry: registryUrl };
if (scope != null) {
npmArgs[`${scope}:registry`] = this.getScopeRegistry(scope);
}
return npmArgs;
}
static getScopeRegistry(scope) {
const execOutput = utilities_1.ExecUtils.spawnAndGetOutput(npmCmd, ["config", "get", `${scope}:registry`]);
if (execOutput.toString().trim() === "undefined")
return;
return execOutput.toString().replace("\n", "");
}
}
exports.NpmRegistryUtils = NpmRegistryUtils;
//# sourceMappingURL=NpmFunctions.js.map