Git Product home page Git Product logo

package.json-validator's Introduction

About

package.json files are required for node.js/npm projects. Beyond just valid json, there are required fields to follow the specifications. This tool verifies the package.json against the specification of your choice, letting you know if you have a valid file. The validation reports required fields that you MUST have, warns for fields that you SHOULD have, and recommends optional fields that you COULD have.

Supported Specifications

Of course, there are multiple ones to follow, which makes it trickier.

Usages

Command line

npm install package-json-validator -g

See pjv --help for usage:

Options:
  --filename, -f         package.json file to validate                      [default: "package.json"]
  --spec, -s             which spec to use - npm|commonjs_1.0|commonjs_1.1  [default: "npm"]
  --warnings, -w         display warnings                                   [default: false]
  --recommendations, -r  display recommendations                            [default: false]
  --quiet, -q            less output                                        [default: false]
  --help, -h, -?         this help message                                  [default: false]

As a node library

npm install package-json-validator

Via Grunt

Have your package validate via a Grunt plugin - see grunt-nice-package

Via Gulp

Have your package validate via a gulp plugin - see gulp-nice-package

API

PJV.validate(packageData[[, spec], options])

spec is either npm, commonjs_1.0, or commonjs_1.1

options is an object with the following available:

{
    warnings: true, // show warnings
    recommendations: true // show recommendations
}

Example:

var PJV=require('package-json-validator').PJV;
PJV.validate(data, spec, options)

Example1:

 var PJV=require('package-json-validator').PJV;
 let text=JSON.stringify({
      "name": "packageJsonValidator",
      "version": "0.1.0",
      "private": true,
      "dependencies": {
        "date-fns": "^2.29.3",
        "install": "^0.13.0",
        "react": "^18.2.0",
        "react-chartjs-2": "^5.0.1",
        "react-dom": "^18.2.0",
        "react-material-ui-carousel": "^3.4.2",
        "react-multi-carousel": "^2.8.2",
        "react-redux": "^8.0.5",
        "react-router-dom": "^6.4.3",
        "react-scripts": "5.0.1",
        "redux": "^4.2.0",
        "styled-components": "^5.3.6",
        "web-vitals": "^2.1.4"
      },
      "scripts": {
        "start": "react-scripts start"
      },
      "eslintConfig": {
        "extends": [
          "react-app",
          "react-app/jest"
        ]
      },
      "browserslist": {
        "production": [
          ">0.2%",
          "not dead",
          "not op_mini all"
        ],
        "development": [
          "last 1 chrome version",
          "last 1 firefox version",
          "last 1 safari version"
        ]
      }
    })
    const data=PJV.validate(text)

Output for above example

console.log(data)
// {
//  valid: true,
//   warnings: [
//    'Missing recommended field: description',
//    'Missing recommended field: keywords',
//    'Missing recommended field: bugs',
//    'Missing recommended field: licenses',
//    'Missing recommended field: author',
//    'Missing recommended field: contributors',
//    'Missing recommended field: repository'
//  ],
//  recommendations: [
//    'Missing optional field: homepage',
//    'Missing optional field: engines'
//  ]
} 

Issues/Requests

Please check out the existing issues, and if you don't see that your problem is already being worked on, please file an issue.

Fork and Pull request

Since you are probably a developer, you can probably just make the change yourself and submit a pull request

License

See LICENSE

package.json-validator's People

Contributors

4u6u57 avatar abrkn avatar amilajack avatar anudeep586 avatar chmontgomery avatar claycarpenter avatar davglass avatar dsebastien avatar hemanth avatar jatin avatar joshuakgoldberg avatar linusu avatar pdehaan avatar sarahhagstrom avatar technickai avatar vkrol avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

package.json-validator's Issues

Man field not accepting string

We're getting the following output on a valid package.json with a man field for installing our manpage:

{ valid: false,
  errors: [ 'Type for field man, was expected to be object, not string' ] }

The package.json spec says that man can be either a single file path or an array of file paths.

package.json has warnings

Whoa! package-json-validator-ception!

Ran the repo's latest package.json through the online validator and testing the globally installed "pjv" module and saw the following warnings:

