You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
74 lines
2.1 KiB
74 lines
2.1 KiB
// src/detect.ts
|
|
import fs from "fs";
|
|
import path from "path";
|
|
import findUp from "find-up";
|
|
var AGENTS = ["pnpm", "yarn", "npm", "pnpm@6", "yarn@berry", "bun"];
|
|
var LOCKS = {
|
|
"bun.lockb": "bun",
|
|
"pnpm-lock.yaml": "pnpm",
|
|
"yarn.lock": "yarn",
|
|
"package-lock.json": "npm",
|
|
"npm-shrinkwrap.json": "npm"
|
|
};
|
|
async function detectPackageManager(cwd = process.cwd()) {
|
|
let agent = null;
|
|
const lockPath = await findUp(Object.keys(LOCKS), { cwd });
|
|
let packageJsonPath;
|
|
if (lockPath)
|
|
packageJsonPath = path.resolve(lockPath, "../package.json");
|
|
else
|
|
packageJsonPath = await findUp("package.json", { cwd });
|
|
if (packageJsonPath && fs.existsSync(packageJsonPath)) {
|
|
try {
|
|
const pkg = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
|
|
if (typeof pkg.packageManager === "string") {
|
|
const [name, version] = pkg.packageManager.split("@");
|
|
if (name === "yarn" && parseInt(version) > 1)
|
|
agent = "yarn@berry";
|
|
else if (name === "pnpm" && parseInt(version) < 7)
|
|
agent = "pnpm@6";
|
|
else if (name in AGENTS)
|
|
agent = name;
|
|
else
|
|
console.warn("[ni] Unknown packageManager:", pkg.packageManager);
|
|
}
|
|
} catch {
|
|
}
|
|
}
|
|
if (!agent && lockPath)
|
|
agent = LOCKS[path.basename(lockPath)];
|
|
return agent;
|
|
}
|
|
|
|
// src/install.ts
|
|
import execa from "execa";
|
|
async function installPackage(names, options = {}) {
|
|
const detectedAgent = options.packageManager || await detectPackageManager(options.cwd) || "npm";
|
|
const [agent] = detectedAgent.split("@");
|
|
if (!Array.isArray(names))
|
|
names = [names];
|
|
const args = options.additionalArgs || [];
|
|
if (options.preferOffline) {
|
|
if (detectedAgent === "yarn@berry")
|
|
args.unshift("--cached");
|
|
else
|
|
args.unshift("--prefer-offline");
|
|
}
|
|
return execa(
|
|
agent,
|
|
[
|
|
agent === "yarn" ? "add" : "install",
|
|
options.dev ? "-D" : "",
|
|
...args,
|
|
...names
|
|
].filter(Boolean),
|
|
{
|
|
stdio: options.silent ? "ignore" : "inherit",
|
|
cwd: options.cwd
|
|
}
|
|
);
|
|
}
|
|
export {
|
|
detectPackageManager,
|
|
installPackage
|
|
};
|
|
|