GithubHelp home page GithubHelp logo

tclindner / npm-package-json-lint Goto Github PK

View Code? Open in Web Editor NEW
218.0 5.0 33.0 5.49 MB

Configurable linter for package.json files

Home Page: https://npmpackagejsonlint.org

License: MIT License

JavaScript 5.26% CSS 0.27% TypeScript 94.47%
linter npm-package npm-package-json-lint nodejs npm

npm-package-json-lint's Introduction

npm-package-json-lint

A package.json linter for Node projects

license npm ci Netlify Status

What is npm-package-json-lint?

npm-package-json-lint helps enforce standards for your package.json file. This helps to ensure that your files are of the highest standard and quality. It is also customisable to match your specific project guidline requirements/desires. It has support for both command line and programmatic usage. Currently it can check for:

  • validity of data types in nodes. Ex: name should always be a string.
  • whether a string is a lowercase
  • whether a version number is a valid
  • the presence of a given module
  • the presence of a pre-release version of a module
  • the presence of an author
  • the presence of any bugs
  • valid dependencies
  • valid licenses
  • and much more!

Please see the website for a list of rules.

Install and Use

First thing first, let's make sure you have the necessary pre-requisites.

System Dependencies

Node

Use the cli

Use cli globally

  • npm install npm-package-json-lint -g

Use cli in project

  • npm install npm-package-json-lint

Using the linter

From the command line
  • Once npm-package-json-lint is installed either in the project or globally it can be run with the following command, npx npm-package-json-lint. This will go through the process of linting/validating your code to meet your desired specifications.
In the program
  • The linter can also be used as a module in the program and the output be displayed via a log message. Adding the following code to your file can accomplish this.

    const npmPackageJsonLint = require("npm-package-json-lint");
    const result = npmPackageJsonLint.lintFiles(["package.json"]);
    console.log(result);
    

Custom Configuration

npm-package-json-lint has the ability to be constomly configured to match your desires. To configure the linter navigate to the .npmpackagejsonlintrc file in the repository and add in or remove your desired rules.

Local Development

Follow these steps to get your local environement set up to allow you to contribute to the repository

  1. In the terminal, navigate to the directory in which you want the repository to be cloned.
  2. Run this command from the terminal, git clone https://github.com/tclindner/npm-package-json-lint.git
  3. After cloning the repository navigate into the project's root directory from the terminal.
  4. Run "npm install" to install the necessary dependencies.
  5. Your local environment is now set up to create PR's and work on different issues

Documentation

Website

Quick links

CLI commands and configuration | Node.js API | Integrations

Migrating from v6.x.x to 7.x.x

Please see the migration guide.

Migrating from v5.x.x to 6.x.x

Please see the migration guide.

Migrating from v4.x.x to 5.x.x

Please see the migration guide.

Migrating from v3.x.x to 4.x.x

Please see the migration guide.

Migrating from v2.x.x to 3.x.x

Please see the migration guide.

Migrating from v1.x.x to 2.x.x

Please see the migration guide.

Migrating from v0.x.x to 1.x.x

Please see the migration guide.

Contributing

Please see CONTRIBUTING.md.

Release History

Please see CHANGELOG.md.

Related

License

Copyright (c) 2016-2023 Thomas Lindner. Licensed under the MIT license.

npm-package-json-lint's People

Contributors

aarongoldenthal avatar chr1shaefn3r avatar cjmartinez217 avatar dangreen avatar ddzz avatar dependabot-preview[bot] avatar dependabot[bot] avatar effrenus avatar evilebottnawi avatar fastfrwrd avatar jogold avatar kenrick95 avatar lddubeau avatar mfranzke avatar michaelmior avatar miripiruni avatar mrmlnc avatar ntwb avatar nvuillam avatar regseb avatar shaneog avatar simison avatar slavafomin avatar tclindner avatar tom-fletcher avatar tomtomsen avatar xboy2012 avatar yeldirium 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  avatar

npm-package-json-lint's Issues

`valid-values-license` not working

npm-package-json-lint version: 2.7.0
npm version: 5.3.0
node version: 8.1.4

The output from npm-package-json-lint:

Error: Error: valid-values-license - must be set to "error", "warning", or "off". Currently set to error,private
    at handleError (/Users/moshe/git/ventures/remote-lib/remote-lib/node_modules/npm-package-json-lint/src/cli.js:28:9)
    at Object.<anonymous> (/Users/moshe/git/ventures/remote-lib/remote-lib/node_modules/npm-package-json-lint/src/cli.js:126:3)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Function.Module.runMain (module.js:605:10)
    at startup (bootstrap_node.js:158:16)
    at bootstrap_node.js:575:3