{
"valid": true,
"warnings": [
"Missing recommended field: keywords",
"Missing recommended field: homepage",
"Missing recommended field: bugs",
"Missing recommended field: licenses"
],
"recommendations": [
"Missing optional field: contributors",
"Missing optional field: files",
"Missing optional field: man",
"Missing optional field: directories",
"Missing optional field: config",
"Missing optional field: bundledDependencies",
"Missing optional field: optionalDependencies",
"Missing optional field: engines",
"Missing optional field: engineStrict",
"Missing optional field: os",
"Missing optional field: cpu",
"Missing optional field: preferGlobal",
"Missing optional field: private",
"Missing optional field: publishConfig"
]
}

Error when specifying bundledDependencies

I get errors when I try validating the following package.json file:

http://package.json.nodejitsu.com/

{
  "valid": false,
  "errors": [
    "Invalid dependency package name: 0",
    "Invalid version range for dependency 0: union",
    "Invalid dependency package name: 1",
    "Invalid version range for dependency 1: ecstatic"
  ],
  "warnings": [
    "Missing recommended field: homepage",
    "Missing recommended field: bugs",
    "Missing recommended field: licenses"
  ],
  "recommendations": [
    "Missing optional field: files",
    "Missing optional field: man",
    "Missing optional field: directories",
    "Missing optional field: config",
    "Missing optional field: optionalDependencies",
    "Missing optional field: engineStrict",
    "Missing optional field: os",
    "Missing optional field: cpu",
    "Missing optional field: private",
    "Missing optional field: publishConfig"
  ]
}

It looks like if I remove the specified bundledDependencies then I no longer get errors:

{
  "valid": true,
  "warnings": [
    "Missing recommended field: homepage",
    "Missing recommended field: bugs",
    "Missing recommended field: licenses"
  ],
  "recommendations": [
    "Missing optional field: files",
    "Missing optional field: man",
    "Missing optional field: directories",
    "Missing optional field: config",
    "Missing optional field: optionalDependencies",
    "Missing optional field: engineStrict",
    "Missing optional field: os",
    "Missing optional field: cpu",
    "Missing optional field: private",
    "Missing optional field: publishConfig"
  ]
}

πŸš€ Feature: Add support for "repository" warnings in npm

npm install will warn the end-user if there's no repository field for a package, so it makes sense to warn the developer too :-)

For example,

npm WARN package.json [email protected] No repository field.
npm WARN package.json [email protected] 'repositories' (plural) Not supported.
npm WARN package.json Please pick one as the 'repository' field

As a bonus, it would of course be nice to warn about the inclusion of the unsupported repositories field at the same time.

Valid dependency package name reported as invalid

The following package.json file is marked as invalid:

