npm-package-json-lint 6.2.0 → 6.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api.js +1 -1
- package/dist/api.js.map +2 -2
- package/dist/cli.js +4 -4
- package/dist/cli.js.map +2 -2
- package/dist/rules/bin-type.js +1 -1
- package/dist/rules/bundledDependencies-type.js +1 -1
- package/dist/rules/config-type.js +1 -1
- package/dist/rules/cpu-type.js +1 -1
- package/dist/rules/dependencies-type.js +1 -1
- package/dist/rules/description-format.js +1 -1
- package/dist/rules/description-type.js +1 -1
- package/dist/rules/devDependencies-type.js +1 -1
- package/dist/rules/directories-type.js +1 -1
- package/dist/rules/engines-type.js +1 -1
- package/dist/rules/files-type.js +1 -1
- package/dist/rules/homepage-type.js +1 -1
- package/dist/rules/keywords-type.js +1 -1
- package/dist/rules/license-type.js +1 -1
- package/dist/rules/main-type.js +1 -1
- package/dist/rules/man-type.js +1 -1
- package/dist/rules/name-format.js +1 -1
- package/dist/rules/name-type.js +1 -1
- package/dist/rules/no-absolute-version-dependencies.js +1 -1
- package/dist/rules/no-absolute-version-devDependencies.js +1 -1
- package/dist/rules/no-archive-dependencies.js +1 -1
- package/dist/rules/no-archive-devDependencies.js +1 -1
- package/dist/rules/no-caret-version-dependencies.js +1 -1
- package/dist/rules/no-caret-version-devDependencies.js +1 -1
- package/dist/rules/no-duplicate-properties.js +1 -1
- package/dist/rules/no-file-dependencies.js +1 -1
- package/dist/rules/no-file-devDependencies.js +1 -1
- package/dist/rules/no-git-dependencies.js +1 -1
- package/dist/rules/no-git-devDependencies.js +1 -1
- package/dist/rules/no-repeated-dependencies.js +1 -1
- package/dist/rules/no-restricted-dependencies.js +1 -1
- package/dist/rules/no-restricted-devDependencies.js +1 -1
- package/dist/rules/no-restricted-pre-release-dependencies.js +1 -1
- package/dist/rules/no-restricted-pre-release-devDependencies.js +1 -1
- package/dist/rules/no-tilde-version-dependencies.js +1 -1
- package/dist/rules/no-tilde-version-devDependencies.js +1 -1
- package/dist/rules/optionalDependencies-type.js +1 -1
- package/dist/rules/os-type.js +1 -1
- package/dist/rules/peerDependencies-type.js +1 -1
- package/dist/rules/prefer-absolute-version-dependencies.js +1 -1
- package/dist/rules/prefer-absolute-version-devDependencies.js +1 -1
- package/dist/rules/prefer-alphabetical-bundledDependencies.js +1 -1
- package/dist/rules/prefer-alphabetical-dependencies.js +1 -1
- package/dist/rules/prefer-alphabetical-devDependencies.js +1 -1
- package/dist/rules/prefer-alphabetical-optionalDependencies.js +1 -1
- package/dist/rules/prefer-alphabetical-peerDependencies.js +1 -1
- package/dist/rules/prefer-alphabetical-scripts.js +1 -1
- package/dist/rules/prefer-caret-version-dependencies.js +1 -1
- package/dist/rules/prefer-caret-version-devDependencies.js +1 -1
- package/dist/rules/prefer-no-contributors.js +1 -1
- package/dist/rules/prefer-no-dependencies.js +1 -1
- package/dist/rules/prefer-no-devDependencies.js +1 -1
- package/dist/rules/prefer-no-engineStrict.js +1 -1
- package/dist/rules/prefer-no-optionalDependencies.js +1 -1
- package/dist/rules/prefer-no-peerDependencies.js +1 -1
- package/dist/rules/prefer-no-version-zero-dependencies.js +1 -1
- package/dist/rules/prefer-no-version-zero-devDependencies.js +1 -1
- package/dist/rules/prefer-property-order.js +1 -1
- package/dist/rules/prefer-scripts.js +1 -1
- package/dist/rules/prefer-tilde-version-dependencies.js +1 -1
- package/dist/rules/prefer-tilde-version-devDependencies.js +1 -1
- package/dist/rules/preferGlobal-type.js +1 -1
- package/dist/rules/private-type.js +1 -1
- package/dist/rules/repository-type.js +1 -1
- package/dist/rules/require-author.js +1 -1
- package/dist/rules/require-bin.js +1 -1
- package/dist/rules/require-bugs.js +1 -1
- package/dist/rules/require-bundledDependencies.js +1 -1
- package/dist/rules/require-config.js +1 -1
- package/dist/rules/require-contributors.js +1 -1
- package/dist/rules/require-cpu.js +1 -1
- package/dist/rules/require-dependencies.js +1 -1
- package/dist/rules/require-description.js +1 -1
- package/dist/rules/require-devDependencies.js +1 -1
- package/dist/rules/require-directories.js +1 -1
- package/dist/rules/require-engines.js +1 -1
- package/dist/rules/require-files.js +1 -1
- package/dist/rules/require-funding.js +1 -1
- package/dist/rules/require-homepage.js +1 -1
- package/dist/rules/require-keywords.js +1 -1
- package/dist/rules/require-license.js +1 -1
- package/dist/rules/require-main.js +1 -1
- package/dist/rules/require-man.js +1 -1
- package/dist/rules/require-module.js +1 -1
- package/dist/rules/require-name.js +1 -1
- package/dist/rules/require-optionalDependencies.js +1 -1
- package/dist/rules/require-os.js +1 -1
- package/dist/rules/require-peerDependencies.js +1 -1
- package/dist/rules/require-preferGlobal.js +1 -1
- package/dist/rules/require-private.js +1 -1
- package/dist/rules/require-publishConfig.js +1 -1
- package/dist/rules/require-repository-directory.js +1 -1
- package/dist/rules/require-repository.js +1 -1
- package/dist/rules/require-scripts.js +1 -1
- package/dist/rules/require-types.js +1 -1
- package/dist/rules/require-typings.js +1 -1
- package/dist/rules/require-version.js +1 -1
- package/dist/rules/scripts-type.js +1 -1
- package/dist/rules/valid-values-author.js +1 -1
- package/dist/rules/valid-values-engines.js +1 -1
- package/dist/rules/valid-values-license.js +1 -1
- package/dist/rules/valid-values-name-scope.js +1 -1
- package/dist/rules/valid-values-private.js +1 -1
- package/dist/rules/valid-values-publishConfig.js +1 -1
- package/dist/rules/version-format.js +1 -1
- package/dist/rules/version-type.js +1 -1
- package/dist/src/validators/dependency-audit.d.ts +95 -48
- package/package.json +1 -1
package/dist/api.js
CHANGED
|
@@ -5,5 +5,5 @@ ${s.message}`;throw typeof n=="string"?new Error(`${n}:
|
|
|
5
5
|
Error: ${e.message}`)},Ye=Symbol("JSON source"),F=t=>{let e={},r="";try{r=We(t),e=JSON.parse((0,ie.default)(r))}catch(n){ae(t,n)}return Object.defineProperty(e,Ye,{value:r,enumerable:!1,writable:!1,configurable:!1}),e},le=t=>{let e={};try{e=Ge(t)}catch(r){ae(t,r)}return e};var q=require("debug")("npm-package-json-lint:applyExtendsIfSpecified"),ce=(t,e,r)=>{let n=t.extends;return Array.isArray(t.extends)||(n=[t.extends]),n.reduceRight((s,o)=>{try{let i=ze(o,r),a=p(p({},i),s),l=p(p({},i.rules),s.rules),c=Array.isArray(i.plugins)?i.plugins:[],d=Array.isArray(s.plugins)?s.plugins:[],y=[...c,...d],w=[...new Set(y)],L=Array.isArray(i.overrides)?i.overrides:[],Ie=Array.isArray(s.overrides)?s.overrides:[],z=[...L,...Ie];return a.rules=l,y.length>0&&(a.plugins=w),z.length>0&&(a.overrides=z),a}catch(i){throw i.message+=`
|
|
6
6
|
Referenced from: ${e}`,i}},t)},ze=(t,e)=>{let r={},n=t;if(t.startsWith("./"))n=I.default.join(process.cwd(),t),r=Ke(n);else{let s=require.resolve(n,{paths:[I.default.dirname(e)]});r=require(s)}return Object.keys(r).length>0&&r.extends&&(r=ce(r,n,e)),r},Ke=t=>{let e={};switch(I.default.extname(t)){case".js":e=le(t);break;case".json":e=F(t);break;default:throw new Error(`Unsupport config file extension. File path: ${t}`)}return e},E=(t,e)=>{let r=p({},t);return q("Loading extends, if applicable"),(r==null?void 0:r.hasOwnProperty("extends"))&&r.extends&&(q("extends property present, applying."),r=ce(r,e,e)),q("Loading extends complete"),r};var ge=g(require("path")),ue=g(require("globby")),v=require("debug")("npm-package-json-lint:applyOverrides"),P=(t,e,r,n)=>{let s=p({},r);return v("overrides"),v(n),n&&n.forEach(o=>{let a=o.patterns.filter(c=>c.length).map(c=>c.endsWith("/package.json")?c:`${c}/package.json`),l=ue.default.sync(a,{cwd:t,gitignore:!0});v("globFiles"),v(l),l.forEach(c=>{let d=ge.default.resolve(t,c);e===d&&(s=p(p({},s),o.rules))})}),v("finalRules"),v(s),s};var h=require("debug")("npm-package-json-lint:cosmicConfigTransformer"),V=(t,e,r)=>(h(`cwd: ${t}`),h("configBaseDirectory"),h(e),n=>{if(h("cosmiconfigResult"),h(n),!n)return null;let{config:s,filepath:o}=n;h("cosmiconfigResult.config"),h(s),h("cosmiconfigResult.filepath"),h(o);let i=e||pe.default.dirname(o||""),a=p({},s),l=E(a,r);return P(t,r,l.rules,l.overrides)});var m=require("debug")("npm-package-json-lint:Config"),Qe=0,T=class{constructor(e,r,n,s,o){r&&(this.config=E(r,"PassedConfig")),this.cwd=e,this.configFile=n,this.configBaseDirectory=s,this.rules=o}getConfigForFile(e){m(`Getting config for ${e}`);let r=e;m(`filePathToSearch: ${r}`);let n;if(typeof this.config>"u")m("User passed config is undefined."),this.configFile?(m("Config file specified, loading it."),n=(0,M.cosmiconfigSync)("npmpackagejsonlint",{transform:V(this.cwd,this.configBaseDirectory,e)}).load(this.configFile)):(m("Config file wasn't specified, searching for config."),n=(0,M.cosmiconfigSync)("npmpackagejsonlint",{transform:V(this.cwd,this.configBaseDirectory,r)}).search(r));else{m("User passed config is set, using it.");let s=this.config;m(`Applying overrides to config for ${e}`),n=P(this.cwd,e,s.rules,s.overrides),m(`Overrides applied for ${e}`)}if(!n)throw new Error(`No npm-package-json-lint configuration found.
|
|
7
7
|
${r}`);if(Object.keys(n).length===Qe)throw new Error(`No rules specified in configuration.
|
|
8
|
-
${r}`);return m(`Overrides applied for ${e}`),m("Final Config"),m(n),se(n,"cli",this.rules),n}};var me=g(require("chalk")),de=require("fs"),N=g(require("path")),O=class{constructor(){this.rules={}}load(){let e=N.default.join(__dirname,"rules");try{return(0,de.readdirSync)(e).forEach(r=>{let o=r.slice(0,-3),i=N.default.join(e,r);this.registerRule(o,i)}),this.rules}catch(r){throw new Error(`Error while loading rules from rules directory - ${r.message}`)}}get(e){if(typeof this.rules[e]>"u"){let s=`Rule, ${e}, is invalid. Please ensure it matches a valid option.`;throw new Error(me.default.bold.red(s))}return require(this.rules[e])}getRules(){return this.rules}registerRule(e,r){this.rules[e]=r}};var j=g(require("path"));var b=(n=>(n.Error="error",n.Warning="warning",n.Off="off",n))(b||{});var fe=t=>t.reduce((r,n)=>{let s=n.severity==="error",o=s?r.errorCount+1:r.errorCount,i=s?r.warningCount:r.warningCount+1;return{errorCount:o,warningCount:i}},{errorCount:0,warningCount:0}),D=t=>t.reduce((e,r)=>({ignoreCount:r.ignored?e.ignoreCount+1:e.ignoreCount,errorCount:e.errorCount+r.errorCount,warningCount:e.warningCount+r.warningCount}),{ignoreCount:0,errorCount:0,warningCount:0});var u=require("debug")("npm-package-json-lint:linter"),_=t=>{let{cwd:e,fileName:r,ignored:n,issues:s,errorCount:o,warningCount:i}=t;return{filePath:`./${j.default.relative(e,r)}`,issues:s,ignored:n,errorCount:o,warningCount:i}},Xe=(t,e,r)=>{let n=[];for(let s in e){let o=r.get(s),i="off",a;if(o.ruleType==="array"||o.ruleType==="object"?(i=typeof e[s]=="string"&&e[s]==="off"?e[s]:e[s][0],a=typeof e[s]=="string"?{}:e[s][1]):o.ruleType==="optionalObject"?typeof e[s]=="string"?(i=e[s],a={}):(i=e[s][0],a=e[s][1]):i=e[s],i!=="off"){let l=o.lint(t,i,a);l!==null&&n.push(l)}}return n},ye=(t,e,r,n,s)=>{let o=Xe(e,r,s),i=fe(o);return _({cwd:t,fileName:n,ignored:!1,issues:o,errorCount:i.errorCount,warningCount:i.warningCount})},Ze=(t,e,r,n)=>{let s=F(j.default.resolve(e));return ye(t,s,r,e,n)},he=t=>{let{cwd:e,packageJsonObject:r,filename:n,ignorer:s,configHelper:o,rules:i}=t;u("executing on package.json object");let a=[],l=n||"",c=j.default.isAbsolute(l)?l:j.default.resolve(e,l),d=j.default.relative(e,c);if(s.ignores(d)){u(`Ignored: ${d}`);let w=_({cwd:e,fileName:c,ignored:!0,issues:[],errorCount:0,warningCount:0});a.push(w)}else{u(`Getting config for ${c}`);let w=o.getConfigForFile(c);u(`Config fetched for ${c}`);let L=ye(e,r,w,c,i);a.push(L)}u("Aggregating overall counts");let y=D(a);return u("stats"),u(y),{results:a,ignoreCount:y.ignoreCount,errorCount:y.errorCount,warningCount:y.warningCount}},be=t=>{let{cwd:e,fileList:r,ignorer:n,configHelper:s,rules:o}=t;u("executing on package.json files");let i=r.map(l=>{let c=j.default.relative(e,l);if(n.ignores(c))return u(`Ignored: ${c}`),_({cwd:e,fileName:l,ignored:!0,issues:[],errorCount:0,warningCount:0});u(`Getting config for ${l}`);let d=s.getConfigForFile(l);return u(`Config fetched for ${l}`),Ze(e,l,d,o)});u("Aggregating overall counts");let a=D(i);return u("stats"),u(a),{results:i,ignoreCount:a.ignoreCount,errorCount:a.errorCount,warningCount:a.warningCount}};var je=g(require("path")),ve=g(require("globby")),f=require("debug")("npm-package-json-lint:getFileList"),we=(t,e)=>{f("patterns"),f(t);let r=t.filter(a=>a.length);f("filteredPatterns"),f(r);let n=r.map(a=>a.endsWith("/package.json")?a:`${a}/**/package.json`);n.push("!**/node_modules/**"),f("globPatterns"),f(n);let s=[],o=new Set,i=ve.default.sync(n,{cwd:e,gitignore:!0});return f("globFiles"),f(i),i.forEach(a=>{let l=je.default.resolve(e,a);o.has(l)||(o.add(l),s.push(l))}),f("Final file list from `getFileList`"),f(s),s};var xe=g(require("fs")),B=g(require("path")),ke=g(require("ignore")),H=require("debug")("npm-package-json-lint:getIgnorer"),et=".npmpackagejsonlintignore",tt="ENOENT",Oe=(t,e)=>{let r=e||et;H(`ignoreFilePath: ${r}`);let n=B.default.isAbsolute(r)?r:B.default.resolve(t,r);H(`absoluteIgnoreFilePath: ${n}`);let s="";try{s=xe.default.readFileSync(n,"utf8")}catch(o){if(o.code!==tt)throw o}return H("Ignore text added"),(0,ke.default)().add(s)};var J=require("debug")("npm-package-json-lint:NpmPackageJsonLint"),nt=Ce(),st=0,ot=t=>t.severity==="error",Re=t=>(0,Fe.default)(t),it=(t,e)=>!e&&!Re(t)||e&&(t||Re(t)),at=t=>{let e=[];return t.forEach(r=>{let n=r.issues.filter(ot);if(n.length>st){let s={issues:n,errorCount:n.length,warningCount:0};e.push(Object.assign(r,s))}}),e},G=class{constructor(e){let{cwd:r,packageJsonObject:n,packageJsonFilePath:s,config:o,configFile:i,configBaseDirectory:a,patterns:l,quiet:c,ignorePath:d,fix:y}=e;this.cwd=(0,U.default)(r||process.cwd()),this.packageJsonObject=n,this.packageJsonFilePath=s&&(0,U.default)(s),this.patterns=l,this.quiet=c||!1,this.ignorePath=d||"",this.fix=y||!1,this.version=nt.version,this.rules=new O,this.rules.load(),this.configHelper=new T(this.cwd,o,i,a,this.rules)}lint(){if(J("Starting lint"),it(this.packageJsonObject,this.patterns))throw new Error("You must pass npm-package-json-lint a `patterns` glob or a `packageJsonObject` string, though not both.");let e=Oe(this.cwd,this.ignorePath),r;if(this.patterns){if(J("Linting using patterns"),!Array.isArray(this.patterns))throw new TypeError("Patterns must be an array.");let n=we(this.patterns,this.cwd);r=be({cwd:this.cwd,fileList:n,ignorer:e,configHelper:this.configHelper,rules:this.rules})}else J("Linting using passed object."),r=he({cwd:this.cwd,packageJsonObject:this.packageJsonObject,ignorer:e,filename:this.packageJsonFilePath,configHelper:this.configHelper,rules:this.rules});return this.quiet?{results:at(r.results),ignoreCount:r.ignoreCount,errorCount:r.errorCount,warningCount:r.warningCount}:(J("lint complete"),r)}};var C=g(require("chalk")),W=g(require("log-symbols"));var Y=class{constructor(e,r,n,s){this.lintId=e,this.severity=r,this.node=n,this.lintMessage=s}toString(){let e=this.severity==="error"?W.default.error:W.default.warning,r=C.default.
|
|
8
|
+
${r}`);return m(`Overrides applied for ${e}`),m("Final Config"),m(n),se(n,"cli",this.rules),n}};var me=g(require("chalk")),de=require("fs"),N=g(require("path")),O=class{constructor(){this.rules={}}load(){let e=N.default.join(__dirname,"rules");try{return(0,de.readdirSync)(e).forEach(r=>{let o=r.slice(0,-3),i=N.default.join(e,r);this.registerRule(o,i)}),this.rules}catch(r){throw new Error(`Error while loading rules from rules directory - ${r.message}`)}}get(e){if(typeof this.rules[e]>"u"){let s=`Rule, ${e}, is invalid. Please ensure it matches a valid option.`;throw new Error(me.default.bold.red(s))}return require(this.rules[e])}getRules(){return this.rules}registerRule(e,r){this.rules[e]=r}};var j=g(require("path"));var b=(n=>(n.Error="error",n.Warning="warning",n.Off="off",n))(b||{});var fe=t=>t.reduce((r,n)=>{let s=n.severity==="error",o=s?r.errorCount+1:r.errorCount,i=s?r.warningCount:r.warningCount+1;return{errorCount:o,warningCount:i}},{errorCount:0,warningCount:0}),D=t=>t.reduce((e,r)=>({ignoreCount:r.ignored?e.ignoreCount+1:e.ignoreCount,errorCount:e.errorCount+r.errorCount,warningCount:e.warningCount+r.warningCount}),{ignoreCount:0,errorCount:0,warningCount:0});var u=require("debug")("npm-package-json-lint:linter"),_=t=>{let{cwd:e,fileName:r,ignored:n,issues:s,errorCount:o,warningCount:i}=t;return{filePath:`./${j.default.relative(e,r)}`,issues:s,ignored:n,errorCount:o,warningCount:i}},Xe=(t,e,r)=>{let n=[];for(let s in e){let o=r.get(s),i="off",a;if(o.ruleType==="array"||o.ruleType==="object"?(i=typeof e[s]=="string"&&e[s]==="off"?e[s]:e[s][0],a=typeof e[s]=="string"?{}:e[s][1]):o.ruleType==="optionalObject"?typeof e[s]=="string"?(i=e[s],a={}):(i=e[s][0],a=e[s][1]):i=e[s],i!=="off"){let l=o.lint(t,i,a);l!==null&&n.push(l)}}return n},ye=(t,e,r,n,s)=>{let o=Xe(e,r,s),i=fe(o);return _({cwd:t,fileName:n,ignored:!1,issues:o,errorCount:i.errorCount,warningCount:i.warningCount})},Ze=(t,e,r,n)=>{let s=F(j.default.resolve(e));return ye(t,s,r,e,n)},he=t=>{let{cwd:e,packageJsonObject:r,filename:n,ignorer:s,configHelper:o,rules:i}=t;u("executing on package.json object");let a=[],l=n||"",c=j.default.isAbsolute(l)?l:j.default.resolve(e,l),d=j.default.relative(e,c);if(s.ignores(d)){u(`Ignored: ${d}`);let w=_({cwd:e,fileName:c,ignored:!0,issues:[],errorCount:0,warningCount:0});a.push(w)}else{u(`Getting config for ${c}`);let w=o.getConfigForFile(c);u(`Config fetched for ${c}`);let L=ye(e,r,w,c,i);a.push(L)}u("Aggregating overall counts");let y=D(a);return u("stats"),u(y),{results:a,ignoreCount:y.ignoreCount,errorCount:y.errorCount,warningCount:y.warningCount}},be=t=>{let{cwd:e,fileList:r,ignorer:n,configHelper:s,rules:o}=t;u("executing on package.json files");let i=r.map(l=>{let c=j.default.relative(e,l);if(n.ignores(c))return u(`Ignored: ${c}`),_({cwd:e,fileName:l,ignored:!0,issues:[],errorCount:0,warningCount:0});u(`Getting config for ${l}`);let d=s.getConfigForFile(l);return u(`Config fetched for ${l}`),Ze(e,l,d,o)});u("Aggregating overall counts");let a=D(i);return u("stats"),u(a),{results:i,ignoreCount:a.ignoreCount,errorCount:a.errorCount,warningCount:a.warningCount}};var je=g(require("path")),ve=g(require("globby")),f=require("debug")("npm-package-json-lint:getFileList"),we=(t,e)=>{f("patterns"),f(t);let r=t.filter(a=>a.length);f("filteredPatterns"),f(r);let n=r.map(a=>a.endsWith("/package.json")?a:`${a}/**/package.json`);n.push("!**/node_modules/**"),f("globPatterns"),f(n);let s=[],o=new Set,i=ve.default.sync(n,{cwd:e,gitignore:!0});return f("globFiles"),f(i),i.forEach(a=>{let l=je.default.resolve(e,a);o.has(l)||(o.add(l),s.push(l))}),f("Final file list from `getFileList`"),f(s),s};var xe=g(require("fs")),B=g(require("path")),ke=g(require("ignore")),H=require("debug")("npm-package-json-lint:getIgnorer"),et=".npmpackagejsonlintignore",tt="ENOENT",Oe=(t,e)=>{let r=e||et;H(`ignoreFilePath: ${r}`);let n=B.default.isAbsolute(r)?r:B.default.resolve(t,r);H(`absoluteIgnoreFilePath: ${n}`);let s="";try{s=xe.default.readFileSync(n,"utf8")}catch(o){if(o.code!==tt)throw o}return H("Ignore text added"),(0,ke.default)().add(s)};var J=require("debug")("npm-package-json-lint:NpmPackageJsonLint"),nt=Ce(),st=0,ot=t=>t.severity==="error",Re=t=>(0,Fe.default)(t),it=(t,e)=>!e&&!Re(t)||e&&(t||Re(t)),at=t=>{let e=[];return t.forEach(r=>{let n=r.issues.filter(ot);if(n.length>st){let s={issues:n,errorCount:n.length,warningCount:0};e.push(Object.assign(r,s))}}),e},G=class{constructor(e){let{cwd:r,packageJsonObject:n,packageJsonFilePath:s,config:o,configFile:i,configBaseDirectory:a,patterns:l,quiet:c,ignorePath:d,fix:y}=e;this.cwd=(0,U.default)(r||process.cwd()),this.packageJsonObject=n,this.packageJsonFilePath=s&&(0,U.default)(s),this.patterns=l,this.quiet=c||!1,this.ignorePath=d||"",this.fix=y||!1,this.version=nt.version,this.rules=new O,this.rules.load(),this.configHelper=new T(this.cwd,o,i,a,this.rules)}lint(){if(J("Starting lint"),it(this.packageJsonObject,this.patterns))throw new Error("You must pass npm-package-json-lint a `patterns` glob or a `packageJsonObject` string, though not both.");let e=Oe(this.cwd,this.ignorePath),r;if(this.patterns){if(J("Linting using patterns"),!Array.isArray(this.patterns))throw new TypeError("Patterns must be an array.");let n=we(this.patterns,this.cwd);r=be({cwd:this.cwd,fileList:n,ignorer:e,configHelper:this.configHelper,rules:this.rules})}else J("Linting using passed object."),r=he({cwd:this.cwd,packageJsonObject:this.packageJsonObject,ignorer:e,filename:this.packageJsonFilePath,configHelper:this.configHelper,rules:this.rules});return this.quiet?{results:at(r.results),ignoreCount:r.ignoreCount,errorCount:r.errorCount,warningCount:r.warningCount}:(J("lint complete"),r)}};var C=g(require("chalk")),W=g(require("log-symbols"));var Y=class{constructor(e,r,n,s){this.lintId=e,this.severity=r,this.node=n,this.lintMessage=s}toString(){let e=this.severity==="error"?W.default.error:W.default.warning,r=C.default.cyan.bold(this.lintId),n=C.default.magenta.bold(this.node),s=this.severity==="error"?C.default.red.bold(this.lintMessage):C.default.yellow(this.lintMessage);return`${e} ${r} - node: ${n} - ${s}`}};0&&(module.exports={LintIssue,NpmPackageJsonLint,Rules,Severity});
|
|
9
9
|
//# sourceMappingURL=api.js.map
|
package/dist/api.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/api.ts", "../src/npm-package-json-lint.ts", "../src/configuration.ts", "../src/config/ConfigSchema.ts", "../src/config/ConfigValidator.ts", "../src/config/cosmicConfigTransformer.ts", "../src/config/applyExtendsIfSpecified.ts", "../src/file-parser.ts", "../src/config/applyOverrides.ts", "../src/native-rules.ts", "../src/linter/linter.ts", "../src/types/severity.ts", "../src/linter/results-helper.ts", "../src/utils/getFileList.ts", "../src/utils/getIgnorer.ts", "../src/lint-issue.ts"],
|
|
4
|
-
"sourcesContent": ["export {NpmPackageJsonLint, NpmPackageJsonLintOptions} from './npm-package-json-lint';\n\nexport {LintIssue} from './lint-issue';\n\nexport {Severity} from './types/severity';\n\nexport {LinterResult} from './linter/linter';\n\nexport {PackageJsonFileLintingResult} from './types/package-json-linting-result';\n\nexport {PackageJsonFileAggregatedResultCounts, OverallAggregatedResultCounts} from './linter/results-helper';\n\nexport {Rules, Rule} from './native-rules';\n", "import isPlainObj from 'is-plain-obj';\nimport slash from 'slash';\nimport {PackageJson} from 'type-fest';\nimport {Config} from './configuration';\nimport {Rules} from './native-rules';\nimport {executeOnPackageJsonFiles, executeOnPackageJsonObject, OverallLintingResult} from './linter/linter';\nimport {getFileList} from './utils/getFileList';\nimport {getIgnorer} from './utils/getIgnorer';\nimport {Severity} from './types/severity';\nimport {PackageJsonFileLintingResult} from './types/package-json-linting-result';\nimport {LintIssue} from './lint-issue';\n\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst debug = require('debug')('npm-package-json-lint:NpmPackageJsonLint');\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst pkg = require('../package.json');\n\nconst noIssues = 0;\n\n/**\n * Checks if the given issue is an error issue.\n *\n * @param issue A {@link LintIssue} object\n * @returns True if error, false if warning.\n * @private\n */\nconst isIssueAnError = (issue: LintIssue): boolean => issue.severity === Severity.Error;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst isPackageJsonObjectValid = (packageJsonObject: PackageJson | any): boolean => isPlainObj(packageJsonObject);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst areRequiredOptionsValid = (packageJsonObject: PackageJson | any, patterns: string[]): boolean =>\n (!patterns && !isPackageJsonObjectValid(packageJsonObject)) ||\n (patterns && (packageJsonObject || isPackageJsonObjectValid(packageJsonObject)));\n\n/**\n * Filters results to only include errors.\n *\n * @param results The results to filter.\n * @returns The filtered results.\n */\nconst getErrorResults = (results: PackageJsonFileLintingResult[]): PackageJsonFileLintingResult[] => {\n const filtered = [];\n\n results.forEach((result) => {\n // eslint-disable-next-line unicorn/no-array-callback-reference\n const filteredIssues = result.issues.filter(isIssueAnError);\n\n if (filteredIssues.length > noIssues) {\n const filteredResult = {\n issues: filteredIssues,\n errorCount: filteredIssues.length,\n warningCount: 0,\n };\n\n filtered.push(Object.assign(result, filteredResult));\n }\n });\n\n return filtered;\n};\n\nexport interface NpmPackageJsonLintOptions {\n cwd?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n packageJsonObject?: any;\n packageJsonFilePath?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n config?: any;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n configFile?: any;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n configBaseDirectory?: any;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n patterns?: any;\n quiet?: boolean;\n ignorePath?: string;\n fix?: boolean;\n}\n\nexport class NpmPackageJsonLint {\n cwd: string;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n packageJsonObject: any;\n\n packageJsonFilePath: string;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n patterns: any;\n\n quiet: boolean;\n\n ignorePath: string;\n\n fix: boolean;\n\n version: string;\n\n rules: Rules;\n\n configHelper: Config;\n\n /**\n * constructor\n * @param options An instance of the {@link NpmPackageJsonLintOptions} options object.\n * @constructor\n */\n constructor(options: NpmPackageJsonLintOptions) {\n const {\n cwd,\n packageJsonObject,\n packageJsonFilePath,\n config,\n configFile,\n configBaseDirectory,\n patterns,\n quiet,\n ignorePath,\n fix,\n } = options;\n\n this.cwd = slash(cwd || process.cwd());\n\n this.packageJsonObject = packageJsonObject;\n this.packageJsonFilePath = packageJsonFilePath ? slash(packageJsonFilePath) : packageJsonFilePath;\n this.patterns = patterns;\n this.quiet = quiet || false;\n this.ignorePath = ignorePath || '';\n this.fix = fix || false;\n\n this.version = pkg.version;\n\n this.rules = new Rules();\n this.rules.load();\n\n this.configHelper = new Config(this.cwd, config, configFile, configBaseDirectory, this.rules);\n }\n\n /**\n * Runs the linter using the config specified in the constructor\n *\n * @returns The results {@link OverallLintingResult} from linting a collection of package.json files.\n */\n lint(): OverallLintingResult {\n debug('Starting lint');\n\n if (areRequiredOptionsValid(this.packageJsonObject, this.patterns)) {\n throw new Error(\n 'You must pass npm-package-json-lint a `patterns` glob or a `packageJsonObject` string, though not both.'\n );\n }\n\n const ignorer = getIgnorer(this.cwd, this.ignorePath);\n let linterOutput: OverallLintingResult;\n\n if (this.patterns) {\n debug('Linting using patterns');\n\n if (!Array.isArray(this.patterns)) {\n throw new TypeError('Patterns must be an array.');\n }\n\n const fileList = getFileList(this.patterns, this.cwd);\n\n linterOutput = executeOnPackageJsonFiles({\n cwd: this.cwd,\n fileList,\n ignorer,\n configHelper: this.configHelper,\n rules: this.rules,\n });\n } else {\n debug('Linting using passed object.');\n linterOutput = executeOnPackageJsonObject({\n cwd: this.cwd,\n packageJsonObject: this.packageJsonObject,\n ignorer,\n filename: this.packageJsonFilePath,\n configHelper: this.configHelper,\n rules: this.rules,\n });\n }\n\n if (this.quiet) {\n const errorsOnly = getErrorResults(linterOutput.results);\n\n return {\n results: errorsOnly,\n ignoreCount: linterOutput.ignoreCount,\n errorCount: linterOutput.errorCount,\n warningCount: linterOutput.warningCount,\n };\n }\n\n debug('lint complete');\n\n return linterOutput;\n }\n}\n", "import {cosmiconfigSync} from 'cosmiconfig';\nimport {validateRules} from './config/ConfigValidator';\nimport {transform} from './config/cosmicConfigTransformer';\nimport {applyExtendsIfSpecified} from './config/applyExtendsIfSpecified';\nimport {applyOverrides} from './config/applyOverrides';\nimport {Rules} from './native-rules';\n\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst debug = require('debug')('npm-package-json-lint:Config');\n\nconst noRules = 0;\n\n/**\n * Config class\n * @class\n */\nexport class Config {\n /**\n * The user passed config object.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n config: any;\n\n /**\n * The current working directory.\n */\n cwd: string;\n\n /**\n * The user passed configFile path.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n configFile: any;\n\n /**\n * The base directory that config should be pulled from.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n configBaseDirectory: any;\n\n /**\n * Rules object\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rules: any;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor(cwd: string, config: any, configFile: any, configBaseDirectory: any, rules: Rules) {\n if (config) {\n this.config = applyExtendsIfSpecified(config, 'PassedConfig');\n }\n\n this.cwd = cwd;\n this.configFile = configFile;\n this.configBaseDirectory = configBaseDirectory;\n this.rules = rules;\n }\n\n /**\n * Gets the config for a file.\n *\n * @param filePath File path of the file being linted.\n * @returns {Object} A config object.\n * @memberof Config\n */\n // eslint-disable-next-line @typescript-eslint/explicit-function-return-type\n getConfigForFile(filePath: string) {\n debug(`Getting config for ${filePath}`);\n const filePathToSearch = filePath;\n\n debug(`filePathToSearch: ${filePathToSearch}`);\n let config;\n\n if (typeof this.config === 'undefined') {\n debug(`User passed config is undefined.`);\n if (this.configFile) {\n debug(`Config file specified, loading it.`);\n config = cosmiconfigSync('npmpackagejsonlint', {\n transform: transform(this.cwd, this.configBaseDirectory, filePath),\n }).load(this.configFile);\n } else {\n debug(`Config file wasn't specified, searching for config.`);\n config = cosmiconfigSync('npmpackagejsonlint', {\n transform: transform(this.cwd, this.configBaseDirectory, filePathToSearch),\n }).search(filePathToSearch);\n }\n } else {\n debug(`User passed config is set, using it.`);\n const configBeforeOverrides = this.config;\n\n debug(`Applying overrides to config for ${filePath}`);\n config = applyOverrides(this.cwd, filePath, configBeforeOverrides.rules, configBeforeOverrides.overrides);\n\n debug(`Overrides applied for ${filePath}`);\n }\n\n if (!config) {\n throw new Error(`No npm-package-json-lint configuration found.\\n${filePathToSearch}`);\n }\n\n if (Object.keys(config).length === noRules) {\n throw new Error(`No rules specified in configuration.\\n${filePathToSearch}`);\n }\n\n debug(`Overrides applied for ${filePath}`);\n debug('Final Config');\n debug(config);\n\n validateRules(config, 'cli', this.rules);\n\n return config;\n }\n}\n", "import Ajv from 'ajv';\nimport ajvErrors from 'ajv-errors';\n\nconst ajv = new Ajv({allErrors: true, jsonPointers: true});\n\najvErrors(ajv);\n\n/**\n * Formats an array of schema validation errors.\n *\n * @param {Array} errors An array of error messages to format.\n * @returns {String} Formatted error message\n */\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nconst formatSchemaErrors = (errors) => errors.map((error) => `\\t- ${error.message}\\n`).join('');\n\nconst standardRuleSchema = {\n type: 'string',\n enum: ['off', 'warning', 'error'],\n errorMessage: {\n type: 'severity must be a string.',\n enum: 'severity must be either \"off\", \"warning\", or \"error\".',\n },\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst arrayRuleSchema = (minItems: any): any => ({\n type: 'array',\n items: [\n standardRuleSchema,\n {\n type: 'array',\n minItems,\n uniqueItems: true,\n errorMessage: {\n type: 'the second item in an array rule config must be an array.',\n minItems: 'the second item in an array rule config must have at least 1 item.',\n uniqueItems: 'the second item in an array rule config must have unique items.',\n },\n },\n ],\n minItems: 2,\n maxItems: 2,\n additionalItems: false,\n errorMessage: {\n type: 'rule config must be an array, e.g. [\"error\", [\"value1\", \"value2\"]].',\n minItems: 'array rules must have two items, severity and options array. e.g. [\"error\", [\"value1\", \"value2\"]].',\n maxItems: 'array rules must have two items, severity and options array. e.g. [\"error\", [\"value1\", \"value2\"]].',\n additionalItems:\n 'array rules are only allowed two items, severity and the list is values. e.g. [\"error\", [\"value1\", \"value2\"]].',\n },\n});\n\nconst objectRuleSchema = {\n type: 'array',\n items: [\n standardRuleSchema,\n {\n type: 'object',\n errorMessage: {\n type: 'the second item in an object rule config must be an object.',\n },\n },\n ],\n minItems: 2,\n maxItems: 2,\n additionalItems: false,\n errorMessage: {\n type: 'rule config must be an array, e.g. [\"error\", {}].',\n minItems: 'object rules must have two items, severity and options object. e.g. [\"error\", {}].',\n maxItems: 'object rules must have two items, severity and options object. e.g. [\"error\", {}].',\n additionalItems: 'object rules are only allowed two items, severity and options object. e.g. [\"error\", {}].',\n },\n};\n\nconst optionalObjExceptionsSchema = {\n type: 'array',\n items: [\n {\n type: 'string',\n errorMessage: {\n type: 'each exception must be a string.',\n },\n },\n ],\n uniqueItems: true,\n minItems: 1,\n errorMessage: {\n type: 'expections must be an array.',\n minItems: 'expections must have at least 1 item.',\n uniqueItems: 'expections must have unique items.',\n },\n};\n\nconst configurationSchema = {\n type: 'object',\n properties: {\n extends: {\n type: ['string', 'array'],\n items: {\n type: 'string',\n },\n minItems: 1,\n uniqueItems: true,\n errorMessage: {\n type: 'extends must be either a string or an array of strings.',\n minItems: 'extends must have at least one item if it is an array.',\n uniqueItems: 'extends must have unique items if it is an array.',\n },\n },\n rules: {\n type: 'object',\n errorMessage: {\n type: 'rules must be an object.',\n },\n },\n root: {\n type: 'boolean',\n errorMessage: {\n type: 'root must be a boolean.',\n },\n },\n },\n additionalProperties: false,\n errorMessage: {\n type: 'npm-package-json-lint config should be an object.',\n additionalProperties:\n 'npm-package-json-lint config has unexpected top-level property. Valid properties include: `extends`, `rules`, and `root`.',\n },\n};\n\n/**\n * Validates standard rules config.\n *\n * @param {Object} ruleConfig The ruleConfig object to validate.\n * @returns {boolean} True if valid. Error if not.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const isStandardRuleSchemaValid = (ruleConfig: any): any => {\n const validate = ajv.compile(standardRuleSchema);\n const isValid = validate(ruleConfig);\n\n if (!isValid) {\n throw new Error(`${formatSchemaErrors(validate.errors)}`);\n }\n\n return true;\n};\n\n/**\n * Validates array rules config.\n *\n * @param {Object} ruleConfig The ruleConfig object to validate.\n * @param {number} minItems Min number of items in the array\n * @returns {boolean} True if valid. Error if not.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const isArrayRuleSchemaValid = (ruleConfig: any, minItems: any): any => {\n const validate = ajv.compile(arrayRuleSchema(minItems));\n const isValid = validate(ruleConfig);\n\n if (!isValid) {\n throw new Error(`${formatSchemaErrors(validate.errors)}`);\n }\n\n return true;\n};\n\n/**\n * Validates array rules config.\n *\n * @param {Object} ruleConfig The ruleConfig object to validate.\n * @returns {boolean} True if valid. Error if not.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const isObjectRuleSchemaValid = (ruleConfig: any): any => {\n const validate = ajv.compile(objectRuleSchema);\n const isValid = validate(ruleConfig);\n\n if (!isValid) {\n throw new Error(`${formatSchemaErrors(validate.errors)}`);\n }\n\n return true;\n};\n\n/**\n * Validates optional object exceptions config.\n *\n * @param {Object} ruleConfig The ruleConfig object to validate.\n * @returns {boolean} True if valid. Error if not.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const isOptionalObjExceptSchemaValid = (ruleConfig: any): any => {\n const validate = ajv.compile(optionalObjExceptionsSchema);\n const isValid = validate(ruleConfig);\n\n if (!isValid) {\n throw new Error(`${formatSchemaErrors(validate.errors)}`);\n }\n\n return true;\n};\n\n/**\n * Validates the top level properties of the config object.\n *\n * @param {Object} config The config object to validate.\n * @param {string} source The name of the configuration source to report in any errors.\n * @returns {boolean} True if valid. Error if not.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const isConfigObjectSchemaValid = (config: any, source: any): any => {\n const validate = ajv.compile(configurationSchema);\n const isValid = validate(config);\n\n if (!isValid) {\n throw new Error(`npm-package-json-lint configuration in ${source} is invalid:\\n${formatSchemaErrors(validate.errors)}`);\n }\n\n return true;\n};\n", "import {RuleType} from '../types/rule-type';\nimport {\n isArrayRuleSchemaValid,\n isConfigObjectSchemaValid,\n isObjectRuleSchemaValid,\n isOptionalObjExceptSchemaValid,\n isStandardRuleSchemaValid,\n} from './ConfigSchema';\n\n/**\n * Validates object rule config\n *\n * @param {Object} ruleConfig Object rule\n * @return {Boolean} True if config is valid, false if not\n * @static\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst isObjectRuleConfigValid = (ruleConfig: any): any => {\n if (typeof ruleConfig === 'string' && ruleConfig === 'off') {\n return true;\n }\n\n if (typeof ruleConfig === 'string' && ruleConfig !== 'off') {\n throw new Error('\\t- is an object type rule. It must be set to \"off\" if an object is not supplied.');\n }\n\n return isObjectRuleSchemaValid(ruleConfig);\n};\n\n/**\n * Validates optional object rule config\n *\n * @param {Object} ruleConfig Object rule\n * @return {Boolean} True if config is valid, false if not\n * @static\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst isOptionalObjRuleConfigValid = (ruleConfig: any): any => {\n const object = 1;\n\n if (typeof ruleConfig === 'string') {\n return isStandardRuleSchemaValid(ruleConfig);\n }\n\n if (isObjectRuleSchemaValid(ruleConfig) && ruleConfig[object].hasOwnProperty('exceptions')) {\n return isOptionalObjExceptSchemaValid(ruleConfig[object].exceptions);\n }\n\n return true;\n};\n\n/**\n * Validates array rule config\n *\n * @param {Array} ruleConfig Array rule\n * @param {number} minItems Min number of items in the array\n * @return {Boolean} True if config is valid, false if not\n * @static\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst isArrayRuleConfigValid = (ruleConfig: any, minItems: any): any => {\n if (typeof ruleConfig === 'string' && ruleConfig === 'off') {\n return true;\n }\n\n if (typeof ruleConfig === 'string' && ruleConfig !== 'off') {\n throw new Error('\\t- is an array type rule. It must be set to \"off\" if an array is not supplied.');\n }\n\n return isArrayRuleSchemaValid(ruleConfig, minItems);\n};\n\n/**\n * Validates standard rule config\n *\n * @param {Object} ruleConfig Value for standard rule config\n * @return {Boolean} True if config is valid, error if not\n * @static\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst isStandardRuleConfigValid = (ruleConfig: any): any => isStandardRuleSchemaValid(ruleConfig);\n\n/**\n * Validates configuration of a rule\n *\n * @param {Object} ruleModule The rule object.\n * @param {string} ruleName The rule's unique name.\n * @param {Array|String} userConfig The user's configuration for a rule.\n * @param {String|null} source The name of the configuration source to report in any errors.\n * @returns {undefined} No return\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst validateRule = (ruleModule: any, ruleName: any, userConfig: any, source: any): any => {\n if (ruleModule) {\n try {\n switch (ruleModule.ruleType) {\n case RuleType.Array: {\n isArrayRuleConfigValid(userConfig, ruleModule.minItems);\n\n break;\n }\n case RuleType.Object: {\n isObjectRuleConfigValid(userConfig);\n\n break;\n }\n case RuleType.OptionalObject: {\n isOptionalObjRuleConfigValid(userConfig);\n\n break;\n }\n default: {\n isStandardRuleConfigValid(userConfig);\n }\n }\n } catch (error_) {\n const modifiedErrorMessage = `Configuration for rule \"${ruleName}\" is invalid:\\n${error_.message}`;\n\n const error =\n typeof source === 'string' ? new Error(`${source}:\\n\\t${modifiedErrorMessage}`) : new Error(modifiedErrorMessage);\n\n throw error;\n }\n }\n};\n\n/**\n * Validates only the rules of a config object\n *\n * @param {Object} rulesConfig The rules config object to validate.\n * @param {String} source The name of the configuration source to report in any errors.\n * @param {Object} rules Rules object\n * @returns {undefined} No return\n * @static\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const validateRules = (rulesConfig: any, source: any, rules: any): any => {\n if (!rulesConfig) {\n return;\n }\n\n Object.keys(rulesConfig).forEach((ruleName) => {\n const ruleModule = rules.get(ruleName);\n\n validateRule(ruleModule, ruleName, rulesConfig[ruleName], source);\n });\n};\n\n/**\n * Validates entire config object, including top-level properties.\n *\n * @param {Object} config The config object to validate.\n * @param {String} source The name of the configuration source to report in any errors.\n * @param {Object} rules Rules object\n * @returns {undefined} No return\n * @static\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const validate = (config: any, source: any, rules: any): any => {\n isConfigObjectSchemaValid(config, source);\n validateRules(config.rules, source, rules);\n};\n", "import path from 'path';\nimport {applyExtendsIfSpecified} from './applyExtendsIfSpecified';\nimport {applyOverrides} from './applyOverrides';\n\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst debug = require('debug')('npm-package-json-lint:cosmicConfigTransformer');\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const transform = (cwd: any, configBaseDirectory: any, filePathBeingLinted: any): any => {\n debug(`cwd: ${cwd}`);\n debug(`configBaseDirectory`);\n debug(configBaseDirectory);\n\n return (cosmiconfigResult) => {\n debug(`cosmiconfigResult`);\n debug(cosmiconfigResult);\n\n if (!cosmiconfigResult) {\n return null;\n }\n\n const {config, filepath} = cosmiconfigResult;\n\n debug(`cosmiconfigResult.config`);\n debug(config);\n debug(`cosmiconfigResult.filepath`);\n debug(filepath);\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const configDir = configBaseDirectory || path.dirname(filepath || '');\n const npmPackageJsonLintConfig = {...config};\n\n const configAfterExtends = applyExtendsIfSpecified(npmPackageJsonLintConfig, filePathBeingLinted);\n const configAfterOverrides = applyOverrides(\n cwd,\n filePathBeingLinted,\n configAfterExtends.rules,\n configAfterExtends.overrides\n );\n\n return configAfterOverrides;\n };\n};\n", "import path from 'path';\nimport {parseJavaScriptFile, parseJsonFile} from '../file-parser';\n\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst debug = require('debug')('npm-package-json-lint:applyExtendsIfSpecified');\n\n/**\n * Applies values from the 'extends' field in a configuration file.\n *\n * @param {Object} config The configuration information.\n * @param {string} parentName Name of parent. For troubleshooting.\n * @param {Object} originalFilePath Base config file the extends originated from\n * @returns {Object} A new configuration object with all of the 'extends' fields loaded and merged.\n * @private\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst applyExtends = (config: any, parentName: any, originalFilePath: any): any => {\n let configExtends = config.extends;\n\n if (!Array.isArray(config.extends)) {\n configExtends = [config.extends];\n }\n\n // eslint-disable-next-line unicorn/no-array-reduce\n return configExtends.reduceRight((previousConfig, moduleName) => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n const extendsConfig = loadFromModule(moduleName, originalFilePath);\n\n // Merge base object\n const mergedConfig = {...extendsConfig, ...previousConfig};\n\n // Merge rules\n const rules = {...extendsConfig.rules, ...previousConfig.rules};\n\n // Merge plugins, if exist\n const extendsConfigPlugins = Array.isArray(extendsConfig.plugins) ? extendsConfig.plugins : [];\n const previousConfigPlugins = Array.isArray(previousConfig.plugins) ? previousConfig.plugins : [];\n const plugins = [...extendsConfigPlugins, ...previousConfigPlugins];\n const uniquePlugins = [...new Set(plugins)];\n\n // Merge overrides, if exist\n const extendsConfigOverrides = Array.isArray(extendsConfig.overrides) ? extendsConfig.overrides : [];\n const previousConfigOverrides = Array.isArray(previousConfig.overrides) ? previousConfig.overrides : [];\n const overrides = [...extendsConfigOverrides, ...previousConfigOverrides];\n\n // Override merged rules\n mergedConfig.rules = rules;\n\n if (plugins.length > 0) {\n mergedConfig.plugins = uniquePlugins;\n }\n\n if (overrides.length > 0) {\n mergedConfig.overrides = overrides;\n }\n\n return mergedConfig;\n } catch (error) {\n error.message += `\\nReferenced from: ${parentName}`;\n throw error;\n }\n }, config);\n};\n\n/**\n * Gets configuration from a extends config module\n *\n * @param {String} moduleName Name of the configuration module\n * @param {Object} originalFilePath Base config file the extends originated from\n * @return {Object} Configuration object\n * @private\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst loadFromModule = (moduleName: any, originalFilePath: any): any => {\n let config = {};\n let adjustedModuleName = moduleName;\n\n if (moduleName.startsWith('./')) {\n // TODO: handle process.cwd() option\n adjustedModuleName = path.join(process.cwd(), moduleName);\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n config = loadConfigFile(adjustedModuleName);\n } else {\n const resolvedModule = require.resolve(adjustedModuleName, {paths: [path.dirname(originalFilePath)]});\n\n // eslint-disable-next-line import/no-dynamic-require, global-require\n config = require(resolvedModule);\n }\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-expect-error\n if (Object.keys(config).length > 0 && config.extends) {\n config = applyExtends(config, adjustedModuleName, originalFilePath);\n }\n\n return config;\n};\n\n/**\n * Loads a configuration file regardless of the source. Inspects the file path\n * to determine the correctly way to load the config file.\n *\n * @param {Object} filePath The path to the configuration.\n * @returns {Object} The configuration information.\n * @private\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst loadConfigFile = (filePath: any): any => {\n let config = {};\n\n switch (path.extname(filePath)) {\n case '.js':\n config = parseJavaScriptFile(filePath);\n break;\n\n case '.json':\n config = parseJsonFile(filePath);\n break;\n\n default:\n throw new Error(`Unsupport config file extension. File path: ${filePath}`);\n }\n\n return config;\n};\n\n/**\n * Loads a configuration file from the given file path.\n *\n * @param {Object} npmPackageJsonLintConfig Parsed config from cosmicconfig\n * @param {string} filepath the path to the config file\n * @returns {Object} the parsed config object (empty object if there was a parse error)\n * @private\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const applyExtendsIfSpecified = (npmPackageJsonLintConfig: any, filepath: any): any => {\n let config = {...npmPackageJsonLintConfig};\n\n debug('Loading extends, if applicable');\n if (config?.hasOwnProperty('extends') && config.extends) {\n debug('extends property present, applying.');\n config = applyExtends(config, filepath, filepath);\n }\n\n debug('Loading extends complete');\n\n return config;\n};\n", "import fs from 'fs';\nimport stripComments from 'strip-json-comments';\n\n/**\n * Require JavaScript file\n *\n * @param fileName String file path of file to load\n * @internal\n */\n// eslint-disable-next-line import/no-dynamic-require, global-require\nconst requireFile = (fileName: string): NodeRequire => require(fileName);\n\n/**\n * Sychronously reads file from file system\n *\n * @param fileName String file path of file to load\n * @internal\n */\nconst readFile = (fileName: string): string => fs.readFileSync(fileName, 'utf8').replace(/^\\uFEFF/, '');\n\n/**\n * Helper method for throwing errors when file fails to load.\n *\n * @param fileName Name of the file that failed to load.\n * @param err Error object\n * @throws {Error}\n * @internal\n */\nconst handleError = (fileName: string, err: Error): void => {\n throw new Error(`Failed to read config file: ${fileName}. \\nError: ${err.message}`);\n};\n\nexport const sourceSymbol = Symbol('JSON source');\n\n/**\n * Parse a JSON file\n *\n * @param fileName String file path of file to load\n * @return Valid JSON\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const parseJsonFile = (fileName: string): Record<string, any> => {\n let json = {};\n let fileContents = '';\n\n try {\n fileContents = readFile(fileName);\n\n json = JSON.parse(stripComments(fileContents));\n } catch (error) {\n handleError(fileName, error);\n }\n\n Object.defineProperty(json, sourceSymbol, {\n value: fileContents,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n\n return json;\n};\n\n/**\n * Parse a JavaScript file\n *\n * @param fileName String file path of file to load\n * @return Valid JavaScript object\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const parseJavaScriptFile = (fileName: string): Record<string, any> => {\n let obj = {};\n\n try {\n obj = requireFile(fileName);\n } catch (error) {\n handleError(fileName, error);\n }\n\n return obj;\n};\n", "import path from 'path';\nimport globby from 'globby';\n\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst debug = require('debug')('npm-package-json-lint:applyOverrides');\n\n/**\n * Applies values from the 'overrides' field in a configuration file.\n * @param {string} cwd The current working directory.\n * @param {Object} filePath The file path of the file being linted.\n * @param {Object} rules Rules object\n * @param {Object} overrides Overrides object\n * @returns {Object} A new configuration object with all of the 'overrides' applied.\n * @private\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const applyOverrides = (cwd: string, filePath: string, rules: any, overrides?: any[]): any => {\n let finalRules = {...rules};\n\n debug('overrides');\n debug(overrides);\n\n if (overrides) {\n overrides.forEach((override) => {\n const filteredPatterns = override.patterns.filter((pattern) => pattern.length);\n const transformedPatterns = filteredPatterns.map((pattern) =>\n pattern.endsWith(`/package.json`) ? pattern : `${pattern}/package.json`\n );\n\n const globFiles = globby.sync(transformedPatterns, {\n cwd,\n gitignore: true,\n });\n\n debug('globFiles');\n debug(globFiles);\n globFiles.forEach((globFile) => {\n const globbedFilePath = path.resolve(cwd, globFile);\n\n if (filePath === globbedFilePath) {\n finalRules = {...finalRules, ...override.rules};\n }\n });\n });\n }\n\n debug('finalRules');\n debug(finalRules);\n\n return finalRules;\n};\n", "import chalk from 'chalk';\nimport {readdirSync} from 'fs';\nimport path from 'path';\nimport {LintFunction} from './types/lint-function';\nimport {RuleType} from './types/rule-type';\n\nexport interface Rule {\n lint: LintFunction;\n ruleType: RuleType;\n minItems?: number;\n}\n\nexport class Rules {\n rules: Record<string, string>;\n\n constructor() {\n this.rules = {};\n }\n\n /**\n * Loads rules\n *\n * @return Set of rules\n */\n load(): Record<string, string> {\n const rulesDirectory = path.join(__dirname, 'rules');\n\n try {\n readdirSync(rulesDirectory).forEach((filePath) => {\n const beginIndex = 0;\n const endIndex = -3;\n // remove the file extension, e.g. `.js`\n const ruleId = filePath.slice(beginIndex, endIndex);\n const filePathToRuleModule = path.join(rulesDirectory, filePath);\n\n this.registerRule(ruleId, filePathToRuleModule);\n });\n\n return this.rules;\n } catch (error) {\n throw new Error(`Error while loading rules from rules directory - ${error.message}`);\n }\n }\n\n /**\n * Loads a rule module\n *\n * @param ruleId Name of the rule\n * @return Rule module\n */\n get(ruleId: string): Rule {\n const rule = this.rules[ruleId];\n\n if (typeof rule === 'undefined') {\n const errorMsg = `Rule, ${ruleId}, is invalid. Please ensure it matches a valid option.`;\n\n throw new Error(chalk.bold.red(errorMsg));\n }\n\n // eslint-disable-next-line import/no-dynamic-require, global-require, @typescript-eslint/no-var-requires\n const ruleModule = require(this.rules[ruleId]);\n\n return ruleModule;\n }\n\n /**\n * Gets entire rule set\n *\n * @returns Rule set\n */\n getRules(): Record<string, string> {\n return this.rules;\n }\n\n /**\n * Registers a rule in the rules object\n *\n * @param ruleId Name of the rule\n * @param filePathToRuleModule File path to rule\n */\n registerRule(ruleId: string, filePathToRuleModule: string): void {\n this.rules[ruleId] = filePathToRuleModule;\n }\n}\n", "import path from 'path';\nimport {PackageJson} from 'type-fest';\nimport {Ignore} from 'ignore';\nimport {Rules} from '../native-rules';\nimport {parseJsonFile} from '../file-parser';\nimport {LintIssue} from '../lint-issue';\nimport {RuleType} from '../types/rule-type';\nimport {Severity} from '../types/severity';\nimport {aggregateCountsPerFile, aggregateOverallCounts, OverallAggregatedResultCounts} from './results-helper';\nimport {Config} from '../configuration';\nimport {PackageJsonFileLintingResult} from '../types/package-json-linting-result';\n\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst debug = require('debug')('npm-package-json-lint:linter');\n\nexport interface CreateResultObjectOptions {\n /**\n * The current working directory.\n */\n cwd: string;\n /**\n * An optional string representing the package.json file.\n */\n fileName: string;\n /**\n * A flag indicating that the file was skipped.\n */\n ignored: boolean;\n /**\n * A list of issues.\n */\n issues: LintIssue[];\n /**\n * Number of errors.\n */\n errorCount: number;\n /**\n * Number of warnings.\n */\n warningCount: number;\n}\n\n/**\n * Creates a results object.\n *\n * @param options A {@link CreateResultObjectOptions} object\n * @returns The lint results {@link PackageJsonFileLintingResult} for the package.json file.\n * @internal\n */\nconst createResultObject = (options: CreateResultObjectOptions): PackageJsonFileLintingResult => {\n const {cwd, fileName, ignored, issues, errorCount, warningCount} = options;\n\n return {\n filePath: `./${path.relative(cwd, fileName)}`,\n issues,\n ignored,\n errorCount,\n warningCount,\n };\n};\n\n/**\n * Runs configured rules against the provided package.json object.\n *\n * @param packageJsonData Valid package.json data\n * @param configObj Configuration object\n * @param rules Object of rule definitions\n * @return An array of {@link LintIssue} objects.\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst lint = (packageJsonData: any, configObj, rules: Rules): LintIssue[] => {\n const lintIssues = [];\n\n // eslint-disable-next-line no-restricted-syntax, guard-for-in\n for (const rule in configObj) {\n const ruleModule = rules.get(rule);\n\n let severity = Severity.Off;\n let ruleConfig;\n\n if (ruleModule.ruleType === RuleType.Array || ruleModule.ruleType === RuleType.Object) {\n severity = typeof configObj[rule] === 'string' && configObj[rule] === 'off' ? configObj[rule] : configObj[rule][0];\n ruleConfig = typeof configObj[rule] === 'string' ? {} : configObj[rule][1];\n } else if (ruleModule.ruleType === RuleType.OptionalObject) {\n if (typeof configObj[rule] === 'string') {\n severity = configObj[rule];\n ruleConfig = {};\n } else {\n // eslint-disable-next-line prefer-destructuring\n severity = configObj[rule][0];\n // eslint-disable-next-line prefer-destructuring\n ruleConfig = configObj[rule][1];\n }\n } else {\n severity = configObj[rule];\n }\n\n if (severity !== Severity.Off) {\n const lintResult = ruleModule.lint(packageJsonData, severity, ruleConfig);\n\n if (lintResult !== null) {\n lintIssues.push(lintResult);\n }\n }\n }\n\n return lintIssues;\n};\n\n/**\n * Processes package.json object\n *\n * @param cwd The current working directory.\n * @param packageJsonObj An object representation of a package.json file.\n * @param config A config object.\n * @param fileName An optional string representing the package.json file.\n * @param rules An instance of `Rules`.\n * @returns A {@link PackageJsonFileLintingResult} object with the result of linting a package.json file.\n * @internal\n */\nconst processPackageJsonObject = (\n cwd: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n packageJsonObj: PackageJson | any,\n // TODO: Type\n config,\n fileName: string,\n rules: Rules\n): PackageJsonFileLintingResult => {\n const lintIssues = lint(packageJsonObj, config, rules);\n const counts = aggregateCountsPerFile(lintIssues);\n const result = createResultObject({\n cwd,\n fileName,\n ignored: false,\n issues: lintIssues,\n errorCount: counts.errorCount,\n warningCount: counts.warningCount,\n });\n\n return result;\n};\n\n/**\n * Processes a package.json file.\n *\n * @param cwd The current working directory.\n * @param fileName The filename of the file being linted.\n * @param config A config object.\n * @param rules An instance of `Rules`.\n * @returns A {@link PackageJsonFileLintingResult} object with the result of linting a package.json file.\n * @internal\n */\n// TODO: Type\nconst processPackageJsonFile = (cwd: string, fileName: string, config, rules: Rules): PackageJsonFileLintingResult => {\n const packageJsonObj = parseJsonFile(path.resolve(fileName));\n\n return processPackageJsonObject(cwd, packageJsonObj, config, fileName, rules);\n};\n\nexport interface LinterResult {\n results: LintIssue[];\n ignoreCount: number;\n /**\n * Number of errors for the package.json file.\n */\n errorCount: number;\n /**\n * Number of warnings for the package.json file.\n */\n warningCount: number;\n}\n\nexport interface ExecuteOnPackageJsonObjectOptions {\n /**\n * The current working directory.\n */\n cwd: string;\n /**\n * An object representation of a package.json file.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n packageJsonObject: PackageJson | any;\n /**\n * An optional string representing the texts filename.\n */\n filename?: string;\n /**\n * An instance of the `ignore` module.\n */\n ignorer: Ignore;\n /**\n * An instance of {@Config}.\n */\n configHelper: Config;\n /**\n * An instance of {@link Rules}\n */\n rules: Rules;\n}\n\nexport interface OverallLintingResult extends OverallAggregatedResultCounts {\n results: PackageJsonFileLintingResult[];\n}\n\n/**\n * Executes linter on package.json object\n *\n * @param options A {@link ExecuteOnPackageJsonObjectOptions} object\n * @returns The results {@link OverallLintingResult} from linting a collection of package.json files.\n */\nexport const executeOnPackageJsonObject = (options: ExecuteOnPackageJsonObjectOptions): OverallLintingResult => {\n const {cwd, packageJsonObject, filename, ignorer, configHelper, rules} = options;\n\n debug('executing on package.json object');\n const results = [];\n\n const filenameDefaulted = filename || '';\n const resolvedFilename = path.isAbsolute(filenameDefaulted) ? filenameDefaulted : path.resolve(cwd, filenameDefaulted);\n const relativeFilePath = path.relative(cwd, resolvedFilename);\n\n if (ignorer.ignores(relativeFilePath)) {\n debug(`Ignored: ${relativeFilePath}`);\n\n const result = createResultObject({\n cwd,\n fileName: resolvedFilename,\n ignored: true,\n issues: [],\n errorCount: 0,\n warningCount: 0,\n });\n\n results.push(result);\n } else {\n debug(`Getting config for ${resolvedFilename}`);\n const config = configHelper.getConfigForFile(resolvedFilename);\n\n debug(`Config fetched for ${resolvedFilename}`);\n const result = processPackageJsonObject(cwd, packageJsonObject, config, resolvedFilename, rules);\n\n results.push(result);\n }\n\n debug('Aggregating overall counts');\n const stats = aggregateOverallCounts(results);\n\n debug('stats');\n debug(stats);\n\n return {\n results,\n ignoreCount: stats.ignoreCount,\n errorCount: stats.errorCount,\n warningCount: stats.warningCount,\n };\n};\n\nexport interface ExecuteOnPackageJsonFilesOptions {\n /**\n * The current working directory.\n */\n cwd: string;\n /**\n * An array of files and directory names.\n */\n fileList: string[];\n /**\n * An instance of the `ignore` module.\n */\n ignorer: Ignore;\n /**\n * An instance of {@Config}.\n */\n configHelper: Config;\n /**\n * An instance of {@link Rules}\n */\n rules: Rules;\n}\n\n/**\n * Executes the current configuration on an array of file and directory names.\n * @param options A {@link ExecuteOnPackageJsonFilesOptions} object\n * @returns The results {@link OverallLintingResult} from linting a collection of package.json files.\n */\nexport const executeOnPackageJsonFiles = (options: ExecuteOnPackageJsonFilesOptions): OverallLintingResult => {\n const {cwd, fileList, ignorer, configHelper, rules} = options;\n\n debug('executing on package.json files');\n const results = fileList.map((filePath) => {\n const relativeFilePath = path.relative(cwd, filePath);\n\n if (ignorer.ignores(relativeFilePath)) {\n debug(`Ignored: ${relativeFilePath}`);\n\n return createResultObject({\n cwd,\n fileName: filePath,\n ignored: true,\n issues: [],\n errorCount: 0,\n warningCount: 0,\n });\n }\n\n debug(`Getting config for ${filePath}`);\n const config = configHelper.getConfigForFile(filePath);\n\n debug(`Config fetched for ${filePath}`);\n\n return processPackageJsonFile(cwd, filePath, config, rules);\n });\n\n debug('Aggregating overall counts');\n const stats = aggregateOverallCounts(results);\n\n debug('stats');\n debug(stats);\n\n return {\n results,\n ignoreCount: stats.ignoreCount,\n errorCount: stats.errorCount,\n warningCount: stats.warningCount,\n };\n};\n", "export enum Severity {\n Error = 'error',\n Warning = 'warning',\n Off = 'off',\n}\n", "import {LintIssue} from '../lint-issue';\nimport {Severity} from '../types/severity';\nimport {PackageJsonFileLintingResult} from '../types/package-json-linting-result';\n\n/**\n * A result count object for a files.\n * @typedef {Object} FileResultCounts\n * @property {number} errorCount Number of errors for a file result.\n * @property {number} warningCount Number of warnings for a file result.\n */\n\nexport interface PackageJsonFileAggregatedResultCounts {\n errorCount: number;\n warningCount: number;\n}\n\n/**\n * Aggregates the count of errors and warning for a package.json file.\n *\n * @param issues Array of {@link LintIssue} objects from a package.json file.\n * @returns Counts object {@link PackageJsonFileAggregatedResultCounts}.\n */\nexport const aggregateCountsPerFile = (issues: LintIssue[]): PackageJsonFileAggregatedResultCounts => {\n const incrementOne = 1;\n\n // eslint-disable-next-line unicorn/no-array-reduce\n return issues.reduce(\n (counts, issue) => {\n const isErrorSeverity = issue.severity === Severity.Error;\n const newErrorCount = isErrorSeverity ? counts.errorCount + incrementOne : counts.errorCount;\n const newWarningCount = isErrorSeverity ? counts.warningCount : counts.warningCount + incrementOne;\n\n return {\n errorCount: newErrorCount,\n warningCount: newWarningCount,\n };\n },\n {\n errorCount: 0,\n warningCount: 0,\n }\n );\n};\n\nexport interface OverallAggregatedResultCounts {\n /**\n * Total number of ignored files.\n */\n ignoreCount: number;\n /**\n * Total number of errors.\n */\n errorCount: number;\n /**\n * Total number of warnings.\n */\n warningCount: number;\n}\n\n/**\n * Aggregates the count of errors and warnings for all package.json files.\n *\n * @param results Array of {@link PackageJsonFileLintingResult} objects from all package.json files.\n * @returns Counts object {@link OverallAggregatedResultCounts}\n */\nexport const aggregateOverallCounts = (results: PackageJsonFileLintingResult[]): OverallAggregatedResultCounts =>\n // eslint-disable-next-line unicorn/no-array-reduce\n results.reduce(\n (counts, result) => ({\n ignoreCount: result.ignored ? counts.ignoreCount + 1 : counts.ignoreCount,\n errorCount: counts.errorCount + result.errorCount,\n warningCount: counts.warningCount + result.warningCount,\n }),\n {\n ignoreCount: 0,\n errorCount: 0,\n warningCount: 0,\n }\n );\n", "import path from 'path';\nimport globby from 'globby';\n\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst debug = require('debug')('npm-package-json-lint:getFileList');\n\n/**\n * Generates a list of files to lint based on a list of provided patterns\n *\n * @param {Array<string>} patterns An array of patterns\n * @param {string} cwd The current working directory.\n * @returns {Array<string>} An array a files to lint.\n */\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport const getFileList = (patterns, cwd) => {\n debug('patterns');\n debug(patterns);\n\n // step 1 - filter out empty entries\n const filteredPatterns = patterns.filter((pattern) => pattern.length);\n\n debug('filteredPatterns');\n debug(filteredPatterns);\n\n // step 2 - convert directories to globs\n const globPatterns = filteredPatterns.map((pattern) =>\n pattern.endsWith(`/package.json`) ? pattern : `${pattern}/**/package.json`\n );\n\n globPatterns.push('!**/node_modules/**');\n\n debug('globPatterns');\n debug(globPatterns);\n\n const files = [];\n const addedFiles = new Set();\n\n const globFiles = globby.sync(globPatterns, {\n cwd,\n gitignore: true,\n });\n\n debug('globFiles');\n debug(globFiles);\n\n globFiles.forEach((globFile) => {\n const filePath = path.resolve(cwd, globFile);\n\n if (addedFiles.has(filePath)) {\n return;\n }\n\n addedFiles.add(filePath);\n files.push(filePath);\n });\n\n debug('Final file list from `getFileList`');\n debug(files);\n\n return files;\n};\n", "import fs from 'fs';\nimport path from 'path';\nimport ignore, {Ignore} from 'ignore';\n\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst debug = require('debug')('npm-package-json-lint:getIgnorer');\n\nconst DEFAULT_IGNORE_FILENAME = '.npmpackagejsonlintignore';\nconst FILE_NOT_FOUND_ERROR_CODE = 'ENOENT';\n\n/**\n * Generates ignorer based on ignore file content.\n *\n * @param cwd Current work directory.\n * @param ignorePath Ignore path.\n * @returns An instance of an Ignorer\n */\nexport const getIgnorer = (cwd: string, ignorePath: string): Ignore => {\n const ignoreFilePath = ignorePath || DEFAULT_IGNORE_FILENAME;\n\n debug(`ignoreFilePath: ${ignoreFilePath}`);\n const absoluteIgnoreFilePath = path.isAbsolute(ignoreFilePath) ? ignoreFilePath : path.resolve(cwd, ignoreFilePath);\n\n debug(`absoluteIgnoreFilePath: ${absoluteIgnoreFilePath}`);\n let ignoreText = '';\n\n try {\n ignoreText = fs.readFileSync(absoluteIgnoreFilePath, 'utf8');\n } catch (readError) {\n if (readError.code !== FILE_NOT_FOUND_ERROR_CODE) {\n throw readError;\n }\n }\n\n debug('Ignore text added');\n\n return ignore().add(ignoreText);\n};\n", "import chalk from 'chalk';\nimport logSymbols from 'log-symbols';\nimport {Severity} from './types/severity';\n\n/**\n * A lint issue\n */\nexport class LintIssue {\n /**\n * Unique, lowercase, hyphen-separate name for the lint\n *\n * @type {string}\n * @memberof LintIssue\n */\n lintId: string;\n\n /**\n * 'error' or 'warning'\n *\n * @type {Severity}\n * @memberof LintIssue\n */\n severity: Severity;\n\n /**\n * Name of the node in the JSON the lint audits\n *\n * @type {string}\n * @memberof LintIssue\n */\n node: string;\n\n /**\n * Human-friendly message to users\n *\n * @type {string}\n * @memberof LintIssue\n */\n lintMessage: string;\n\n /**\n * Creates an instance of LintIssue.\n * @param lintId Unique, lowercase, hyphen-separate name for the lint\n * @param severity 'error' or 'warning'\n * @param node Name of the node in the JSON the lint audits\n * @param lintMessage Human-friendly message to users\n * @memberof LintIssue\n */\n constructor(lintId: string, severity: Severity, node: string, lintMessage: string) {\n this.lintId = lintId;\n this.severity = severity;\n this.node = node;\n this.lintMessage = lintMessage;\n }\n\n /**\n * Helper to convert the LintIssue to a printable string\n *\n * @returns {string} Human-friendly message about the lint issue\n */\n toString(): string {\n const logSymbol = this.severity === Severity.Error ? logSymbols.error : logSymbols.warning;\n const formattedLintId = chalk.gray.dim(this.lintId);\n const formattedNode = chalk.gray.bold(this.node);\n const formattedMessage =\n this.severity === Severity.Error ? chalk.bold.red(this.lintMessage) : chalk.yellow(this.lintMessage);\n\n return `${logSymbol} ${formattedLintId} - node: ${formattedNode} - ${formattedMessage}`;\n }\n}\n"],
|
|
5
|
-
"mappings": "mzFAAA,6GCAA,OAAuB,2BACvB,EAAkB,oBCDlB,MAA8B,uBCA9B,OAAgB,kBAChB,GAAsB,yBAEhB,EAAM,GAAI,YAAI,CAAC,UAAW,GAAM,aAAc,EAAI,CAAC,EAEzD,eAAU,CAAG,EASb,GAAM,GAAqB,AAAC,GAAW,EAAO,IAAI,AAAC,GAAU,MAAO,E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C,EACJ,KAAK,WAAa,QAAiB,UAAM,KAAK,IAAI,KAAK,WAAW,EAAI,UAAM,OAAO,KAAK,WAAW,EAErG,MAAO,GAAG,KAAa,aAA2B,OAAmB,GACvE,CACF",
|
|
4
|
+
"sourcesContent": ["export {NpmPackageJsonLint, NpmPackageJsonLintOptions} from './npm-package-json-lint';\n\nexport {LintIssue} from './lint-issue';\n\nexport {Severity} from './types/severity';\n\nexport {LinterResult} from './linter/linter';\n\nexport {PackageJsonFileLintingResult} from './types/package-json-linting-result';\n\nexport {PackageJsonFileAggregatedResultCounts, OverallAggregatedResultCounts} from './linter/results-helper';\n\nexport {Rules, Rule} from './native-rules';\n", "import isPlainObj from 'is-plain-obj';\nimport slash from 'slash';\nimport {PackageJson} from 'type-fest';\nimport {Config} from './configuration';\nimport {Rules} from './native-rules';\nimport {executeOnPackageJsonFiles, executeOnPackageJsonObject, OverallLintingResult} from './linter/linter';\nimport {getFileList} from './utils/getFileList';\nimport {getIgnorer} from './utils/getIgnorer';\nimport {Severity} from './types/severity';\nimport {PackageJsonFileLintingResult} from './types/package-json-linting-result';\nimport {LintIssue} from './lint-issue';\n\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst debug = require('debug')('npm-package-json-lint:NpmPackageJsonLint');\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst pkg = require('../package.json');\n\nconst noIssues = 0;\n\n/**\n * Checks if the given issue is an error issue.\n *\n * @param issue A {@link LintIssue} object\n * @returns True if error, false if warning.\n * @private\n */\nconst isIssueAnError = (issue: LintIssue): boolean => issue.severity === Severity.Error;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst isPackageJsonObjectValid = (packageJsonObject: PackageJson | any): boolean => isPlainObj(packageJsonObject);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst areRequiredOptionsValid = (packageJsonObject: PackageJson | any, patterns: string[]): boolean =>\n (!patterns && !isPackageJsonObjectValid(packageJsonObject)) ||\n (patterns && (packageJsonObject || isPackageJsonObjectValid(packageJsonObject)));\n\n/**\n * Filters results to only include errors.\n *\n * @param results The results to filter.\n * @returns The filtered results.\n */\nconst getErrorResults = (results: PackageJsonFileLintingResult[]): PackageJsonFileLintingResult[] => {\n const filtered = [];\n\n results.forEach((result) => {\n // eslint-disable-next-line unicorn/no-array-callback-reference\n const filteredIssues = result.issues.filter(isIssueAnError);\n\n if (filteredIssues.length > noIssues) {\n const filteredResult = {\n issues: filteredIssues,\n errorCount: filteredIssues.length,\n warningCount: 0,\n };\n\n filtered.push(Object.assign(result, filteredResult));\n }\n });\n\n return filtered;\n};\n\nexport interface NpmPackageJsonLintOptions {\n cwd?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n packageJsonObject?: any;\n packageJsonFilePath?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n config?: any;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n configFile?: any;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n configBaseDirectory?: any;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n patterns?: any;\n quiet?: boolean;\n ignorePath?: string;\n fix?: boolean;\n}\n\nexport class NpmPackageJsonLint {\n cwd: string;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n packageJsonObject: any;\n\n packageJsonFilePath: string;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n patterns: any;\n\n quiet: boolean;\n\n ignorePath: string;\n\n fix: boolean;\n\n version: string;\n\n rules: Rules;\n\n configHelper: Config;\n\n /**\n * constructor\n * @param options An instance of the {@link NpmPackageJsonLintOptions} options object.\n * @constructor\n */\n constructor(options: NpmPackageJsonLintOptions) {\n const {\n cwd,\n packageJsonObject,\n packageJsonFilePath,\n config,\n configFile,\n configBaseDirectory,\n patterns,\n quiet,\n ignorePath,\n fix,\n } = options;\n\n this.cwd = slash(cwd || process.cwd());\n\n this.packageJsonObject = packageJsonObject;\n this.packageJsonFilePath = packageJsonFilePath ? slash(packageJsonFilePath) : packageJsonFilePath;\n this.patterns = patterns;\n this.quiet = quiet || false;\n this.ignorePath = ignorePath || '';\n this.fix = fix || false;\n\n this.version = pkg.version;\n\n this.rules = new Rules();\n this.rules.load();\n\n this.configHelper = new Config(this.cwd, config, configFile, configBaseDirectory, this.rules);\n }\n\n /**\n * Runs the linter using the config specified in the constructor\n *\n * @returns The results {@link OverallLintingResult} from linting a collection of package.json files.\n */\n lint(): OverallLintingResult {\n debug('Starting lint');\n\n if (areRequiredOptionsValid(this.packageJsonObject, this.patterns)) {\n throw new Error(\n 'You must pass npm-package-json-lint a `patterns` glob or a `packageJsonObject` string, though not both.'\n );\n }\n\n const ignorer = getIgnorer(this.cwd, this.ignorePath);\n let linterOutput: OverallLintingResult;\n\n if (this.patterns) {\n debug('Linting using patterns');\n\n if (!Array.isArray(this.patterns)) {\n throw new TypeError('Patterns must be an array.');\n }\n\n const fileList = getFileList(this.patterns, this.cwd);\n\n linterOutput = executeOnPackageJsonFiles({\n cwd: this.cwd,\n fileList,\n ignorer,\n configHelper: this.configHelper,\n rules: this.rules,\n });\n } else {\n debug('Linting using passed object.');\n linterOutput = executeOnPackageJsonObject({\n cwd: this.cwd,\n packageJsonObject: this.packageJsonObject,\n ignorer,\n filename: this.packageJsonFilePath,\n configHelper: this.configHelper,\n rules: this.rules,\n });\n }\n\n if (this.quiet) {\n const errorsOnly = getErrorResults(linterOutput.results);\n\n return {\n results: errorsOnly,\n ignoreCount: linterOutput.ignoreCount,\n errorCount: linterOutput.errorCount,\n warningCount: linterOutput.warningCount,\n };\n }\n\n debug('lint complete');\n\n return linterOutput;\n }\n}\n", "import {cosmiconfigSync} from 'cosmiconfig';\nimport {validateRules} from './config/ConfigValidator';\nimport {transform} from './config/cosmicConfigTransformer';\nimport {applyExtendsIfSpecified} from './config/applyExtendsIfSpecified';\nimport {applyOverrides} from './config/applyOverrides';\nimport {Rules} from './native-rules';\n\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst debug = require('debug')('npm-package-json-lint:Config');\n\nconst noRules = 0;\n\n/**\n * Config class\n * @class\n */\nexport class Config {\n /**\n * The user passed config object.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n config: any;\n\n /**\n * The current working directory.\n */\n cwd: string;\n\n /**\n * The user passed configFile path.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n configFile: any;\n\n /**\n * The base directory that config should be pulled from.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n configBaseDirectory: any;\n\n /**\n * Rules object\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rules: any;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor(cwd: string, config: any, configFile: any, configBaseDirectory: any, rules: Rules) {\n if (config) {\n this.config = applyExtendsIfSpecified(config, 'PassedConfig');\n }\n\n this.cwd = cwd;\n this.configFile = configFile;\n this.configBaseDirectory = configBaseDirectory;\n this.rules = rules;\n }\n\n /**\n * Gets the config for a file.\n *\n * @param filePath File path of the file being linted.\n * @returns {Object} A config object.\n * @memberof Config\n */\n // eslint-disable-next-line @typescript-eslint/explicit-function-return-type\n getConfigForFile(filePath: string) {\n debug(`Getting config for ${filePath}`);\n const filePathToSearch = filePath;\n\n debug(`filePathToSearch: ${filePathToSearch}`);\n let config;\n\n if (typeof this.config === 'undefined') {\n debug(`User passed config is undefined.`);\n if (this.configFile) {\n debug(`Config file specified, loading it.`);\n config = cosmiconfigSync('npmpackagejsonlint', {\n transform: transform(this.cwd, this.configBaseDirectory, filePath),\n }).load(this.configFile);\n } else {\n debug(`Config file wasn't specified, searching for config.`);\n config = cosmiconfigSync('npmpackagejsonlint', {\n transform: transform(this.cwd, this.configBaseDirectory, filePathToSearch),\n }).search(filePathToSearch);\n }\n } else {\n debug(`User passed config is set, using it.`);\n const configBeforeOverrides = this.config;\n\n debug(`Applying overrides to config for ${filePath}`);\n config = applyOverrides(this.cwd, filePath, configBeforeOverrides.rules, configBeforeOverrides.overrides);\n\n debug(`Overrides applied for ${filePath}`);\n }\n\n if (!config) {\n throw new Error(`No npm-package-json-lint configuration found.\\n${filePathToSearch}`);\n }\n\n if (Object.keys(config).length === noRules) {\n throw new Error(`No rules specified in configuration.\\n${filePathToSearch}`);\n }\n\n debug(`Overrides applied for ${filePath}`);\n debug('Final Config');\n debug(config);\n\n validateRules(config, 'cli', this.rules);\n\n return config;\n }\n}\n", "import Ajv from 'ajv';\nimport ajvErrors from 'ajv-errors';\n\nconst ajv = new Ajv({allErrors: true, jsonPointers: true});\n\najvErrors(ajv);\n\n/**\n * Formats an array of schema validation errors.\n *\n * @param {Array} errors An array of error messages to format.\n * @returns {String} Formatted error message\n */\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nconst formatSchemaErrors = (errors) => errors.map((error) => `\\t- ${error.message}\\n`).join('');\n\nconst standardRuleSchema = {\n type: 'string',\n enum: ['off', 'warning', 'error'],\n errorMessage: {\n type: 'severity must be a string.',\n enum: 'severity must be either \"off\", \"warning\", or \"error\".',\n },\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst arrayRuleSchema = (minItems: any): any => ({\n type: 'array',\n items: [\n standardRuleSchema,\n {\n type: 'array',\n minItems,\n uniqueItems: true,\n errorMessage: {\n type: 'the second item in an array rule config must be an array.',\n minItems: 'the second item in an array rule config must have at least 1 item.',\n uniqueItems: 'the second item in an array rule config must have unique items.',\n },\n },\n ],\n minItems: 2,\n maxItems: 2,\n additionalItems: false,\n errorMessage: {\n type: 'rule config must be an array, e.g. [\"error\", [\"value1\", \"value2\"]].',\n minItems: 'array rules must have two items, severity and options array. e.g. [\"error\", [\"value1\", \"value2\"]].',\n maxItems: 'array rules must have two items, severity and options array. e.g. [\"error\", [\"value1\", \"value2\"]].',\n additionalItems:\n 'array rules are only allowed two items, severity and the list is values. e.g. [\"error\", [\"value1\", \"value2\"]].',\n },\n});\n\nconst objectRuleSchema = {\n type: 'array',\n items: [\n standardRuleSchema,\n {\n type: 'object',\n errorMessage: {\n type: 'the second item in an object rule config must be an object.',\n },\n },\n ],\n minItems: 2,\n maxItems: 2,\n additionalItems: false,\n errorMessage: {\n type: 'rule config must be an array, e.g. [\"error\", {}].',\n minItems: 'object rules must have two items, severity and options object. e.g. [\"error\", {}].',\n maxItems: 'object rules must have two items, severity and options object. e.g. [\"error\", {}].',\n additionalItems: 'object rules are only allowed two items, severity and options object. e.g. [\"error\", {}].',\n },\n};\n\nconst optionalObjExceptionsSchema = {\n type: 'array',\n items: [\n {\n type: 'string',\n errorMessage: {\n type: 'each exception must be a string.',\n },\n },\n ],\n uniqueItems: true,\n minItems: 1,\n errorMessage: {\n type: 'expections must be an array.',\n minItems: 'expections must have at least 1 item.',\n uniqueItems: 'expections must have unique items.',\n },\n};\n\nconst configurationSchema = {\n type: 'object',\n properties: {\n extends: {\n type: ['string', 'array'],\n items: {\n type: 'string',\n },\n minItems: 1,\n uniqueItems: true,\n errorMessage: {\n type: 'extends must be either a string or an array of strings.',\n minItems: 'extends must have at least one item if it is an array.',\n uniqueItems: 'extends must have unique items if it is an array.',\n },\n },\n rules: {\n type: 'object',\n errorMessage: {\n type: 'rules must be an object.',\n },\n },\n root: {\n type: 'boolean',\n errorMessage: {\n type: 'root must be a boolean.',\n },\n },\n },\n additionalProperties: false,\n errorMessage: {\n type: 'npm-package-json-lint config should be an object.',\n additionalProperties:\n 'npm-package-json-lint config has unexpected top-level property. Valid properties include: `extends`, `rules`, and `root`.',\n },\n};\n\n/**\n * Validates standard rules config.\n *\n * @param {Object} ruleConfig The ruleConfig object to validate.\n * @returns {boolean} True if valid. Error if not.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const isStandardRuleSchemaValid = (ruleConfig: any): any => {\n const validate = ajv.compile(standardRuleSchema);\n const isValid = validate(ruleConfig);\n\n if (!isValid) {\n throw new Error(`${formatSchemaErrors(validate.errors)}`);\n }\n\n return true;\n};\n\n/**\n * Validates array rules config.\n *\n * @param {Object} ruleConfig The ruleConfig object to validate.\n * @param {number} minItems Min number of items in the array\n * @returns {boolean} True if valid. Error if not.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const isArrayRuleSchemaValid = (ruleConfig: any, minItems: any): any => {\n const validate = ajv.compile(arrayRuleSchema(minItems));\n const isValid = validate(ruleConfig);\n\n if (!isValid) {\n throw new Error(`${formatSchemaErrors(validate.errors)}`);\n }\n\n return true;\n};\n\n/**\n * Validates array rules config.\n *\n * @param {Object} ruleConfig The ruleConfig object to validate.\n * @returns {boolean} True if valid. Error if not.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const isObjectRuleSchemaValid = (ruleConfig: any): any => {\n const validate = ajv.compile(objectRuleSchema);\n const isValid = validate(ruleConfig);\n\n if (!isValid) {\n throw new Error(`${formatSchemaErrors(validate.errors)}`);\n }\n\n return true;\n};\n\n/**\n * Validates optional object exceptions config.\n *\n * @param {Object} ruleConfig The ruleConfig object to validate.\n * @returns {boolean} True if valid. Error if not.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const isOptionalObjExceptSchemaValid = (ruleConfig: any): any => {\n const validate = ajv.compile(optionalObjExceptionsSchema);\n const isValid = validate(ruleConfig);\n\n if (!isValid) {\n throw new Error(`${formatSchemaErrors(validate.errors)}`);\n }\n\n return true;\n};\n\n/**\n * Validates the top level properties of the config object.\n *\n * @param {Object} config The config object to validate.\n * @param {string} source The name of the configuration source to report in any errors.\n * @returns {boolean} True if valid. Error if not.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const isConfigObjectSchemaValid = (config: any, source: any): any => {\n const validate = ajv.compile(configurationSchema);\n const isValid = validate(config);\n\n if (!isValid) {\n throw new Error(`npm-package-json-lint configuration in ${source} is invalid:\\n${formatSchemaErrors(validate.errors)}`);\n }\n\n return true;\n};\n", "import {RuleType} from '../types/rule-type';\nimport {\n isArrayRuleSchemaValid,\n isConfigObjectSchemaValid,\n isObjectRuleSchemaValid,\n isOptionalObjExceptSchemaValid,\n isStandardRuleSchemaValid,\n} from './ConfigSchema';\n\n/**\n * Validates object rule config\n *\n * @param {Object} ruleConfig Object rule\n * @return {Boolean} True if config is valid, false if not\n * @static\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst isObjectRuleConfigValid = (ruleConfig: any): any => {\n if (typeof ruleConfig === 'string' && ruleConfig === 'off') {\n return true;\n }\n\n if (typeof ruleConfig === 'string' && ruleConfig !== 'off') {\n throw new Error('\\t- is an object type rule. It must be set to \"off\" if an object is not supplied.');\n }\n\n return isObjectRuleSchemaValid(ruleConfig);\n};\n\n/**\n * Validates optional object rule config\n *\n * @param {Object} ruleConfig Object rule\n * @return {Boolean} True if config is valid, false if not\n * @static\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst isOptionalObjRuleConfigValid = (ruleConfig: any): any => {\n const object = 1;\n\n if (typeof ruleConfig === 'string') {\n return isStandardRuleSchemaValid(ruleConfig);\n }\n\n if (isObjectRuleSchemaValid(ruleConfig) && ruleConfig[object].hasOwnProperty('exceptions')) {\n return isOptionalObjExceptSchemaValid(ruleConfig[object].exceptions);\n }\n\n return true;\n};\n\n/**\n * Validates array rule config\n *\n * @param {Array} ruleConfig Array rule\n * @param {number} minItems Min number of items in the array\n * @return {Boolean} True if config is valid, false if not\n * @static\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst isArrayRuleConfigValid = (ruleConfig: any, minItems: any): any => {\n if (typeof ruleConfig === 'string' && ruleConfig === 'off') {\n return true;\n }\n\n if (typeof ruleConfig === 'string' && ruleConfig !== 'off') {\n throw new Error('\\t- is an array type rule. It must be set to \"off\" if an array is not supplied.');\n }\n\n return isArrayRuleSchemaValid(ruleConfig, minItems);\n};\n\n/**\n * Validates standard rule config\n *\n * @param {Object} ruleConfig Value for standard rule config\n * @return {Boolean} True if config is valid, error if not\n * @static\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst isStandardRuleConfigValid = (ruleConfig: any): any => isStandardRuleSchemaValid(ruleConfig);\n\n/**\n * Validates configuration of a rule\n *\n * @param {Object} ruleModule The rule object.\n * @param {string} ruleName The rule's unique name.\n * @param {Array|String} userConfig The user's configuration for a rule.\n * @param {String|null} source The name of the configuration source to report in any errors.\n * @returns {undefined} No return\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst validateRule = (ruleModule: any, ruleName: any, userConfig: any, source: any): any => {\n if (ruleModule) {\n try {\n switch (ruleModule.ruleType) {\n case RuleType.Array: {\n isArrayRuleConfigValid(userConfig, ruleModule.minItems);\n\n break;\n }\n case RuleType.Object: {\n isObjectRuleConfigValid(userConfig);\n\n break;\n }\n case RuleType.OptionalObject: {\n isOptionalObjRuleConfigValid(userConfig);\n\n break;\n }\n default: {\n isStandardRuleConfigValid(userConfig);\n }\n }\n } catch (error_) {\n const modifiedErrorMessage = `Configuration for rule \"${ruleName}\" is invalid:\\n${error_.message}`;\n\n const error =\n typeof source === 'string' ? new Error(`${source}:\\n\\t${modifiedErrorMessage}`) : new Error(modifiedErrorMessage);\n\n throw error;\n }\n }\n};\n\n/**\n * Validates only the rules of a config object\n *\n * @param {Object} rulesConfig The rules config object to validate.\n * @param {String} source The name of the configuration source to report in any errors.\n * @param {Object} rules Rules object\n * @returns {undefined} No return\n * @static\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const validateRules = (rulesConfig: any, source: any, rules: any): any => {\n if (!rulesConfig) {\n return;\n }\n\n Object.keys(rulesConfig).forEach((ruleName) => {\n const ruleModule = rules.get(ruleName);\n\n validateRule(ruleModule, ruleName, rulesConfig[ruleName], source);\n });\n};\n\n/**\n * Validates entire config object, including top-level properties.\n *\n * @param {Object} config The config object to validate.\n * @param {String} source The name of the configuration source to report in any errors.\n * @param {Object} rules Rules object\n * @returns {undefined} No return\n * @static\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const validate = (config: any, source: any, rules: any): any => {\n isConfigObjectSchemaValid(config, source);\n validateRules(config.rules, source, rules);\n};\n", "import path from 'path';\nimport {applyExtendsIfSpecified} from './applyExtendsIfSpecified';\nimport {applyOverrides} from './applyOverrides';\n\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst debug = require('debug')('npm-package-json-lint:cosmicConfigTransformer');\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const transform = (cwd: any, configBaseDirectory: any, filePathBeingLinted: any): any => {\n debug(`cwd: ${cwd}`);\n debug(`configBaseDirectory`);\n debug(configBaseDirectory);\n\n return (cosmiconfigResult) => {\n debug(`cosmiconfigResult`);\n debug(cosmiconfigResult);\n\n if (!cosmiconfigResult) {\n return null;\n }\n\n const {config, filepath} = cosmiconfigResult;\n\n debug(`cosmiconfigResult.config`);\n debug(config);\n debug(`cosmiconfigResult.filepath`);\n debug(filepath);\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const configDir = configBaseDirectory || path.dirname(filepath || '');\n const npmPackageJsonLintConfig = {...config};\n\n const configAfterExtends = applyExtendsIfSpecified(npmPackageJsonLintConfig, filePathBeingLinted);\n const configAfterOverrides = applyOverrides(\n cwd,\n filePathBeingLinted,\n configAfterExtends.rules,\n configAfterExtends.overrides\n );\n\n return configAfterOverrides;\n };\n};\n", "import path from 'path';\nimport {parseJavaScriptFile, parseJsonFile} from '../file-parser';\n\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst debug = require('debug')('npm-package-json-lint:applyExtendsIfSpecified');\n\n/**\n * Applies values from the 'extends' field in a configuration file.\n *\n * @param {Object} config The configuration information.\n * @param {string} parentName Name of parent. For troubleshooting.\n * @param {Object} originalFilePath Base config file the extends originated from\n * @returns {Object} A new configuration object with all of the 'extends' fields loaded and merged.\n * @private\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst applyExtends = (config: any, parentName: any, originalFilePath: any): any => {\n let configExtends = config.extends;\n\n if (!Array.isArray(config.extends)) {\n configExtends = [config.extends];\n }\n\n // eslint-disable-next-line unicorn/no-array-reduce\n return configExtends.reduceRight((previousConfig, moduleName) => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n const extendsConfig = loadFromModule(moduleName, originalFilePath);\n\n // Merge base object\n const mergedConfig = {...extendsConfig, ...previousConfig};\n\n // Merge rules\n const rules = {...extendsConfig.rules, ...previousConfig.rules};\n\n // Merge plugins, if exist\n const extendsConfigPlugins = Array.isArray(extendsConfig.plugins) ? extendsConfig.plugins : [];\n const previousConfigPlugins = Array.isArray(previousConfig.plugins) ? previousConfig.plugins : [];\n const plugins = [...extendsConfigPlugins, ...previousConfigPlugins];\n const uniquePlugins = [...new Set(plugins)];\n\n // Merge overrides, if exist\n const extendsConfigOverrides = Array.isArray(extendsConfig.overrides) ? extendsConfig.overrides : [];\n const previousConfigOverrides = Array.isArray(previousConfig.overrides) ? previousConfig.overrides : [];\n const overrides = [...extendsConfigOverrides, ...previousConfigOverrides];\n\n // Override merged rules\n mergedConfig.rules = rules;\n\n if (plugins.length > 0) {\n mergedConfig.plugins = uniquePlugins;\n }\n\n if (overrides.length > 0) {\n mergedConfig.overrides = overrides;\n }\n\n return mergedConfig;\n } catch (error) {\n error.message += `\\nReferenced from: ${parentName}`;\n throw error;\n }\n }, config);\n};\n\n/**\n * Gets configuration from a extends config module\n *\n * @param {String} moduleName Name of the configuration module\n * @param {Object} originalFilePath Base config file the extends originated from\n * @return {Object} Configuration object\n * @private\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst loadFromModule = (moduleName: any, originalFilePath: any): any => {\n let config = {};\n let adjustedModuleName = moduleName;\n\n if (moduleName.startsWith('./')) {\n // TODO: handle process.cwd() option\n adjustedModuleName = path.join(process.cwd(), moduleName);\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n config = loadConfigFile(adjustedModuleName);\n } else {\n const resolvedModule = require.resolve(adjustedModuleName, {paths: [path.dirname(originalFilePath)]});\n\n // eslint-disable-next-line import/no-dynamic-require, global-require\n config = require(resolvedModule);\n }\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-expect-error\n if (Object.keys(config).length > 0 && config.extends) {\n config = applyExtends(config, adjustedModuleName, originalFilePath);\n }\n\n return config;\n};\n\n/**\n * Loads a configuration file regardless of the source. Inspects the file path\n * to determine the correctly way to load the config file.\n *\n * @param {Object} filePath The path to the configuration.\n * @returns {Object} The configuration information.\n * @private\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst loadConfigFile = (filePath: any): any => {\n let config = {};\n\n switch (path.extname(filePath)) {\n case '.js':\n config = parseJavaScriptFile(filePath);\n break;\n\n case '.json':\n config = parseJsonFile(filePath);\n break;\n\n default:\n throw new Error(`Unsupport config file extension. File path: ${filePath}`);\n }\n\n return config;\n};\n\n/**\n * Loads a configuration file from the given file path.\n *\n * @param {Object} npmPackageJsonLintConfig Parsed config from cosmicconfig\n * @param {string} filepath the path to the config file\n * @returns {Object} the parsed config object (empty object if there was a parse error)\n * @private\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const applyExtendsIfSpecified = (npmPackageJsonLintConfig: any, filepath: any): any => {\n let config = {...npmPackageJsonLintConfig};\n\n debug('Loading extends, if applicable');\n if (config?.hasOwnProperty('extends') && config.extends) {\n debug('extends property present, applying.');\n config = applyExtends(config, filepath, filepath);\n }\n\n debug('Loading extends complete');\n\n return config;\n};\n", "import fs from 'fs';\nimport stripComments from 'strip-json-comments';\n\n/**\n * Require JavaScript file\n *\n * @param fileName String file path of file to load\n * @internal\n */\n// eslint-disable-next-line import/no-dynamic-require, global-require\nconst requireFile = (fileName: string): NodeRequire => require(fileName);\n\n/**\n * Sychronously reads file from file system\n *\n * @param fileName String file path of file to load\n * @internal\n */\nconst readFile = (fileName: string): string => fs.readFileSync(fileName, 'utf8').replace(/^\\uFEFF/, '');\n\n/**\n * Helper method for throwing errors when file fails to load.\n *\n * @param fileName Name of the file that failed to load.\n * @param err Error object\n * @throws {Error}\n * @internal\n */\nconst handleError = (fileName: string, err: Error): void => {\n throw new Error(`Failed to read config file: ${fileName}. \\nError: ${err.message}`);\n};\n\nexport const sourceSymbol = Symbol('JSON source');\n\n/**\n * Parse a JSON file\n *\n * @param fileName String file path of file to load\n * @return Valid JSON\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const parseJsonFile = (fileName: string): Record<string, any> => {\n let json = {};\n let fileContents = '';\n\n try {\n fileContents = readFile(fileName);\n\n json = JSON.parse(stripComments(fileContents));\n } catch (error) {\n handleError(fileName, error);\n }\n\n Object.defineProperty(json, sourceSymbol, {\n value: fileContents,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n\n return json;\n};\n\n/**\n * Parse a JavaScript file\n *\n * @param fileName String file path of file to load\n * @return Valid JavaScript object\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const parseJavaScriptFile = (fileName: string): Record<string, any> => {\n let obj = {};\n\n try {\n obj = requireFile(fileName);\n } catch (error) {\n handleError(fileName, error);\n }\n\n return obj;\n};\n", "import path from 'path';\nimport globby from 'globby';\n\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst debug = require('debug')('npm-package-json-lint:applyOverrides');\n\n/**\n * Applies values from the 'overrides' field in a configuration file.\n * @param {string} cwd The current working directory.\n * @param {Object} filePath The file path of the file being linted.\n * @param {Object} rules Rules object\n * @param {Object} overrides Overrides object\n * @returns {Object} A new configuration object with all of the 'overrides' applied.\n * @private\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const applyOverrides = (cwd: string, filePath: string, rules: any, overrides?: any[]): any => {\n let finalRules = {...rules};\n\n debug('overrides');\n debug(overrides);\n\n if (overrides) {\n overrides.forEach((override) => {\n const filteredPatterns = override.patterns.filter((pattern) => pattern.length);\n const transformedPatterns = filteredPatterns.map((pattern) =>\n pattern.endsWith(`/package.json`) ? pattern : `${pattern}/package.json`\n );\n\n const globFiles = globby.sync(transformedPatterns, {\n cwd,\n gitignore: true,\n });\n\n debug('globFiles');\n debug(globFiles);\n globFiles.forEach((globFile) => {\n const globbedFilePath = path.resolve(cwd, globFile);\n\n if (filePath === globbedFilePath) {\n finalRules = {...finalRules, ...override.rules};\n }\n });\n });\n }\n\n debug('finalRules');\n debug(finalRules);\n\n return finalRules;\n};\n", "import chalk from 'chalk';\nimport {readdirSync} from 'fs';\nimport path from 'path';\nimport {LintFunction} from './types/lint-function';\nimport {RuleType} from './types/rule-type';\n\nexport interface Rule {\n lint: LintFunction;\n ruleType: RuleType;\n minItems?: number;\n}\n\nexport class Rules {\n rules: Record<string, string>;\n\n constructor() {\n this.rules = {};\n }\n\n /**\n * Loads rules\n *\n * @return Set of rules\n */\n load(): Record<string, string> {\n const rulesDirectory = path.join(__dirname, 'rules');\n\n try {\n readdirSync(rulesDirectory).forEach((filePath) => {\n const beginIndex = 0;\n const endIndex = -3;\n // remove the file extension, e.g. `.js`\n const ruleId = filePath.slice(beginIndex, endIndex);\n const filePathToRuleModule = path.join(rulesDirectory, filePath);\n\n this.registerRule(ruleId, filePathToRuleModule);\n });\n\n return this.rules;\n } catch (error) {\n throw new Error(`Error while loading rules from rules directory - ${error.message}`);\n }\n }\n\n /**\n * Loads a rule module\n *\n * @param ruleId Name of the rule\n * @return Rule module\n */\n get(ruleId: string): Rule {\n const rule = this.rules[ruleId];\n\n if (typeof rule === 'undefined') {\n const errorMsg = `Rule, ${ruleId}, is invalid. Please ensure it matches a valid option.`;\n\n throw new Error(chalk.bold.red(errorMsg));\n }\n\n // eslint-disable-next-line import/no-dynamic-require, global-require, @typescript-eslint/no-var-requires\n const ruleModule = require(this.rules[ruleId]);\n\n return ruleModule;\n }\n\n /**\n * Gets entire rule set\n *\n * @returns Rule set\n */\n getRules(): Record<string, string> {\n return this.rules;\n }\n\n /**\n * Registers a rule in the rules object\n *\n * @param ruleId Name of the rule\n * @param filePathToRuleModule File path to rule\n */\n registerRule(ruleId: string, filePathToRuleModule: string): void {\n this.rules[ruleId] = filePathToRuleModule;\n }\n}\n", "import path from 'path';\nimport {PackageJson} from 'type-fest';\nimport {Ignore} from 'ignore';\nimport {Rules} from '../native-rules';\nimport {parseJsonFile} from '../file-parser';\nimport {LintIssue} from '../lint-issue';\nimport {RuleType} from '../types/rule-type';\nimport {Severity} from '../types/severity';\nimport {aggregateCountsPerFile, aggregateOverallCounts, OverallAggregatedResultCounts} from './results-helper';\nimport {Config} from '../configuration';\nimport {PackageJsonFileLintingResult} from '../types/package-json-linting-result';\n\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst debug = require('debug')('npm-package-json-lint:linter');\n\nexport interface CreateResultObjectOptions {\n /**\n * The current working directory.\n */\n cwd: string;\n /**\n * An optional string representing the package.json file.\n */\n fileName: string;\n /**\n * A flag indicating that the file was skipped.\n */\n ignored: boolean;\n /**\n * A list of issues.\n */\n issues: LintIssue[];\n /**\n * Number of errors.\n */\n errorCount: number;\n /**\n * Number of warnings.\n */\n warningCount: number;\n}\n\n/**\n * Creates a results object.\n *\n * @param options A {@link CreateResultObjectOptions} object\n * @returns The lint results {@link PackageJsonFileLintingResult} for the package.json file.\n * @internal\n */\nconst createResultObject = (options: CreateResultObjectOptions): PackageJsonFileLintingResult => {\n const {cwd, fileName, ignored, issues, errorCount, warningCount} = options;\n\n return {\n filePath: `./${path.relative(cwd, fileName)}`,\n issues,\n ignored,\n errorCount,\n warningCount,\n };\n};\n\n/**\n * Runs configured rules against the provided package.json object.\n *\n * @param packageJsonData Valid package.json data\n * @param configObj Configuration object\n * @param rules Object of rule definitions\n * @return An array of {@link LintIssue} objects.\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst lint = (packageJsonData: any, configObj, rules: Rules): LintIssue[] => {\n const lintIssues = [];\n\n // eslint-disable-next-line no-restricted-syntax, guard-for-in\n for (const rule in configObj) {\n const ruleModule = rules.get(rule);\n\n let severity = Severity.Off;\n let ruleConfig;\n\n if (ruleModule.ruleType === RuleType.Array || ruleModule.ruleType === RuleType.Object) {\n severity = typeof configObj[rule] === 'string' && configObj[rule] === 'off' ? configObj[rule] : configObj[rule][0];\n ruleConfig = typeof configObj[rule] === 'string' ? {} : configObj[rule][1];\n } else if (ruleModule.ruleType === RuleType.OptionalObject) {\n if (typeof configObj[rule] === 'string') {\n severity = configObj[rule];\n ruleConfig = {};\n } else {\n // eslint-disable-next-line prefer-destructuring\n severity = configObj[rule][0];\n // eslint-disable-next-line prefer-destructuring\n ruleConfig = configObj[rule][1];\n }\n } else {\n severity = configObj[rule];\n }\n\n if (severity !== Severity.Off) {\n const lintResult = ruleModule.lint(packageJsonData, severity, ruleConfig);\n\n if (lintResult !== null) {\n lintIssues.push(lintResult);\n }\n }\n }\n\n return lintIssues;\n};\n\n/**\n * Processes package.json object\n *\n * @param cwd The current working directory.\n * @param packageJsonObj An object representation of a package.json file.\n * @param config A config object.\n * @param fileName An optional string representing the package.json file.\n * @param rules An instance of `Rules`.\n * @returns A {@link PackageJsonFileLintingResult} object with the result of linting a package.json file.\n * @internal\n */\nconst processPackageJsonObject = (\n cwd: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n packageJsonObj: PackageJson | any,\n // TODO: Type\n config,\n fileName: string,\n rules: Rules\n): PackageJsonFileLintingResult => {\n const lintIssues = lint(packageJsonObj, config, rules);\n const counts = aggregateCountsPerFile(lintIssues);\n const result = createResultObject({\n cwd,\n fileName,\n ignored: false,\n issues: lintIssues,\n errorCount: counts.errorCount,\n warningCount: counts.warningCount,\n });\n\n return result;\n};\n\n/**\n * Processes a package.json file.\n *\n * @param cwd The current working directory.\n * @param fileName The filename of the file being linted.\n * @param config A config object.\n * @param rules An instance of `Rules`.\n * @returns A {@link PackageJsonFileLintingResult} object with the result of linting a package.json file.\n * @internal\n */\n// TODO: Type\nconst processPackageJsonFile = (cwd: string, fileName: string, config, rules: Rules): PackageJsonFileLintingResult => {\n const packageJsonObj = parseJsonFile(path.resolve(fileName));\n\n return processPackageJsonObject(cwd, packageJsonObj, config, fileName, rules);\n};\n\nexport interface LinterResult {\n results: LintIssue[];\n ignoreCount: number;\n /**\n * Number of errors for the package.json file.\n */\n errorCount: number;\n /**\n * Number of warnings for the package.json file.\n */\n warningCount: number;\n}\n\nexport interface ExecuteOnPackageJsonObjectOptions {\n /**\n * The current working directory.\n */\n cwd: string;\n /**\n * An object representation of a package.json file.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n packageJsonObject: PackageJson | any;\n /**\n * An optional string representing the texts filename.\n */\n filename?: string;\n /**\n * An instance of the `ignore` module.\n */\n ignorer: Ignore;\n /**\n * An instance of {@Config}.\n */\n configHelper: Config;\n /**\n * An instance of {@link Rules}\n */\n rules: Rules;\n}\n\nexport interface OverallLintingResult extends OverallAggregatedResultCounts {\n results: PackageJsonFileLintingResult[];\n}\n\n/**\n * Executes linter on package.json object\n *\n * @param options A {@link ExecuteOnPackageJsonObjectOptions} object\n * @returns The results {@link OverallLintingResult} from linting a collection of package.json files.\n */\nexport const executeOnPackageJsonObject = (options: ExecuteOnPackageJsonObjectOptions): OverallLintingResult => {\n const {cwd, packageJsonObject, filename, ignorer, configHelper, rules} = options;\n\n debug('executing on package.json object');\n const results = [];\n\n const filenameDefaulted = filename || '';\n const resolvedFilename = path.isAbsolute(filenameDefaulted) ? filenameDefaulted : path.resolve(cwd, filenameDefaulted);\n const relativeFilePath = path.relative(cwd, resolvedFilename);\n\n if (ignorer.ignores(relativeFilePath)) {\n debug(`Ignored: ${relativeFilePath}`);\n\n const result = createResultObject({\n cwd,\n fileName: resolvedFilename,\n ignored: true,\n issues: [],\n errorCount: 0,\n warningCount: 0,\n });\n\n results.push(result);\n } else {\n debug(`Getting config for ${resolvedFilename}`);\n const config = configHelper.getConfigForFile(resolvedFilename);\n\n debug(`Config fetched for ${resolvedFilename}`);\n const result = processPackageJsonObject(cwd, packageJsonObject, config, resolvedFilename, rules);\n\n results.push(result);\n }\n\n debug('Aggregating overall counts');\n const stats = aggregateOverallCounts(results);\n\n debug('stats');\n debug(stats);\n\n return {\n results,\n ignoreCount: stats.ignoreCount,\n errorCount: stats.errorCount,\n warningCount: stats.warningCount,\n };\n};\n\nexport interface ExecuteOnPackageJsonFilesOptions {\n /**\n * The current working directory.\n */\n cwd: string;\n /**\n * An array of files and directory names.\n */\n fileList: string[];\n /**\n * An instance of the `ignore` module.\n */\n ignorer: Ignore;\n /**\n * An instance of {@Config}.\n */\n configHelper: Config;\n /**\n * An instance of {@link Rules}\n */\n rules: Rules;\n}\n\n/**\n * Executes the current configuration on an array of file and directory names.\n * @param options A {@link ExecuteOnPackageJsonFilesOptions} object\n * @returns The results {@link OverallLintingResult} from linting a collection of package.json files.\n */\nexport const executeOnPackageJsonFiles = (options: ExecuteOnPackageJsonFilesOptions): OverallLintingResult => {\n const {cwd, fileList, ignorer, configHelper, rules} = options;\n\n debug('executing on package.json files');\n const results = fileList.map((filePath) => {\n const relativeFilePath = path.relative(cwd, filePath);\n\n if (ignorer.ignores(relativeFilePath)) {\n debug(`Ignored: ${relativeFilePath}`);\n\n return createResultObject({\n cwd,\n fileName: filePath,\n ignored: true,\n issues: [],\n errorCount: 0,\n warningCount: 0,\n });\n }\n\n debug(`Getting config for ${filePath}`);\n const config = configHelper.getConfigForFile(filePath);\n\n debug(`Config fetched for ${filePath}`);\n\n return processPackageJsonFile(cwd, filePath, config, rules);\n });\n\n debug('Aggregating overall counts');\n const stats = aggregateOverallCounts(results);\n\n debug('stats');\n debug(stats);\n\n return {\n results,\n ignoreCount: stats.ignoreCount,\n errorCount: stats.errorCount,\n warningCount: stats.warningCount,\n };\n};\n", "export enum Severity {\n Error = 'error',\n Warning = 'warning',\n Off = 'off',\n}\n", "import {LintIssue} from '../lint-issue';\nimport {Severity} from '../types/severity';\nimport {PackageJsonFileLintingResult} from '../types/package-json-linting-result';\n\n/**\n * A result count object for a files.\n * @typedef {Object} FileResultCounts\n * @property {number} errorCount Number of errors for a file result.\n * @property {number} warningCount Number of warnings for a file result.\n */\n\nexport interface PackageJsonFileAggregatedResultCounts {\n errorCount: number;\n warningCount: number;\n}\n\n/**\n * Aggregates the count of errors and warning for a package.json file.\n *\n * @param issues Array of {@link LintIssue} objects from a package.json file.\n * @returns Counts object {@link PackageJsonFileAggregatedResultCounts}.\n */\nexport const aggregateCountsPerFile = (issues: LintIssue[]): PackageJsonFileAggregatedResultCounts => {\n const incrementOne = 1;\n\n // eslint-disable-next-line unicorn/no-array-reduce\n return issues.reduce(\n (counts, issue) => {\n const isErrorSeverity = issue.severity === Severity.Error;\n const newErrorCount = isErrorSeverity ? counts.errorCount + incrementOne : counts.errorCount;\n const newWarningCount = isErrorSeverity ? counts.warningCount : counts.warningCount + incrementOne;\n\n return {\n errorCount: newErrorCount,\n warningCount: newWarningCount,\n };\n },\n {\n errorCount: 0,\n warningCount: 0,\n }\n );\n};\n\nexport interface OverallAggregatedResultCounts {\n /**\n * Total number of ignored files.\n */\n ignoreCount: number;\n /**\n * Total number of errors.\n */\n errorCount: number;\n /**\n * Total number of warnings.\n */\n warningCount: number;\n}\n\n/**\n * Aggregates the count of errors and warnings for all package.json files.\n *\n * @param results Array of {@link PackageJsonFileLintingResult} objects from all package.json files.\n * @returns Counts object {@link OverallAggregatedResultCounts}\n */\nexport const aggregateOverallCounts = (results: PackageJsonFileLintingResult[]): OverallAggregatedResultCounts =>\n // eslint-disable-next-line unicorn/no-array-reduce\n results.reduce(\n (counts, result) => ({\n ignoreCount: result.ignored ? counts.ignoreCount + 1 : counts.ignoreCount,\n errorCount: counts.errorCount + result.errorCount,\n warningCount: counts.warningCount + result.warningCount,\n }),\n {\n ignoreCount: 0,\n errorCount: 0,\n warningCount: 0,\n }\n );\n", "import path from 'path';\nimport globby from 'globby';\n\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst debug = require('debug')('npm-package-json-lint:getFileList');\n\n/**\n * Generates a list of files to lint based on a list of provided patterns\n *\n * @param {Array<string>} patterns An array of patterns\n * @param {string} cwd The current working directory.\n * @returns {Array<string>} An array a files to lint.\n */\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport const getFileList = (patterns, cwd) => {\n debug('patterns');\n debug(patterns);\n\n // step 1 - filter out empty entries\n const filteredPatterns = patterns.filter((pattern) => pattern.length);\n\n debug('filteredPatterns');\n debug(filteredPatterns);\n\n // step 2 - convert directories to globs\n const globPatterns = filteredPatterns.map((pattern) =>\n pattern.endsWith(`/package.json`) ? pattern : `${pattern}/**/package.json`\n );\n\n globPatterns.push('!**/node_modules/**');\n\n debug('globPatterns');\n debug(globPatterns);\n\n const files = [];\n const addedFiles = new Set();\n\n const globFiles = globby.sync(globPatterns, {\n cwd,\n gitignore: true,\n });\n\n debug('globFiles');\n debug(globFiles);\n\n globFiles.forEach((globFile) => {\n const filePath = path.resolve(cwd, globFile);\n\n if (addedFiles.has(filePath)) {\n return;\n }\n\n addedFiles.add(filePath);\n files.push(filePath);\n });\n\n debug('Final file list from `getFileList`');\n debug(files);\n\n return files;\n};\n", "import fs from 'fs';\nimport path from 'path';\nimport ignore, {Ignore} from 'ignore';\n\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst debug = require('debug')('npm-package-json-lint:getIgnorer');\n\nconst DEFAULT_IGNORE_FILENAME = '.npmpackagejsonlintignore';\nconst FILE_NOT_FOUND_ERROR_CODE = 'ENOENT';\n\n/**\n * Generates ignorer based on ignore file content.\n *\n * @param cwd Current work directory.\n * @param ignorePath Ignore path.\n * @returns An instance of an Ignorer\n */\nexport const getIgnorer = (cwd: string, ignorePath: string): Ignore => {\n const ignoreFilePath = ignorePath || DEFAULT_IGNORE_FILENAME;\n\n debug(`ignoreFilePath: ${ignoreFilePath}`);\n const absoluteIgnoreFilePath = path.isAbsolute(ignoreFilePath) ? ignoreFilePath : path.resolve(cwd, ignoreFilePath);\n\n debug(`absoluteIgnoreFilePath: ${absoluteIgnoreFilePath}`);\n let ignoreText = '';\n\n try {\n ignoreText = fs.readFileSync(absoluteIgnoreFilePath, 'utf8');\n } catch (readError) {\n if (readError.code !== FILE_NOT_FOUND_ERROR_CODE) {\n throw readError;\n }\n }\n\n debug('Ignore text added');\n\n return ignore().add(ignoreText);\n};\n", "import chalk from 'chalk';\nimport logSymbols from 'log-symbols';\nimport {Severity} from './types/severity';\n\n/**\n * A lint issue\n */\nexport class LintIssue {\n /**\n * Unique, lowercase, hyphen-separate name for the lint\n *\n * @type {string}\n * @memberof LintIssue\n */\n lintId: string;\n\n /**\n * 'error' or 'warning'\n *\n * @type {Severity}\n * @memberof LintIssue\n */\n severity: Severity;\n\n /**\n * Name of the node in the JSON the lint audits\n *\n * @type {string}\n * @memberof LintIssue\n */\n node: string;\n\n /**\n * Human-friendly message to users\n *\n * @type {string}\n * @memberof LintIssue\n */\n lintMessage: string;\n\n /**\n * Creates an instance of LintIssue.\n * @param lintId Unique, lowercase, hyphen-separate name for the lint\n * @param severity 'error' or 'warning'\n * @param node Name of the node in the JSON the lint audits\n * @param lintMessage Human-friendly message to users\n * @memberof LintIssue\n */\n constructor(lintId: string, severity: Severity, node: string, lintMessage: string) {\n this.lintId = lintId;\n this.severity = severity;\n this.node = node;\n this.lintMessage = lintMessage;\n }\n\n /**\n * Helper to convert the LintIssue to a printable string\n *\n * @returns {string} Human-friendly message about the lint issue\n */\n toString(): string {\n const logSymbol = this.severity === Severity.Error ? logSymbols.error : logSymbols.warning;\n const formattedLintId = chalk.cyan.bold(this.lintId);\n const formattedNode = chalk.magenta.bold(this.node);\n const formattedMessage =\n this.severity === Severity.Error ? chalk.red.bold(this.lintMessage) : chalk.yellow(this.lintMessage);\n\n return `${logSymbol} ${formattedLintId} - node: ${formattedNode} - ${formattedMessage}`;\n }\n}\n"],
|
|
5
|
+
"mappings": "mzFAAA,6GCAA,OAAuB,2BACvB,EAAkB,oBCDlB,MAA8B,uBCA9B,OAAgB,kBAChB,GAAsB,yBAEhB,EAAM,GAAI,YAAI,CAAC,UAAW,GAAM,aAAc,EAAI,CAAC,EAEzD,eAAU,CAAG,EASb,GAAM,GAAqB,AAAC,GAAW,EAAO,IAAI,AAAC,GAAU,MAAO,EAAM;AAAA,CAAW,EAAE,KAAK,EAAE,EAExF,EAAqB,CACzB,KAAM,SACN,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,UAAM,OAAO,KAAK,WAAW,EAErG,MAAO,GAAG,KAAa,aAA2B,OAAmB,GACvE,CACF",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/cli.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var qe=Object.create;var q=Object.defineProperty;var Ae=Object.getOwnPropertyDescriptor;var Me=Object.getOwnPropertyNames,ee=Object.getOwnPropertySymbols,Te=Object.getPrototypeOf,te=Object.prototype.hasOwnProperty,Ve=Object.prototype.propertyIsEnumerable;var ne=(n,e,t)=>e in n?q(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,p=(n,e)=>{for(var t in e||(e={}))te.call(e,t)&&ne(n,t,e[t]);if(ee)for(var t of ee(e))Ve.call(e,t)&&ne(n,t,e[t]);return n};var Ne=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var De=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Me(e))!te.call(n,o)&&o!==t&&q(n,o,{get:()=>e[o],enumerable:!(r=Ae(e,o))||r.enumerable});return n};var g=(n,e,t)=>(t=n!=null?qe(Te(n)):{},De(e||!n||!n.__esModule?q(t,"default",{value:n,enumerable:!0}):t,n));var
|
|
2
|
+
var qe=Object.create;var q=Object.defineProperty;var Ae=Object.getOwnPropertyDescriptor;var Me=Object.getOwnPropertyNames,ee=Object.getOwnPropertySymbols,Te=Object.getPrototypeOf,te=Object.prototype.hasOwnProperty,Ve=Object.prototype.propertyIsEnumerable;var ne=(n,e,t)=>e in n?q(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,p=(n,e)=>{for(var t in e||(e={}))te.call(e,t)&&ne(n,t,e[t]);if(ee)for(var t of ee(e))Ve.call(e,t)&&ne(n,t,e[t]);return n};var Ne=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var De=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Me(e))!te.call(n,o)&&o!==t&&q(n,o,{get:()=>e[o],enumerable:!(r=Ae(e,o))||r.enumerable});return n};var g=(n,e,t)=>(t=n!=null?qe(Te(n)):{},De(e||!n||!n.__esModule?q(t,"default",{value:n,enumerable:!0}):t,n));var Ee=Ne((Zn,ln)=>{ln.exports={name:"npm-package-json-lint",version:"0.0.0",description:"Configurable linter for package.json files.",keywords:["lint","linter","package.json","audit","auditor","npm-package-json-lint"],homepage:"https://github.com/tclindner/npm-package-json-lint",bugs:{url:"https://github.com/tclindner/npm-package-json-lint/issues"},author:"Thomas Lindner",repository:{type:"git",url:"https://github.com/tclindner/npm-package-json-lint.git"},bin:{npmPkgJsonLint:"dist/cli.js"},files:["CONTRIBUTING.md","dist"],main:"dist/api.js",types:"dist/src/api.d.ts",scripts:{build:"npm run esbuild && npm run tsc",esbuild:"node esbuild.config.js",eslint:"eslint . --format=node_modules/eslint-formatter-pretty",npmpackagejsonlint:"node dist/cli.js ./package.json",lint:"npm run eslint && npm run npmpackagejsonlint",test:"npm run build && jest","test:ci":"jest --runInBand",tsc:"tsc --project tsconfig.json"},dependencies:{ajv:"^6.12.6","ajv-errors":"^1.0.1",chalk:"^4.1.2",cosmiconfig:"^7.0.1",debug:"^4.3.4",globby:"^11.1.0",ignore:"^5.2.0","is-plain-obj":"^3.0.0","jsonc-parser":"^3.0.0","log-symbols":"^4.1.0",meow:"^9.0.0",plur:"^4.0.0",semver:"^7.3.5",slash:"^3.0.0","strip-json-comments":"^3.1.1","type-fest":"^2.12.0","validate-npm-package-name":"^3.0.0"},devDependencies:{"@types/jest":"^27.4.1","@types/node":"^17.0.21","@typescript-eslint/eslint-plugin":"^5.15.0",esbuild:"^0.14.27","esbuild-node-externals":"^1.4.1",eslint:"^8.11.0","eslint-config-tc":"^22.0.0","eslint-config-typescript-tc":"^6.0.0","eslint-formatter-pretty":"^4.1.0","eslint-plugin-eslint-comments":"^3.2.0","eslint-plugin-import":"^2.25.4","eslint-plugin-jest":"^26.1.1","eslint-plugin-prettier":"^4.0.0","eslint-plugin-unicorn":"^41.0.1",figures:"^3.2.0",jest:"^27.5.1","npm-package-json-lint-config-default":"^5.0.0","npm-package-json-lint-config-tc":"^6.0.0",prettier:"^2.6.0","ts-jest":"^27.1.3",typescript:"^4.6.2"},engines:{node:">=14.0.0",npm:">=6.0.0"},license:"MIT"}});var Q=g(require("chalk")),$e=g(require("meow"));var Je=g(require("is-plain-obj")),Y=g(require("slash"));var D=require("cosmiconfig");var re=g(require("ajv")),oe=g(require("ajv-errors")),P=new re.default({allErrors:!0,jsonPointers:!0});(0,oe.default)(P);var F=n=>n.map(e=>` - ${e.message}
|
|
3
3
|
`).join(""),A={type:"string",enum:["off","warning","error"],errorMessage:{type:"severity must be a string.",enum:'severity must be either "off", "warning", or "error".'}},We=n=>({type:"array",items:[A,{type:"array",minItems:n,uniqueItems:!0,errorMessage:{type:"the second item in an array rule config must be an array.",minItems:"the second item in an array rule config must have at least 1 item.",uniqueItems:"the second item in an array rule config must have unique items."}}],minItems:2,maxItems:2,additionalItems:!1,errorMessage:{type:'rule config must be an array, e.g. ["error", ["value1", "value2"]].',minItems:'array rules must have two items, severity and options array. e.g. ["error", ["value1", "value2"]].',maxItems:'array rules must have two items, severity and options array. e.g. ["error", ["value1", "value2"]].',additionalItems:'array rules are only allowed two items, severity and the list is values. e.g. ["error", ["value1", "value2"]].'}}),_e={type:"array",items:[A,{type:"object",errorMessage:{type:"the second item in an object rule config must be an object."}}],minItems:2,maxItems:2,additionalItems:!1,errorMessage:{type:'rule config must be an array, e.g. ["error", {}].',minItems:'object rules must have two items, severity and options object. e.g. ["error", {}].',maxItems:'object rules must have two items, severity and options object. e.g. ["error", {}].',additionalItems:'object rules are only allowed two items, severity and options object. e.g. ["error", {}].'}},He={type:"array",items:[{type:"string",errorMessage:{type:"each exception must be a string."}}],uniqueItems:!0,minItems:1,errorMessage:{type:"expections must be an array.",minItems:"expections must have at least 1 item.",uniqueItems:"expections must have unique items."}};var M=n=>{let e=P.compile(A);if(!e(n))throw new Error(`${F(e.errors)}`);return!0},se=(n,e)=>{let t=P.compile(We(e));if(!t(n))throw new Error(`${F(t.errors)}`);return!0},T=n=>{let e=P.compile(_e);if(!e(n))throw new Error(`${F(e.errors)}`);return!0},ie=n=>{let e=P.compile(He);if(!e(n))throw new Error(`${F(e.errors)}`);return!0};var Ue=n=>{if(typeof n=="string"&&n==="off")return!0;if(typeof n=="string"&&n!=="off")throw new Error(' - is an object type rule. It must be set to "off" if an object is not supplied.');return T(n)},Ge=n=>typeof n=="string"?M(n):T(n)&&n[1].hasOwnProperty("exceptions")?ie(n[1].exceptions):!0,ze=(n,e)=>{if(typeof n=="string"&&n==="off")return!0;if(typeof n=="string"&&n!=="off")throw new Error(' - is an array type rule. It must be set to "off" if an array is not supplied.');return se(n,e)},Ye=n=>M(n),Ke=(n,e,t,r)=>{if(n)try{switch(n.ruleType){case"array":{ze(t,n.minItems);break}case"object":{Ue(t);break}case"optionalObject":{Ge(t);break}default:Ye(t)}}catch(o){let s=`Configuration for rule "${e}" is invalid:
|
|
4
4
|
${o.message}`;throw typeof r=="string"?new Error(`${r}:
|
|
5
|
-
${s}`):new Error(s)}},ae=(n,e,t)=>{!n||Object.keys(n).forEach(r=>{let o=t.get(r);Ke(o,r,n[r],e)})};var de=g(require("path"));var
|
|
5
|
+
${s}`):new Error(s)}},ae=(n,e,t)=>{!n||Object.keys(n).forEach(r=>{let o=t.get(r);Ke(o,r,n[r],e)})};var de=g(require("path"));var E=g(require("path"));var le=g(require("fs")),ce=g(require("strip-json-comments")),Qe=n=>require(n),Xe=n=>le.default.readFileSync(n,"utf8").replace(/^\uFEFF/,""),ge=(n,e)=>{throw new Error(`Failed to read config file: ${n}.
|
|
6
6
|
Error: ${e.message}`)},Ze=Symbol("JSON source"),R=n=>{let e={},t="";try{t=Xe(n),e=JSON.parse((0,ce.default)(t))}catch(r){ge(n,r)}return Object.defineProperty(e,Ze,{value:t,enumerable:!1,writable:!1,configurable:!1}),e},ue=n=>{let e={};try{e=Qe(n)}catch(t){ge(n,t)}return e};var V=require("debug")("npm-package-json-lint:applyExtendsIfSpecified"),pe=(n,e,t)=>{let r=n.extends;return Array.isArray(n.extends)||(r=[n.extends]),r.reduceRight((o,s)=>{try{let i=en(s,t),a=p(p({},i),o),l=p(p({},i.rules),o.rules),c=Array.isArray(i.plugins)?i.plugins:[],f=Array.isArray(o.plugins)?o.plugins:[],y=[...c,...f],O=[...new Set(y)],S=Array.isArray(i.overrides)?i.overrides:[],Se=Array.isArray(o.overrides)?o.overrides:[],Z=[...S,...Se];return a.rules=l,y.length>0&&(a.plugins=O),Z.length>0&&(a.overrides=Z),a}catch(i){throw i.message+=`
|
|
7
|
-
Referenced from: ${e}`,i}},n)},en=(n,e)=>{let t={},r=n;if(n.startsWith("./"))r=
|
|
7
|
+
Referenced from: ${e}`,i}},n)},en=(n,e)=>{let t={},r=n;if(n.startsWith("./"))r=E.default.join(process.cwd(),n),t=nn(r);else{let o=require.resolve(r,{paths:[E.default.dirname(e)]});t=require(o)}return Object.keys(t).length>0&&t.extends&&(t=pe(t,r,e)),t},nn=n=>{let e={};switch(E.default.extname(n)){case".js":e=ue(n);break;case".json":e=R(n);break;default:throw new Error(`Unsupport config file extension. File path: ${n}`)}return e},I=(n,e)=>{let t=p({},n);return V("Loading extends, if applicable"),(t==null?void 0:t.hasOwnProperty("extends"))&&t.extends&&(V("extends property present, applying."),t=pe(t,e,e)),V("Loading extends complete"),t};var me=g(require("path")),fe=g(require("globby")),k=require("debug")("npm-package-json-lint:applyOverrides"),J=(n,e,t,r)=>{let o=p({},t);return k("overrides"),k(r),r&&r.forEach(s=>{let a=s.patterns.filter(c=>c.length).map(c=>c.endsWith("/package.json")?c:`${c}/package.json`),l=fe.default.sync(a,{cwd:n,gitignore:!0});k("globFiles"),k(l),l.forEach(c=>{let f=me.default.resolve(n,c);e===f&&(o=p(p({},o),s.rules))})}),k("finalRules"),k(o),o};var h=require("debug")("npm-package-json-lint:cosmicConfigTransformer"),N=(n,e,t)=>(h(`cwd: ${n}`),h("configBaseDirectory"),h(e),r=>{if(h("cosmiconfigResult"),h(r),!r)return null;let{config:o,filepath:s}=r;h("cosmiconfigResult.config"),h(o),h("cosmiconfigResult.filepath"),h(s);let i=e||de.default.dirname(s||""),a=p({},o),l=I(a,t);return J(n,t,l.rules,l.overrides)});var m=require("debug")("npm-package-json-lint:Config"),tn=0,W=class{constructor(e,t,r,o,s){t&&(this.config=I(t,"PassedConfig")),this.cwd=e,this.configFile=r,this.configBaseDirectory=o,this.rules=s}getConfigForFile(e){m(`Getting config for ${e}`);let t=e;m(`filePathToSearch: ${t}`);let r;if(typeof this.config>"u")m("User passed config is undefined."),this.configFile?(m("Config file specified, loading it."),r=(0,D.cosmiconfigSync)("npmpackagejsonlint",{transform:N(this.cwd,this.configBaseDirectory,e)}).load(this.configFile)):(m("Config file wasn't specified, searching for config."),r=(0,D.cosmiconfigSync)("npmpackagejsonlint",{transform:N(this.cwd,this.configBaseDirectory,t)}).search(t));else{m("User passed config is set, using it.");let o=this.config;m(`Applying overrides to config for ${e}`),r=J(this.cwd,e,o.rules,o.overrides),m(`Overrides applied for ${e}`)}if(!r)throw new Error(`No npm-package-json-lint configuration found.
|
|
8
8
|
${t}`);if(Object.keys(r).length===tn)throw new Error(`No rules specified in configuration.
|
|
9
|
-
${t}`);return m(`Overrides applied for ${e}`),m("Final Config"),m(r),ae(r,"cli",this.rules),r}};var ye=g(require("chalk")),he=require("fs"),_=g(require("path")),H=class{constructor(){this.rules={}}load(){let e=_.default.join(__dirname,"rules");try{return(0,he.readdirSync)(e).forEach(t=>{let s=t.slice(0,-3),i=_.default.join(e,t);this.registerRule(s,i)}),this.rules}catch(t){throw new Error(`Error while loading rules from rules directory - ${t.message}`)}}get(e){if(typeof this.rules[e]>"u"){let o=`Rule, ${e}, is invalid. Please ensure it matches a valid option.`;throw new Error(ye.default.bold.red(o))}return require(this.rules[e])}getRules(){return this.rules}registerRule(e,t){this.rules[e]=t}};var j=g(require("path"));var we=n=>n.reduce((t,r)=>{let o=r.severity==="error",s=o?t.errorCount+1:t.errorCount,i=o?t.warningCount:t.warningCount+1;return{errorCount:s,warningCount:i}},{errorCount:0,warningCount:0}),B=n=>n.reduce((e,t)=>({ignoreCount:t.ignored?e.ignoreCount+1:e.ignoreCount,errorCount:e.errorCount+t.errorCount,warningCount:e.warningCount+t.warningCount}),{ignoreCount:0,errorCount:0,warningCount:0});var u=require("debug")("npm-package-json-lint:linter"),U=n=>{let{cwd:e,fileName:t,ignored:r,issues:o,errorCount:s,warningCount:i}=n;return{filePath:`./${j.default.relative(e,t)}`,issues:o,ignored:r,errorCount:s,warningCount:i}},rn=(n,e,t)=>{let r=[];for(let o in e){let s=t.get(o),i="off",a;if(s.ruleType==="array"||s.ruleType==="object"?(i=typeof e[o]=="string"&&e[o]==="off"?e[o]:e[o][0],a=typeof e[o]=="string"?{}:e[o][1]):s.ruleType==="optionalObject"?typeof e[o]=="string"?(i=e[o],a={}):(i=e[o][0],a=e[o][1]):i=e[o],i!=="off"){let l=s.lint(n,i,a);l!==null&&r.push(l)}}return r},je=(n,e,t,r,o)=>{let s=rn(e,t,o),i=we(s);return U({cwd:n,fileName:r,ignored:!1,issues:s,errorCount:i.errorCount,warningCount:i.warningCount})},on=(n,e,t,r)=>{let o=R(j.default.resolve(e));return je(n,o,t,e,r)},ke=n=>{let{cwd:e,packageJsonObject:t,filename:r,ignorer:o,configHelper:s,rules:i}=n;u("executing on package.json object");let a=[],l=r||"",c=j.default.isAbsolute(l)?l:j.default.resolve(e,l),f=j.default.relative(e,c);if(o.ignores(f)){u(`Ignored: ${f}`);let O=U({cwd:e,fileName:c,ignored:!0,issues:[],errorCount:0,warningCount:0});a.push(O)}else{u(`Getting config for ${c}`);let O=s.getConfigForFile(c);u(`Config fetched for ${c}`);let S=je(e,t,O,c,i);a.push(S)}u("Aggregating overall counts");let y=B(a);return u("stats"),u(y),{results:a,ignoreCount:y.ignoreCount,errorCount:y.errorCount,warningCount:y.warningCount}},xe=n=>{let{cwd:e,fileList:t,ignorer:r,configHelper:o,rules:s}=n;u("executing on package.json files");let i=t.map(l=>{let c=j.default.relative(e,l);if(r.ignores(c))return u(`Ignored: ${c}`),U({cwd:e,fileName:l,ignored:!0,issues:[],errorCount:0,warningCount:0});u(`Getting config for ${l}`);let f=o.getConfigForFile(l);return u(`Config fetched for ${l}`),on(e,l,f,s)});u("Aggregating overall counts");let a=B(i);return u("stats"),u(a),{results:i,ignoreCount:a.ignoreCount,errorCount:a.errorCount,warningCount:a.warningCount}};var ve=g(require("path")),Ce=g(require("globby")),d=require("debug")("npm-package-json-lint:getFileList"),Oe=(n,e)=>{d("patterns"),d(n);let t=n.filter(a=>a.length);d("filteredPatterns"),d(t);let r=t.map(a=>a.endsWith("/package.json")?a:`${a}/**/package.json`);r.push("!**/node_modules/**"),d("globPatterns"),d(r);let o=[],s=new Set,i=Ce.default.sync(r,{cwd:e,gitignore:!0});return d("globFiles"),d(i),i.forEach(a=>{let l=ve.default.resolve(e,a);s.has(l)||(s.add(l),o.push(l))}),d("Final file list from `getFileList`"),d(o),o};var Pe=g(require("fs")),z=g(require("path")),Fe=g(require("ignore")),G=require("debug")("npm-package-json-lint:getIgnorer"),sn=".npmpackagejsonlintignore",an="ENOENT",Re=(n,e)=>{let t=e||sn;G(`ignoreFilePath: ${t}`);let r=z.default.isAbsolute(t)?t:z.default.resolve(n,t);G(`absoluteIgnoreFilePath: ${r}`);let o="";try{o=Pe.default.readFileSync(r,"utf8")}catch(s){if(s.code!==an)throw s}return G("Ignore text added"),(0,Fe.default)().add(o)};var L=require("debug")("npm-package-json-lint:NpmPackageJsonLint"),cn=
|
|
9
|
+
${t}`);return m(`Overrides applied for ${e}`),m("Final Config"),m(r),ae(r,"cli",this.rules),r}};var ye=g(require("chalk")),he=require("fs"),_=g(require("path")),H=class{constructor(){this.rules={}}load(){let e=_.default.join(__dirname,"rules");try{return(0,he.readdirSync)(e).forEach(t=>{let s=t.slice(0,-3),i=_.default.join(e,t);this.registerRule(s,i)}),this.rules}catch(t){throw new Error(`Error while loading rules from rules directory - ${t.message}`)}}get(e){if(typeof this.rules[e]>"u"){let o=`Rule, ${e}, is invalid. Please ensure it matches a valid option.`;throw new Error(ye.default.bold.red(o))}return require(this.rules[e])}getRules(){return this.rules}registerRule(e,t){this.rules[e]=t}};var j=g(require("path"));var we=n=>n.reduce((t,r)=>{let o=r.severity==="error",s=o?t.errorCount+1:t.errorCount,i=o?t.warningCount:t.warningCount+1;return{errorCount:s,warningCount:i}},{errorCount:0,warningCount:0}),B=n=>n.reduce((e,t)=>({ignoreCount:t.ignored?e.ignoreCount+1:e.ignoreCount,errorCount:e.errorCount+t.errorCount,warningCount:e.warningCount+t.warningCount}),{ignoreCount:0,errorCount:0,warningCount:0});var u=require("debug")("npm-package-json-lint:linter"),U=n=>{let{cwd:e,fileName:t,ignored:r,issues:o,errorCount:s,warningCount:i}=n;return{filePath:`./${j.default.relative(e,t)}`,issues:o,ignored:r,errorCount:s,warningCount:i}},rn=(n,e,t)=>{let r=[];for(let o in e){let s=t.get(o),i="off",a;if(s.ruleType==="array"||s.ruleType==="object"?(i=typeof e[o]=="string"&&e[o]==="off"?e[o]:e[o][0],a=typeof e[o]=="string"?{}:e[o][1]):s.ruleType==="optionalObject"?typeof e[o]=="string"?(i=e[o],a={}):(i=e[o][0],a=e[o][1]):i=e[o],i!=="off"){let l=s.lint(n,i,a);l!==null&&r.push(l)}}return r},je=(n,e,t,r,o)=>{let s=rn(e,t,o),i=we(s);return U({cwd:n,fileName:r,ignored:!1,issues:s,errorCount:i.errorCount,warningCount:i.warningCount})},on=(n,e,t,r)=>{let o=R(j.default.resolve(e));return je(n,o,t,e,r)},ke=n=>{let{cwd:e,packageJsonObject:t,filename:r,ignorer:o,configHelper:s,rules:i}=n;u("executing on package.json object");let a=[],l=r||"",c=j.default.isAbsolute(l)?l:j.default.resolve(e,l),f=j.default.relative(e,c);if(o.ignores(f)){u(`Ignored: ${f}`);let O=U({cwd:e,fileName:c,ignored:!0,issues:[],errorCount:0,warningCount:0});a.push(O)}else{u(`Getting config for ${c}`);let O=s.getConfigForFile(c);u(`Config fetched for ${c}`);let S=je(e,t,O,c,i);a.push(S)}u("Aggregating overall counts");let y=B(a);return u("stats"),u(y),{results:a,ignoreCount:y.ignoreCount,errorCount:y.errorCount,warningCount:y.warningCount}},xe=n=>{let{cwd:e,fileList:t,ignorer:r,configHelper:o,rules:s}=n;u("executing on package.json files");let i=t.map(l=>{let c=j.default.relative(e,l);if(r.ignores(c))return u(`Ignored: ${c}`),U({cwd:e,fileName:l,ignored:!0,issues:[],errorCount:0,warningCount:0});u(`Getting config for ${l}`);let f=o.getConfigForFile(l);return u(`Config fetched for ${l}`),on(e,l,f,s)});u("Aggregating overall counts");let a=B(i);return u("stats"),u(a),{results:i,ignoreCount:a.ignoreCount,errorCount:a.errorCount,warningCount:a.warningCount}};var ve=g(require("path")),Ce=g(require("globby")),d=require("debug")("npm-package-json-lint:getFileList"),Oe=(n,e)=>{d("patterns"),d(n);let t=n.filter(a=>a.length);d("filteredPatterns"),d(t);let r=t.map(a=>a.endsWith("/package.json")?a:`${a}/**/package.json`);r.push("!**/node_modules/**"),d("globPatterns"),d(r);let o=[],s=new Set,i=Ce.default.sync(r,{cwd:e,gitignore:!0});return d("globFiles"),d(i),i.forEach(a=>{let l=ve.default.resolve(e,a);s.has(l)||(s.add(l),o.push(l))}),d("Final file list from `getFileList`"),d(o),o};var Pe=g(require("fs")),z=g(require("path")),Fe=g(require("ignore")),G=require("debug")("npm-package-json-lint:getIgnorer"),sn=".npmpackagejsonlintignore",an="ENOENT",Re=(n,e)=>{let t=e||sn;G(`ignoreFilePath: ${t}`);let r=z.default.isAbsolute(t)?t:z.default.resolve(n,t);G(`absoluteIgnoreFilePath: ${r}`);let o="";try{o=Pe.default.readFileSync(r,"utf8")}catch(s){if(s.code!==an)throw s}return G("Ignore text added"),(0,Fe.default)().add(o)};var L=require("debug")("npm-package-json-lint:NpmPackageJsonLint"),cn=Ee(),gn=0,un=n=>n.severity==="error",Ie=n=>(0,Je.default)(n),pn=(n,e)=>!e&&!Ie(n)||e&&(n||Ie(n)),mn=n=>{let e=[];return n.forEach(t=>{let r=t.issues.filter(un);if(r.length>gn){let o={issues:r,errorCount:r.length,warningCount:0};e.push(Object.assign(t,o))}}),e},K=class{constructor(e){let{cwd:t,packageJsonObject:r,packageJsonFilePath:o,config:s,configFile:i,configBaseDirectory:a,patterns:l,quiet:c,ignorePath:f,fix:y}=e;this.cwd=(0,Y.default)(t||process.cwd()),this.packageJsonObject=r,this.packageJsonFilePath=o&&(0,Y.default)(o),this.patterns=l,this.quiet=c||!1,this.ignorePath=f||"",this.fix=y||!1,this.version=cn.version,this.rules=new H,this.rules.load(),this.configHelper=new W(this.cwd,s,i,a,this.rules)}lint(){if(L("Starting lint"),pn(this.packageJsonObject,this.patterns))throw new Error("You must pass npm-package-json-lint a `patterns` glob or a `packageJsonObject` string, though not both.");let e=Re(this.cwd,this.ignorePath),t;if(this.patterns){if(L("Linting using patterns"),!Array.isArray(this.patterns))throw new TypeError("Patterns must be an array.");let r=Oe(this.patterns,this.cwd);t=xe({cwd:this.cwd,fileList:r,ignorer:e,configHelper:this.configHelper,rules:this.rules})}else L("Linting using passed object."),t=ke({cwd:this.cwd,packageJsonObject:this.packageJsonObject,ignorer:e,filename:this.packageJsonFilePath,configHelper:this.configHelper,rules:this.rules});return this.quiet?{results:mn(t.results),ignoreCount:t.ignoreCount,errorCount:t.errorCount,warningCount:t.warningCount}:(L("lint complete"),t)}};var b=g(require("chalk")),x=g(require("plur")),$=0,fn=1,dn=n=>{n.forEach(e=>{console.log(e.toString())})},yn=(n,e)=>{let{filePath:t,issues:r,ignored:o,errorCount:s,warningCount:i}=n;if(o)console.log(""),console.log(`${b.default.yellow.underline(t)} - ignored`);else if(s>$||!e&&i>$){console.log(""),console.log(b.default.underline(t)),dn(r);let a=`${s} ${(0,x.default)("error",s)}`,l=`${i} ${(0,x.default)("warning",i)}`;console.log(b.default.red.bold(a)),e||console.log(b.default.yellow.bold(l))}},hn=(n,e)=>{let{errorCount:t,warningCount:r,ignoreCount:o}=n;if(t>$||r>$){let s=`${t} ${(0,x.default)("error",t)}`,i=`${r} ${(0,x.default)("warning",r)}`,a=`${o} ${(0,x.default)("file",o)} ignored`;console.log(""),console.log(b.default.underline("Totals")),console.log(b.default.red.bold(s)),e||(console.log(b.default.yellow.bold(i)),console.log(b.default.yellow.bold(a)))}},Le=(n,e)=>{n.results.forEach(t=>{yn(t,e)}),n.results.length>fn&&hn(n,e)};var w=require("debug")("npm-package-json-lint:cli"),C={zeroClean:0,oneMissingTarget:1,twoLintErrorsDetected:2,runTimeException:3,exceedMaxWarnings:4},bn=(0,$e.default)(`
|
|
10
10
|
Usage
|
|
11
11
|
$ npmPkgJsonLint <patterns>
|
|
12
12
|
|