Skip to content

Commit

Permalink
Add validation for npm module name
Browse files Browse the repository at this point in the history
  • Loading branch information
jennyEckstein committed Feb 24, 2021
1 parent 8468537 commit be1133d
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 1 deletion.
10 changes: 10 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,19 @@ const path = require('path');
const semver = require('semver');
const { exec } = require('child_process');
const { promisify } = require('util');
const validatePackageName = require('validate-npm-package-name');

const execAsync = promisify(exec);

function isValidNpmPackageName(name) {
const { errors } = validatePackageName(name);
if (errors) {
throw new Error(`NPM package name: "${name}" is invalid. ${errors}`);
}
}

async function getLatestVersions(name) {
isValidNpmPackageName(name);
const { stdout } = await execAsync(`npm view ${name} versions --json`);
try {
return JSON.parse(stdout);
Expand All @@ -22,6 +31,7 @@ async function getLatestVersions(name) {
}

async function getLatestTag(name) {
isValidNpmPackageName(name);
try {
const { stdout } = await execAsync(`npm view ${name} dist-tags --json`);
const { latest } = JSON.parse(stdout);
Expand Down
8 changes: 8 additions & 0 deletions lib/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,14 @@ describe('lib/index', () => {
expect(logger.info).toHaveBeenNthCalledWith(6, `Upgraded dependencies:\n["1.0.0"]`);
expect(logger.info).toHaveBeenNthCalledWith(7, `Upgraded development dependencies:\n["1.0.0"]`);
});

test('throw error when npm module name is invalid', async () => {
mockExports.dependencies = { 'bad name Dependency': '1.2.3' };
mockExecAsync.mockImplementationOnce(mock);
await expect(verifyDeps({ autoUpgrade: true, dir, logger })).rejects.toThrow(
'NPM package name: "bad name Dependency" is invalid. name can only contain URL-friendly characters'
);
});
});

module.exports = mockExports;
13 changes: 13 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@
"dependencies": {
"chalk": "^3.0.0",
"minimist": "^1.2.5",
"semver": "^7.3.4"
"semver": "^7.3.4",
"validate-npm-package-name": "^3.0.0"
},
"devDependencies": {
"auto-changelog": "^1.16.4",
Expand Down

0 comments on commit be1133d

Please sign in to comment.