{
  "name": "tmp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "dSebastien <[email protected]> (https://www.dsebastien.net)",
  "license": "ISC",
  "dependencies": {
    "@reactivex/rxjs": "5.0.0-alpha.7"
  }
}

output of pjv package.json:

{ valid: false,
  errors: [ 'Invalid dependency package name: @reactivex/rxjs' ] }

πŸš€ Feature: Option to get the valid fields returned?

Hi there, I'm using this module as part of a bigger validator for Ghost themes.

After I've checked that the package.json is valid, I want to use some of the fields to inform my report (name, version, description, etc) and eventually I'd like to add a few extra validations of my own which are Ghost-specific.

At the moment, I end up having to do some work twice. I can't parse the JSON and pass pre-parsed JSON to package.json-validator as it expects a string, but I also don't believe it's currently possible to get the parsed JSON back from PJV to do further work on.

I'm happy to submit a PR, but thought I'd check first, would the option to get the valid JSON back be something that would be accepted? Any thoughts or recommendations on naming or approach?

πŸ› Bug: Local path dependencies not recognized

Example input:

{
  "name": "test",
  "version": "1.0.0",
  "author": "test",
  "devDependencies": {
    "test": "file:./"
  }
}

Expected result:

{
  "valid": true
}

Actual result:

{
  "valid": false,
  "errors": [
    "Invalid version range for dependency test: file:./"
  ]
}

πŸš€ Feature: Recommend `main` and `exports`

Per https://nodejs.org/api/esm.html#esm_main_entry_point_export

To set the main entry point for a package, it is advisable to define both "exports" and "main" in the package’s package.json file:

{
"main": "./main.js",
"exports": "./main.js"
}

The benefit of doing this is that when using the "exports" field all subpaths of the package will no longer be available to importers under require('pkg/subpath.js'), and instead they will get a new error, ERR_PACKAGE_PATH_NOT_EXPORTED.

This encapsulation of exports provides more reliable guarantees about package interfaces for tools and when handling semver upgrades for a package. It is not a strong encapsulation since a direct require of any absolute subpath of the package such as require('/path/to/node_modules/pkg/subpath.js') will still load subpath.js.

Also the order within exports (and the order within exports subpaths, e.g., {exports: {"./feature": {browser: "./feature-browser.js", default: "./feature.js"}} and within nested conditions, e.g., {"exports": {"import": {"node": "./feature-node.mjs"}}}) could be enforced per https://nodejs.org/api/esm.html#esm_conditional_exports :

"node" - matched for any Node.js environment. Can be a CommonJS or ES module file. This condition should always come after "import" or "require".
"default" - the generic fallback that will always match. Can be a CommonJS or ES module file. This condition should always come last.

package.json reports errors when module name is only 1 char

I was validating a package.json file and noticed it was complaining about the "q" module. I believe the current dependency name RegExp is trying to match 2 or more characters. We may need to switch a "+" to a "*".

PJV.js:7 packageFormat: /^[a-z0-9][a-z0-9\.\-_]+$/,

{
  "name": "foo",
  "version": "0.1.0",
  "dependencies": {
    "q": "0.9.7"
  }
}

author attribute isn't a required field for npm

It looks like the author field is required by package.json-validator, but not by npm.

I don't see any mention of the author field being required in the published npm package.json documentation. I only see that the name and version fields are required:

The most important things in your package.json are the name and version fields. Those are actually required, and your package won't install without them.

I tested this out against older and more recent versions of npm. I put together a very minimal module that contains ony name and version attributes, and attempted to declare that minimal module as a dependency of another empty module. Everything (install, uninstall, update, etc.) seems to work fine even though the minimal module doesn't contain the author attribute.

Am I missing something, or is this a bug?

Latest version shows as 0.6.1 in npm?

Hi, just wanted to flag up that the package.json in the repo states the version as 0.6.0, but on npm it says 0.6.1 😁

There are no tags since 0.5.6 and no changelog so I'm wondering what is in 0.6.1 πŸ€”

Also: Is this module likely to be actively maintained again? I'm using it for a project and need to get some updates in. I can PR but my last issue didn't get a reply so I thought I'd ask before PRing or forking.

Author string doesnt support optional email/url when using shorthand

I think this should be valid, but it is complaining:

{
  "name": "foo",
  "author": "peter",
  "version": "0.0.1"
}

The error I'm getting from the online validator is:

{
  "valid": false,
  "errors": [
    "String not valid for author, expected format is Barney Rubble <[email protected]> (http://barnyrubble.tumblr.com/)"
  ],
  "warnings": [
   ...
  ],
  "recommendations": [
    ...
  ]
}

Ignore warnings with packages uppercase characters

The following package.json gives me an error:

{
  "name": "bar",
  "version": "0.0.2",
  "dependencies": {
    "JSONSelect": "0.4.0"
  }
}

And the warning of "Invalid dependency package name: JSONSelect":

  "errors": [
    "Invalid dependency package name: JSONSelect"
  ]

support for license (singular)

Steps to reproduce:

  1. On http://package-json-validator.com/ enter the URL: https://github.com/isaacs/node-tap

Actual results:

{
  "valid": false,
  "errors": [
    "Type for field license, was expected to be string, not object",
    "Type for field repository, was expected to be object, not string"
  ],
  "warnings": [
    "Missing recommended field: bugs"
  ],
  "recommendations": [
    "Missing optional field: homepage"
  ]
}

Expected results:

We should support the singular version of license. I figure @isaacs knows a thing or two about package.json and license is valid. I found https://www.npmjs.org/doc/files/package.json.html#license but it only mentions the shorthand version of the license as a strong, not as an object. And makes no mention of licenses[] plural.

PJV.validate is not a function

I think it may be my mistake, but if it is I hope someone knows how to help me I'm using the npm package package-json-validator in a nodejs script and when I run the code it gives an error saying PJV.validate is not a function

My script:

var PJV = require("package-json-validator").PJV;

const data = "{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"package-json-validator": "^0.6.3"
},
"devDependencies": {},
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"author": "",
"license": "ISC"
}";

PJV.validate(data, "npm", {
warnings: true, // show warnings
recommendations: true // show recommendations
})

Line numbers?

This is my one gripe with npm. Seems an obvious addition to this package.

πŸš€ Feature: Recommend "type"

Per https://nodejs.org/api/esm.html#esm_package_json_type_field