What you expected to happen: Linting the license value.
The steps to reproduce the problem:

{
  "rules": {
    "valid-values-license": ["error", [
      "private"
    ]]
  }
}

TypeError: Cannot read property 'length' of undefined

  • A little info about your environment
    • npm-package-json-lint version 2.8.0
    • npm version 5.3.0
    • node version 8.4.0
  • The output from npm-package-json-lint
TypeError: Cannot read property 'length' of undefined
/path/to/node_modules/npm-package-json-lint/src/cli.js:28
  throw new Error(err);
  ^

Error: TypeError: Cannot read property 'length' of undefined
    at handleError (/path/to/node_modules/npm-package-json-lint/src/cli.js:28:9)
    at Object.<anonymous> (/path/to/node_modules/npm-package-json-lint/src/cli.js:126:3)
    at Module._compile (module.js:573:30)
    at Object.Module._extensions..js (module.js:584:10)
    at Module.load (module.js:507:32)
    at tryModuleLoad (module.js:470:12)
    at Function.Module._load (module.js:462:3)
    at Function.Module.runMain (module.js:609:10)
    at startup (bootstrap_node.js:158:16)
    at bootstrap_node.js:598:3
  • What you expected to happen
    Not throw error.
  • The steps to reproduce the problem
  1. Create npmpackagejsonlint.config.js with prefer-property-order rule.
module.exports = {
  rules: {
    "prefer-property-order": ["error", [
      "name",
      "version",
      "description",
      "keywords",
      "homepage",
      "bugs",
      "license",
      "author",
      "contributors",
      "files",
      "main",
      "jsnext:main",
      "bin",
      "man",
      "directories",
      "repository",
      "scripts",
      "config",
      "dependencies",
      "devDependencies",
      "peerDependencies",
      "bundleDependencies",
      "bundledDependencies",
      "optionalDependencies",
      "engines",
      "engineStrict",
      "os",
      "cpu",
      "preferGlobal",
      "private",
      "publishConfig"
    ]]
  }
};
  1. Create package.json.
{
  "name": "test",
  "version": "0.0.4",
  "description": "test"
}

API don't respect `extend`

When reporting a bug, please include:

  • A little info about your environment
    • npm-package-json-lint version 3.0.0
    • npm version 6.0.0
    • node version 10.0.0
  • The output from npm-package-json-lint
    Output error only which in configuration list without rules in extend.
  • What you expected to happen
    Respect extends in api
  • The steps to reproduce the problem
    new NpmPackageJsonLint().lint(
      packageJsonData, 
      ThisVariableAcceptOnlyArrayOfRulesButShouldAcceptConfigAndRespectExtends
    );

In 2 version all works good and as expected. Thanks!

[perhaps a Feature Request] Custom rule

It may just be me, but...

I can't seem to find a way to include my own, custom rule (just like ESLint and TSLint provides). Granted, I could create a rule, and submit a pull request for it, but I may have a very domain specific rule, that I want to apply.

Is there already an option to do that.... if not, this can be considered a feature request 😄

Improvement: running lint programatically

Hello,

thanks for the linter!
It would be awesome to have a Node.js API to use linter programmatically. The part in cli.js could be abstracted and exported for programmatic usage similarly as ESLint does with its CLIEngine

Missing properties on `prefer-property-order` has unexpected behavour

My package.json has the property nyc which is not included on the default order list at:

{
  "rules": {
    "prefer-property-order": ["error", []]
  }
}

This rule is failing with the following error:

Your package.json properties are not in the desired order. nyc is not in the preferred property list.

I think that prefer-property-order should ignore properties that are not in the preferred property list.

Windows compatibility

In Windows environments, the following error is thrown:

 "wp-scripts lint-pkg-json" found some errors. Please fix them and try committing again.
Pattern, [...]\plugins\gutenberg\packages\wordcount\package.json, is a file, but isn't a package.json file.

Looking at the source for where the error is thrown, it's expected this could be an issue with the path separator differences in Windows environments:

if (resolvedPath.endsWith('/package.json')) {

See also:

Context:

Our configuration, including defined dependency links, can be found at https://github.com/WordPress/gutenberg/tree/master/packages/npm-package-json-lint-config

Allow specifying values for private

We have a monorepo for our engineering team. We have a setup inspired by babel, react and others, where lots of npm packages live in a single repo. For all of those, we need to ensure that private is always set to true in the package.json. Is this something this tool could do?

bundledDependencies-type: should be an Array

"bundledDependencies" should be an Array.
But it is treated as an Object.

Quoted from the wiki page of "bundledDependencies-type":

Enabling this rule will result in an error being generated if the value in bundledDependencies is not an object.

https://github.com/tclindner/npm-package-json-lint/wiki/bundledDependencies-type

Quoted from the document page of package.json:

bundledDependencies

This defines an array of package names that will be bundled when publishing the package.

In cases where you need to preserve npm packages locally or have them available through a single file download, you can bundle the packages in a tarball file by specifying the package names in the bundledDependencies array and executing npm pack.

For example:

If we define a package.json like this:

{
  "name": "awesome-web-framework",
  "version": "1.0.0",
  "bundledDependencies": [
    "renderized", "super-streams"
  ]
}

https://docs.npmjs.com/files/package.json#bundleddependencies


My environment

  • npm-package-json-lint version: 2.11.1
  • npm version: 5.6.0
  • node version: 8.9.4

The output from npm-package-json-lint

package.json

{
    "bundledDependencies": [
        "foo",
        "bar"
    ]
}

.npmpackagejsonlintrc

{
    "rules": {
        "bundledDependencies-type": "error"
    }
}

Output

1 error
✖ bundledDependencies-type - node: bundledDependencies - Type should be an Object

Support `--ignore-path` for CLI

I remove template because it is not bug, it is feature. stylelint/eslint/etc linters have --ignore-path CLI option for ignoring paths, example i have project where use php and nodejs, php use composer as package manager and store all dependencies in vendor directory and some packages contains package.json, i want ignore vendor directory.

I use npmPkgJsonLint --quiet . command for linting.

Also it is speedup glob (and linting too), because repo can contains a lot of directory and files which are not included in git. Will be great support npmPkgJsonLint --quiet . --ignore-path .gitignore. I can send a PR.

Drop support for Node v6 and v7

Bump the following dependencies

  • is-plain-obj to 2.x.x
  • log-symbols to 3.x.x
  • figures to 3.x.x
  • strip-json-comments to 3.x.x
  • node-semver to 6.x.x

Add an --init option to the cli

Background #40

Add a new option to the cli that guides users through the process of create a configuration object for npm-package-json-lint.

Misleading instructions at role `prefer-property-order`

My package.json look like this:

{
  "name": "foo",
  "version": "1.2.3",
  "main": "index.js",
  "repository": "https://github.com/foo/bar",
  "bugs": "https://github.com/foo/bar/issues"
}

With the default ordering bugs should be after version but the message I get is:

Your package.json properties are not in the desired order. Please move bugs before repository.

If I will put bugs before repository I will get:

Your package.json properties are not in the desired order. Please move bugs before main.

I think that better instructions will be (notice the quotes I added also):

Your package.json properties are not in the desired order. Please move "bugs" after "version".

My version is: 2.8.2

Improve rule loader support for array type rules

npm-package-json-lint has two types of rules. The first type allows users to set their severity level (i.e. off, warning, and error). The second type allows users to pass an array of values with the severity level. Currently, the rules loader is not coded in a way that scales for varying types of array based rules. The goal of this issue is to improve that process and prevent future issues like #53.

FYI @evilebottnawi

v3 not reading configuration from `package.json`

  • A little info about your environment
    • npm-package-json-lint version - v3 via npx -p npm-package-json-lint@beta -c "npmPkgJsonLint ."
    • npm version - 6.0.0
    • node version - 8.11.1
  • The output from npm-package-json-lint
  • What you expected to happen
  • The steps to reproduce the problem

In a .npmpackagejsonlintrc.json file in the root of my repo I had:

{
	"rules": {
		"require-publishConfig": "error",
		"valid-values-author": ["error", [
			"My Name"
		]]
	}
}

The output from the above:

❯ npx -p npm-package-json-lint@beta -c "npmPkgJsonLint . -c .npmpackagejsonlintrc.json"
npx: installed 81 in 4.136s

./package.json
✖ require-publishConfig - node: publishConfig - publishConfig is required
1 error
0 warnings

./packages/package1/package.json
✖ require-publishConfig - node: publishConfig - publishConfig is required
✖ valid-values-author - node: author - Invalid value for author
2 errors
0 warnings

./packages/package2/package.json
✖ require-publishConfig - node: publishConfig - publishConfig is required
✖ valid-values-author - node: author - Invalid value for author
2 errors
0 warnings

I then copied the above (and deleted the .npmpackagejsonlintrc.json file) to my package.json:

	"npmPackageJsonLintConfig": {
		"rules": {
			"require-publishConfig": "error",
			"valid-values-author": ["error", [
				"My Name"
			]]
		}
	},

When I run npx -p npm-package-json-lint@beta -c "npmPkgJsonLint ." I get the following result:

npx: installed 81 in 4.315s
No npm-package-json-lint configuration found.
./packages/package1/package.json

I expected using the above command that npmPkgJsonLint would load the config that is now in my package.json file.

More helpful default configuration

Ay, npm-package-json-lint should really report type screwups in package.json for any of the keys.

The engine presence check should also be enabled by default. It sucks when a Node.js project fails to document which version of Node.js is required to run it.

If name is missing, things are likely to break with npm. That should be on by default. Same goes for version.

New Rule: Indentation Validation

It would be great to have an indentation rule.

Our repo uses tabs for indentation in all JSON files including package.json

(npm added/fixed support for tabbed indentaion in the 5.x releases)

Turns out, whilst creating our npm-package-json-lint shared config I used spaces instead of tabs 🤦‍♂️

Having a rule to detect, and enforce the correct indentation type would be awesome

ESLint use this configuration for their indent rule:

For example, for 2-space indentation:

{
    "indent": ["error", 2]
}

Or for tabbed indentation:

{
    "indent": ["error", "tab"]
}

No configuration found when installed with pnpm

I installed npm-package-json-lint-config-default and created the config file from it's installation instructions, but it says it can't find the config. When pointing it to the config with -c .npmpackagejsonlintrc.json it does work.

When reporting a bug, please include:

  • A little info about your environment
    • npm-package-json-lint version: 2.0.0
    • npm version: pnpm version: 3.6.1
    • node version: v10.15.3
  • The output from npm-package-json-lint:
$ npx npmPkgJsonLint .
No npm-package-json-lint configuration found.
./package.json
  • What you expected to happen
    package.json gets checked.

Reduce package size

Package contains unnecessary directories and files - grunt, tests, .jscsrc and maybe others. I can do PR if your accept this issue.

feature suggestion: support exceptions for the "prefer-...-dependencies" rules

I use rules like prefer-caret-version-dependencies. However, sometimes a dependency has a problem that requires me to specify a version range that cannot be represented with a caret version.

Looking at the documentation, I cannot see a way currently to specify exceptions to the rule. Either all dependencies are checked and if any of them don't use the caret syntax, I get an error. Or I have to turn off the rule or make it a warning. But a warning is not really the level of forcefulness I want. It is too easy to miss a warning.

improvement: possibility to use glob

Hello everybody :)
first of thanks for your work, i just found it and its awesome!

