UNPKG

@appium/support

Version:

Support libs used across Appium packages

260 lines 10.4 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.npm = exports.NPM = exports.INSTALL_LOCKFILE_RELATIVE_PATH = exports.CACHE_DIR_RELATIVE_PATH = void 0; const node_path_1 = __importDefault(require("node:path")); const semver = __importStar(require("semver")); const env_1 = require("./env"); const teen_process_1 = require("teen_process"); const fs_1 = require("./fs"); const util = __importStar(require("./util")); const system = __importStar(require("./system")); const resolve_from_1 = __importDefault(require("resolve-from")); /** * Relative path to directory containing any Appium internal files * XXX: this is duplicated in `appium/lib/constants.js`. */ exports.CACHE_DIR_RELATIVE_PATH = node_path_1.default.join('node_modules', '.cache', 'appium'); /** * Relative path to lockfile used when installing an extension via `appium` */ exports.INSTALL_LOCKFILE_RELATIVE_PATH = node_path_1.default.join(exports.CACHE_DIR_RELATIVE_PATH, '.install.lock'); /** * XXX: This should probably be a singleton, but it isn't. Maybe this module should just export functions? */ class NPM { /** * Execute `npm` with given args. * * If the process exits with a nonzero code, the contents of `STDOUT` and `STDERR` will be in the * `message` of any rejected error. */ async exec(cmd, args, opts, execOpts = {}) { const { cwd, json, lockFile } = opts; const teenProcessExecOpts = { ...execOpts, shell: system.isWindows() || execOpts.shell, cwd, }; const argsCopy = [cmd, ...args]; if (json) { argsCopy.push('--json'); } const npmCmd = system.isWindows() ? 'npm.cmd' : 'npm'; let runner = async () => await (0, teen_process_1.exec)(npmCmd, argsCopy, teenProcessExecOpts); if (lockFile) { const acquireLock = util.getLockFileGuard(lockFile); const _runner = runner; runner = async () => (await acquireLock(_runner)); } let ret; try { const { stdout, stderr, code } = await runner(); ret = { stdout, stderr, code }; try { ret.json = JSON.parse(stdout); } catch { // ignore } } catch (e) { const { stdout = '', stderr = '', code = null } = e; throw new Error(`npm command '${argsCopy.join(' ')}' failed with code ${code}.\n\nSTDOUT:\n${stdout.trim()}\n\nSTDERR:\n${stderr.trim()}`); } return ret; } /** * Gets the latest published version of a package from npm registry. * * @param cwd - Current working directory for npm command * @param pkg - Package name to query * @returns Latest version string, or `null` if package not found (e.g. 404) */ async getLatestVersion(cwd, pkg) { try { const result = await this.exec('view', [pkg, 'dist-tags'], { json: true, cwd }); const json = result.json; return json?.latest ?? null; } catch (err) { if (!(err instanceof Error) || !err.message.includes('E404')) { throw err; } return null; } } /** * Gets the latest version of a package that is a safe upgrade from the current version * (same major, no prereleases). Fetches versions from npm and delegates to * {@link NPM.getLatestSafeUpgradeFromVersions}. * * @param cwd - Current working directory for npm command * @param pkg - Package name to query * @param curVersion - Current installed version * @returns Latest safe upgrade version string, or `null` if none or package not found */ async getLatestSafeUpgradeVersion(cwd, pkg, curVersion) { try { const result = await this.exec('view', [pkg, 'versions'], { json: true, cwd }); const allVersions = result.json; if (!Array.isArray(allVersions)) { return null; } return this.getLatestSafeUpgradeFromVersions(curVersion, allVersions); } catch (err) { if (!(err instanceof Error) || !err.message.includes('E404')) { throw err; } return null; } } /** * Runs `npm ls`, optionally for a particular package. */ async list(cwd, pkg) { return (await this.exec('list', pkg ? [pkg] : [], { cwd, json: true })).json; } /** * Given a current version and a list of all versions for a package, return the version which is * the highest safely-upgradable version (meaning not crossing any major revision boundaries, and * not including any alpha/beta/rc versions) */ getLatestSafeUpgradeFromVersions(curVersion, allVersions) { let safeUpgradeVer = null; const curSemver = semver.parse(curVersion) ?? semver.parse(semver.coerce(curVersion)); if (curSemver === null) { throw new Error(`Could not parse current version '${curVersion}'`); } for (const testVer of allVersions) { const testSemver = semver.parse(testVer) ?? semver.parse(semver.coerce(testVer)); if (testSemver === null || testSemver.prerelease.length > 0 || curSemver.compare(testSemver) === 1 || testSemver.major > curSemver.major) { continue; } if (safeUpgradeVer === null || testSemver.compare(safeUpgradeVer) === 1) { safeUpgradeVer = testSemver; } } return safeUpgradeVer ? safeUpgradeVer.format() : null; } /** * Installs a package w/ `npm` */ async installPackage(cwd, installStr, opts) { const { pkgName, installType } = opts; let dummyPkgJson; const dummyPkgPath = node_path_1.default.join(cwd, 'package.json'); try { dummyPkgJson = JSON.parse(await fs_1.fs.readFile(dummyPkgPath, 'utf8')); } catch (err) { const nodeErr = err; if (nodeErr.code === 'ENOENT') { dummyPkgJson = {}; await fs_1.fs.writeFile(dummyPkgPath, JSON.stringify(dummyPkgJson, null, 2), 'utf8'); } else { throw err; } } const installOpts = ['--save-dev', '--no-progress', '--no-audit']; if (!(await (0, env_1.hasAppiumDependency)(cwd))) { if (process.env.APPIUM_OMIT_PEER_DEPS) { installOpts.push('--omit=peer'); } installOpts.push('--save-exact', '--global-style', '--no-package-lock'); } const cmd = installType === 'local' ? 'link' : 'install'; const res = await this.exec(cmd, [...installOpts, installStr], { cwd, json: true, lockFile: this._getInstallLockfilePath(cwd), }); if (res.json && typeof res.json === 'object' && 'error' in res.json && res.json.error) { throw new Error(String(res.json.error)); } const pkgJsonPath = (0, resolve_from_1.default)(cwd, `${pkgName}/package.json`); try { const pkgJson = await fs_1.fs.readFile(pkgJsonPath, 'utf8'); const pkg = JSON.parse(pkgJson); return { installPath: node_path_1.default.dirname(pkgJsonPath), pkg }; } catch { throw new Error('The package was not downloaded correctly; its package.json ' + 'did not exist or was unreadable. We looked for it at ' + pkgJsonPath); } } /** * Uninstalls a package with `npm uninstall`. * * @param cwd - Current working directory (project root) * @param pkg - Package name to uninstall */ async uninstallPackage(cwd, pkg) { await this.exec('uninstall', [pkg], { cwd, lockFile: this._getInstallLockfilePath(cwd), }); } /** * Fetches package metadata from the npm registry via `npm info`. * * @param pkg - Npm package spec to query * @param entries - Field names to be included into the resulting output. By default all fields are included. * @returns Package metadata as a record of string values */ async getPackageInfo(pkg, entries = []) { const result = await this.exec('info', [pkg, ...entries], { cwd: process.cwd(), json: true, }); return (result.json ?? {}); } /** Returns path to "install" lockfile */ _getInstallLockfilePath(cwd) { return node_path_1.default.join(cwd, exports.INSTALL_LOCKFILE_RELATIVE_PATH); } } exports.NPM = NPM; exports.npm = new NPM(); //# sourceMappingURL=npm.js.map