Package authors should include the "type" field, even in packages where all sources are CommonJS. Being explicit about the type of the package will future-proof the package in case the default type of Node.js ever changes, and it will also make things easier for build tools and loaders to determine how the files in the package should be interpreted.

It could also be checked for the valid values "commonjs" or "module".

Thanks!

Malware alert on homepage

Clicking the homepage link presents the following malware alert from uBlock Origin:

uBlock Origin has prevented the following page from loading:

http://click.expmediadirect1.com/click?i=pW1KX8XbnF0_0

Because of the following filter:

||expmediadirect1.com^

Found in: uBlock filters – Badware risks 

πŸš€ Feature: Check for weird built-in node modules

I've seen a ton of modules that specify fs and path in their dependencies.
http://npm.im/fs

It may be a bit hacky, but you could possibly store an array of built-in Node modules from https://nodejs.org/dist/latest-v6.x/docs/api/ (ie: "assert", "buffer", "child_process", "fs", "http", "path", etc) and then display warnings if the package.json uses any of those built-in modules.

Of course, there may be a valid reason to use the npm version of "path", so I guess they shouldn't be fatal errors, but I find most people may do npm i fs path -S by mistake and often don't want them or understand they have been built-in since Node 0.1. 🀷

Convert to npm module so it can be used w/ Node.js

It'd be super awesome if this could be abstracted and run as a Node.js module so I could integrate it w/ something like Grunt where my build would fail if the package.json file wasnt valid.

Submitting an issue so I can subscribe to notifications.

πŸš€ Feature: Accept parsed JSON directly

Hello!

Thank you for this great library!

However, right now, the validate function accepts the manifest in a string format, however, it would be great if it would accept a pre-parsed JSON object.

This would be beneficial in pipeline scenarios.

Thanks!

Your sample package.json files both fail validation

Error: "Type for field repository, was expected to be string,object, not string".

There even seems to be an error in the error message.

FYI I started looking into this because my plugin was out of date on npm. If you do npm info intl-tel-input (or if you check the website), it says the latest version is 2.0.10, when it is actually 3.4.0. I wondered if it might be a problem with my package.json, so I ran it on your site and got this same error, but couldn't figure out what was wrong with the repository field, so tried the samples and they failed too, as does the example on the npm page about package.json.

Support for shorthand GitHub strings for repository field

I'm getting an error with the following value in my package.json file:

"repository": "mozilla/fxa-profile-server",
package.json is NOT valid
{ valid: false,
  errors: [ 'Type for field repository, was expected to be object, not string' ],
  warnings:
   [ 'Missing recommended field: keywords',
     'Missing recommended field: contributors' ] }