I want to ask if there is a possibility to add a glob pattern option, because i got a lerna-monorepo, like babel does.

Or for the beginning maybe the possibility to add multiple -f {path}-arguments to a single command.

But of course globbing would make it a lot more useful in scenarios like:

  • scan whole project repo
  • lerna setup (my scenario)
  • usage of lint-staged (also my scenario)
  • usage with CI tools

Some rules not respected configuration

I have config for some rules:

{
    "rules": {
        "valid-values-author": "off",
        "valid-values-private": "off",
        "valid-values-license": "off"
    }
}

But I still get a output about a warning:

----warnings-----
valid-values-author - node: author - Invalid value for author
valid-values-private - node: private - Invalid value for private
valid-values-license - node: license - Invalid value for license

Can't use an object as `author`with `valid-values-author`

When reporting a bug, please include:

  • A little info about your environment
    • npm-package-json-lint version: 2.11.0
    • yarn version: 1.3.2
    • node version: 6.10.0
  • The output from npm-package-json-lint
1 error
✖ valid-values-author - node: author - Invalid value for author
  • What you expected to happen
    No errors
  • The steps to reproduce the problem
    Use a package.json with author like the following:
author: {
  "name": "Joe Bloggs",
  "url": "https://example.com"
}

New Rule: Description Validation

A rule to validate description format.

It was mentioned WordPress/gutenberg#8121 (comment) that it would be great to have a rule to ensure that a description ended with a . period:

e.g. My package description. rather than My package description

Another possability would be to ensure that the description started with a capital letter:

e.g. My package description. rather than my package description

Support for entires order?

