-
-
Notifications
You must be signed in to change notification settings - Fork 594
/
npm-packages-exists.ts
63 lines (55 loc) · 1.74 KB
/
npm-packages-exists.ts
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
import chalk from "chalk";
import isLocalPath from "./is-local-path";
import npmExists from "./npm-exists";
import { resolvePackages } from "./resolve-packages";
const WEBPACK_SCAFFOLD_PREFIX: string = "webpack-scaffold";
/**
*
* Loops through an array and checks if a package is registered
* on npm and throws an error if it is not.
*
* @param {String[]} pkg - Array of packages to check existence of
* @returns {Array} resolvePackages - Returns an process to install the packages
*/
export default function npmPackagesExists(pkg: string[]): void {
const acceptedPackages: string[] = [];
function resolvePackagesIfReady() {
if (acceptedPackages.length === pkg.length) {
return resolvePackages(acceptedPackages);
}
}
pkg.forEach((scaffold: string): void => {
if (isLocalPath(scaffold)) {
// If the scaffold is a path to a local folder, no name validation is necessary.
acceptedPackages.push(scaffold);
resolvePackagesIfReady();
return;
}
// The scaffold is on npm; validate name and existence
if (
scaffold.length <= WEBPACK_SCAFFOLD_PREFIX.length ||
scaffold.slice(0, WEBPACK_SCAFFOLD_PREFIX.length) !== WEBPACK_SCAFFOLD_PREFIX
) {
throw new TypeError(
chalk.bold(`${scaffold} isn't a valid name.\n`) +
chalk.red(
`\nIt should be prefixed with '${WEBPACK_SCAFFOLD_PREFIX}', but have different suffix.\n`,
),
);
}
npmExists(scaffold)
.then((moduleExists: boolean) => {
if (moduleExists) {
acceptedPackages.push(scaffold);
} else {
Error.stackTraceLimit = 0;
throw new TypeError(`Cannot resolve location of package ${scaffold}.`);
}
})
.catch((err: IError) => {
console.error(err.stack || err);
process.exit(0);
})
.then(resolvePackagesIfReady);
});
}