depguard
Version:
A powerful CLI tool to check and update npm/yarn dependencies in your projects
66 lines (65 loc) • 2.81 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Update = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const child_process_1 = require("child_process");
const axios_1 = __importDefault(require("axios"));
const semver_1 = __importDefault(require("semver"));
const chalk_1 = __importDefault(require("chalk"));
const config_1 = require("./config/config");
class Update {
constructor() {
this.config = new config_1.Config();
}
getPackageManager() {
return fs_1.default.existsSync(path_1.default.resolve(process.cwd(), 'yarn.lock')) ? 'yarn' : 'npm';
}
async getLatestVersion(pkg) {
try {
const res = await axios_1.default.get(`https://registry.npmjs.org/${pkg}/latest`);
return res.data.version;
}
catch {
return null;
}
}
async updateDependencies(options = {}) {
const { safe = false } = options;
const { exclude } = this.config.loadConfig();
const pkgPath = path_1.default.resolve(process.cwd(), 'package.json');
const pkg = JSON.parse(fs_1.default.readFileSync(pkgPath, 'utf-8'));
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
const packageManager = this.getPackageManager();
const updated = [];
for (const [name, currentRange] of Object.entries(deps)) {
if (exclude.includes(name))
continue;
const latest = await this.getLatestVersion(name);
if (!latest)
continue;
const current = currentRange.replace(/^[~^]/, '');
const isCompatible = semver_1.default.satisfies(latest, currentRange);
if (safe && !isCompatible)
continue;
const version = safe ? `^${latest}` : latest;
const cmd = packageManager === 'yarn'
? `yarn add ${name}@${version}`
: `npm install ${name}@${version}`;
console.log(`Updating ${name} → ${version}`);
(0, child_process_1.execSync)(cmd, { stdio: 'inherit' });
updated.push({ name, currentRange, updatedVersion: version });
}
this.generateReport(updated);
console.log(chalk_1.default.green('\nAll dependencies updated.\n'));
}
generateReport(updated) {
const reportPath = path_1.default.resolve(process.cwd(), 'report.json');
fs_1.default.writeFileSync(reportPath, JSON.stringify(updated, null, 2));
console.log(chalk_1.default.green('Report written to report.json'));
}
}
exports.Update = Update;