I wonder if there is support for entries ordering such as: First name then description etc..

I would like it to have default ordering and if I want I can reorder it by given an array of entries.

Create a Jest "runner"

Jest has the option to support custom "runners"

A couple of examples:
https://www.npmjs.com/package/jest-runner-eslint
https://www.npmjs.com/package/jest-runner-stylelint

Each of the above (and others) utilise this library:
https://www.npmjs.com/package/create-jest-runner

It would be great to have a npm-package-json-lint "runner" for jest
• e.g. https://www.npmjs.com/package/jest-runner-npm-package-json-lint

Happy to help work on this, though maybe waiting on any issues in #82 to be resolved first.

p.s. @evilebottnawi I'd like to add this to @stylelint/jest-preset-stylelint, what do you think?

Add `--fix` flag

It would be nice if there were a --fix flag, similar to tools like eslint, which handles fixable errors in a project's package.json. From what I can see, the rules that could be fixable include: prefer-property-order and the prefer-alphabetical-* rules.

prefer-property-order is particularly annoying as it typically involves running pjl-cli over and over again until the desired order is met.

Could this be achieved simply by adding a new fix property to each rule that is fixable and invoke it if the --fix flag is passed in?

Quiet option for cli

I have CI and will be awesome to avoid output in console using quite option. BTW, standard behavior many linters not output nothing if this not contain error. warning, deprecated and etc.

`no-caret-version-dependencies` does not work with multiple dependencies

I'm using this in an angular 5.2 project, node 8.12. Library version 3.4.0

When specifying the no-caret-version-dependencies to 'error' it will only error out when there is only one dependency. With multiple dependencies, it always returns true. This behavior seems to be verified with unit tests. I changed the following in no-caret-version-dependencies.test.js

  context('when package.json has node with an invalid value', function() {
    it('LintIssue object should be returned', function() {
      const packageJsonData = {
        dependencies: {
          'npm-package-json-lint': '^1.0.0'
        }
      };
      const response = lint(packageJsonData, 'error');

      response.lintId.should.equal('no-caret-version-dependencies');
      response.severity.should.equal('error');
      response.node.should.equal('dependencies');
      response.lintMessage.should.equal('You are using an invalid version range. Please do not use ^.');
    });
  });

to

  context('when package.json has node with an invalid value', function() {
    it('LintIssue object should be returned', function() {
      const packageJsonData = {
        dependencies: {
          'npm-package-json-lint': '^1.0.0',
          'foo': '1.2.3'
        }
      };
      const response = lint(packageJsonData, 'error');

      response.lintId.should.equal('no-caret-version-dependencies');
      response.severity.should.equal('error');
      response.node.should.equal('dependencies');
      response.lintMessage.should.equal('You are using an invalid version range. Please do not use ^.');
    });
  });

and get a failing test. It seems like there might be an error in dependency-audit.js:areVersRangesValid, but I can't really see why.

Support overrides

It would be great to have support for an overrides field in the config file, just like ESLint has. This could be especially useful for monorepos.

{
  "overrides": {
    "files": ["./package.json", "./packages/package1/package.json"],
    "rules": {
      "require-homepage": "off"
    }
  }
}

Any plans to support this? Ready to help.

New Rule: Engines Validation

It would be great to have a valid-values-engines rule to validate and enfore specific Node.js and/or npm versions, ideally support valid SemVer versioning.


"engines": {
  "node": "8.9.3",
  "npm": "6.1.0"
},

Feat: "script-type"

Right now this validates valid cases where the individual script is not a string.

Include git dependencies in version linting

With Github and Gitlab (there might be more) you can depend on a git URL in package.json like so:

"mydep": "git+ssh://[email protected]:internalapps/mydep.git"

However, the version is optional and at my org I want to ensure that a version is included like so for commit id:

"mydep": "git+ssh://[email protected]:internalapps/mydep.git#500546a"

or string for a tag or branch name

"mydep": "git+ssh://[email protected]:internalapps/mydep.git#v0.1.1"

I think just ensuring that .git isn't at the end of the value could be enough but I haven't done much testing. ..+\.git#.+ could work too. Let me know if you think this could be an addition :)

name-scope-format & name-folder-format

Please add name-scope-format
Example: @scope/name

  1. Forces @scope/ to be before name
  2. Forces scope and name to be lowercase

Please add name-folder-format

  1. Require name to be the name of the folder that package.json is in
  2. Require folder and name to be lowercase
  3. Be compatible with name-scope-format (see above)

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.