I believe this was added in npm 1.3.10 (per http://dailyjs.com/2013/09/06/npm-updates/). In fact, I think this may be the npm issue: npm/npm#3783

errors when patch version is double digits

I'm getting errors when trying to parse the following package.json file:

{
  "name": "foo",
  "version": "0.3.10",
  "author": "bar <[email protected]>",
  "description": "",
  "license": "MIT"
}

And the error is:

{
  "valid": false,
  "errors": [
    "Value for field version, 0.3.10 does not match format: /^[0-9]+\\.[0-9]+\\.[0-9+a-zA-Z\\.]$/"
  ],
  "warnings": [
    ...
  ],
  "recommendations": [
    ...
  ]
}

I checked http://semver.org/spec/v2.0.0.html and didn't see any mention of the patch version being limited to 0-9.

Use a .travis.yml file to run npm test on each push to repo

Yay Travis!

I think all you'd need is to create a .travis.yml file and add the following contents (as well as sign up at https://travis-ci.org/ and tell it to watch this repo):

language: node_js
node_js:
  - "0.10"

This should run npm install and npm test for you automatically. Then just add a fancy badge to your README.md to see the current status. We may need to tweak another couple things like adding before_install which installs the grunt-cli or whatever.

Invalid version range for dependency: latest

I'm getting errors when my dependency version range is set to "latest", which should be legit according to npm's package.json dependencies docs:

$ pjv --warnings
package.json is NOT valid

{ valid: false,
  errors:
   [ 'Invalid version range for dependency chai: latest',
     'Invalid version range for dependency jsxhint: latest',
     'Invalid version range for dependency mocha: latest',
     'Invalid version range for dependency sinon: latest' ],
  warnings: [ 'Missing recommended field: contributors' ] }

Where our devDependencies look a little something like this:

  "devDependencies": {
    "6to5ify": "^4.0.*",
    "chai": "latest",
    "gulp-sourcemaps": "^1.3.0",
    "jsxhint": "latest",
    "karma": "^0.12.*",
    "karma-6to5-preprocessor": "^3.0.*",
    "karma-browserify": "^3.0.*",
    "karma-chai": "^0.1.*",
    "karma-chai-plugins": "^0.2.4",
    "karma-chrome-launcher": "^0.1.7",
    "karma-firefox-launcher": "^0.1.*",
    "karma-mocha": "^0.1.*",
    "karma-react-preprocessor": "0.0.*",
    "mocha": "latest",
    "react-tools": "0.12.2",
    "sinon": "latest"
  }

πŸš€ Feature: Too many API requests should give a meaningful error

If I try to parse a Github package.json via the url method, I get the following error message

screen shot 2017-01-20 at 1 22 09 pm

After debugging the error, I found out that it's caused by making "too many requests" to the Github API.

/**/angular.callbacks._1t({
  "meta": {
    "Content-Type": "application/javascript; charset=utf-8",
    "X-RateLimit-Limit": "60",
    "X-RateLimit-Remaining": "0",
    "X-RateLimit-Reset": "1484939293",
    "X-GitHub-Media-Type": "github.v3; format=json",
    "status": 403
  },
  "data": {
    "message": "API rate limit exceeded for xxx.xxx.xxx.xxx. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)",
    "documentation_url": "https://developer.github.com/v3/#rate-limiting"
  }
})

Would be nice if the error was more meaningful. Something like this would be nice

{
  "valid": "false",
  "critical":" Github API limit exceeded! Please wait a few minutes before making another request."
}

πŸš€ Feature: Validate by repo name.

var PJV=require('package-json-validator').PJV;
PJV.validate(repoName, spec, options);
psjv -r repoName

This is try to fetch the required package.json from the npmjs.org based on the repoName and validate it, will be very useful for scripts that are programatically validated list of repos.

πŸ› Bug: Support version protocols: npm:, workspace:, etc.

I use the syntax of the title so that I can have two different major version of one project as a dependency (one @1.x.x and one 2.x.x), but this validator doesn't recognize this syntax and outputs an error instead. It would be cool if this syntax was supported, but given that it is quite uncommon (to the best of my knowledge) I don't think this should be a priority.

The following package.json content can be used to reproduce this error.

{
  "name": "project",
  "version": "1.0.0",
  "private": true,
  "description": "...",
  "homepage": "https://github.com/ericcornelissen/project",
  "license": "MIT",
  "main": "lib/index.js",
  "repository": {
    "type": "git",
    "url": "https://github.com/ericcornelissen/project"
  },
  "dependencies": {
    "svgo-v1": "npm:[email protected]",
    "svgo-v2": "npm:[email protected]"
  }
}

πŸ› Bug: Add support for GitHub URLs in dependencies

I'm currently trying to get my package.json valided before submiting a new package. However, the validation is faling since I'm trying to use GitHub URLs in my dependencies.

From the npm docs:

As of version 1.1.65, you can refer to GitHub urls as just "foo": "user/foo-project".

However, if I use the following de

"dependencies": {
  "foo": "user/foo-project"
}

package.json-validator tell me that my package.json is not valid:

package.json is NOT valid
{ valid: false,
  errors: [ 'Invalid version range for dependency foo: user/foo-project' ] }

Errors when trying to validate versions with patch labels

I'm getting errors when trying to validate a version with a hyphen and label:

{
  "name": "foo",
  "version": "1.0.0-alpha",
  "author": "bar <[email protected]>",
  "description": "",
  "license": "MIT"
}

And the error is:

{
  "valid": false,
  "errors": [
    "Value for field version, 1.0.0-alpha does not match format: /^[0-9]+\\.[0-9]+\\.[0-9+a-zA-Z\\.]$/"
  ],
  "warnings": ["..."],
  "recommendations": ["..."]
}

Other examples (see sections 9-11 of http://semver.org/spec/v2.0.0.html) are:

Examples: 1.0.0-alpha, 1.0.0-alpha.1, 1.0.0-0.3.7, 1.0.0-x.7.z.92.

Examples: 1.0.0-alpha+001, 1.0.0+20130313144700, 1.0.0-beta+exp.sha.5114f85.

Example: 1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-alpha.beta < 1.0.0-beta < 1.0.0-beta.2 < 1.0.0-beta.11 < 1.0.0-rc.1 < 1.0.0.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.