Socket
Socket
Sign inDemoInstall

amd-conversion-analyser

Package Overview
Dependencies
Maintainers
2
Versions
11
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

amd-conversion-analyser - npm Package Compare versions

Comparing version 1.4.0 to 1.5.0

test/data/amdModuleNoName.js

2

bin/amd.js
#!/usr/bin/env node
'use strict';
require('../dist/index.js');

@@ -0,1 +1,2 @@

'use strict';
module.exports = {

@@ -2,0 +3,0 @@ "patterns": ["**/*.js"],

@@ -1,1 +0,1 @@

'use strict';var argv=require('minimist')(process.argv.slice(2)),path=require('path'),fs=require('fs'),ConversionDetector=require('./lib/conversiondetector'),FILE_LOG_LEVELS=['debug','info','warn','error'],DEFAULT_FILE_LOG_LEVEL='info';function printHelp(){console.log('Run:'),console.log(' node index.js /your/source/dir <options>'),console.log('Options:'),console.log(' --globals // Show information about used globals per file'),console.log(' --globals-summary // List all globals used by most to least frequent usage'),console.log(' --no-utf8 // Don\'t do pretty print'),console.log(' --no-summary // Don\'t show the conversion summary'),console.log(' --no-files // Don\'t list the files'),console.log(' --no-ok // Don\'t show already converted files'),console.log(' --config <file> // Use this config file'),console.log(' --idea // Show a link to open the file directly in IntelliJ IDEA'),console.log(' --idea-globals // Show a link to open the file directly in IntelliJ IDEA at the position of the found global'),console.log(' --file-log-level // Set log level for amd conversion status ('+FILE_LOG_LEVELS.join(', ')+'); default: '+DEFAULT_FILE_LOG_LEVEL)}function main(){if(argv.help)return void printHelp();if('undefined'==typeof argv._[0])return console.log('No input directory given. Run with --help for options'),console.log(),void printHelp();var b=[argv.config,path.join(argv._[0],'.amdanalyserrc'),path.join(__dirname,'../','config.js')].find(function(d){try{return!!d&&(fs.accessSync(d,fs.R_OK),fs.statSync(d).isFile())}catch(f){return!1}});try{console.log('Loading config from ',path.resolve(b));var a=require(path.resolve(b))}catch(d){return void console.error('Could not load config file: '+d.message)}a.symbols=require('./lib/symbols')(!1!==argv.utf8),argv['file-log-level']=FILE_LOG_LEVELS.includes(argv['file-log-level'])?argv['file-log-level']:DEFAULT_FILE_LOG_LEVEL;var c=new ConversionDetector(argv._[0],a,argv,console);c.run()}main();
'use strict';var argv=require('minimist')(process.argv.slice(2)),path=require('path'),fs=require('fs'),ConversionDetector=require('./lib/conversiondetector'),FILE_LOG_LEVELS=['debug','info','warn','error'],DEFAULT_FILE_LOG_LEVEL='info';function printHelp(){console.log('Run:'),console.log(' node index.js /your/source/dir <options>'),console.log('Options:'),console.log(' --globals // Show information about used globals per file'),console.log(' --globals-summary // List all globals used by most to least frequent usage'),console.log(' --no-utf8 // Don\'t do pretty print'),console.log(' --no-summary // Don\'t show the conversion summary'),console.log(' --no-files // Don\'t list the files'),console.log(' --no-ok // Don\'t show already converted files'),console.log(' --save <file> // Save results to file'),console.log(' --config <file> // Use this config file'),console.log(' --idea // Show a link to open the file directly in IntelliJ IDEA'),console.log(' --idea-globals // Show a link to open the file directly in IntelliJ IDEA at the position of the found global'),console.log(' --file-log-level // Set log level for amd conversion status ('+FILE_LOG_LEVELS.join(', ')+'); default: '+DEFAULT_FILE_LOG_LEVEL)}function main(){if(argv.help)return void printHelp();if('undefined'==typeof argv._[0])return console.log('No input directory given. Run with --help for options'),console.log(),void printHelp();var a=[argv.config,path.join(argv._[0],'.amdanalyserrc'),path.join(__dirname,'../','config.js')].find(function(a){try{return!!a&&(fs.accessSync(a,fs.R_OK),fs.statSync(a).isFile())}catch(a){return!1}});try{console.log('Loading config from ',path.resolve(a));var b=require(path.resolve(a))}catch(a){return void console.error('Could not load config file: '+a.message)}b.symbols=require('./lib/symbols')(!1!==argv.utf8),argv['file-log-level']=FILE_LOG_LEVELS.includes(argv['file-log-level'])?argv['file-log-level']:DEFAULT_FILE_LOG_LEVEL;var c=new ConversionDetector(argv._[0],b,argv,console);c.run()}main();

@@ -1,1 +0,1 @@

"use strict";var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},acorn=require("acorn"),glob=require("globby"),detectAMD=require("./detect-amd"),detectGlobals=require("acorn-globals"),globals=require("globals"),arrayUniq=require("array-uniq"),_=require("lodash"),fs=require("fs"),path=require("path"),colors=require("colors/safe"),winston=require("winston");colors.setTheme({ok:"grey",warn:"yellow",error:"red"});function ConversionDetector(a,b,c){function d(t){return new winston.Logger({level:t})}var h=b.symbols,j=b.patterns||["**/*.js"],k=[],l=d(),m=d(),n=d(),o=d(c["file-log-level"]),p=d(),q=!!c["globals-summary"],r=c.globals||c["idea-globals"],s=!1!==c.ok;(function(){r&&l.add(winston.transports.Console,{showLevel:!1}),q&&m.add(winston.transports.Console,{showLevel:!1}),!1!==c.files&&(n.add(winston.transports.Console,{showLevel:!1}),o.add(winston.transports.Console,{showLevel:!1})),!1!==c.summary&&p.add(winston.transports.Console,{showLevel:!1})})(),this._excludedGlobals=[],this._globals=[],this._countNonAMD=0,this._countGlobals=0,this._countAMDDefine=0,this._countAMDRequire=0,this.setupExcludedGlobals=function(t,u){var v="undefined"==typeof u?[]:u;return t&&Object.keys(t).filter(function(w){return t[w]}).forEach(function(w){var x=globals[w];x&&(v=arrayUniq(v.concat(Object.keys(x))))}),v},this.getFilename=function(t){return path.basename(t)},this.markAsNonAMD=function(t){++this._countNonAMD,k.push({filepath:t,amd:!1,is:h.ERR,msg:"Not an AMD module"})},this.markAsAMD=function(t,u){++this._countAMDDefine,this.findGlobals(t,u)},this.markAsAMDRequire=function(t,u){++this._countAMDRequire,this.findGlobals(t,u)},this.trimToEndOfVariableName=function(t){for(var w,u=[],v=t.parents.length-1;0<=v;v--)if(w=t.parents[v],"Identifier"==w.type)u.push(w.name);else if("MemberExpression"==w.type)u.push(w.property.name||w.property.value);else if("ThisExpression"==w.type)u.push("this");else break;return u.join(".")},this.isExcludedVariable=function(t){var u=[],v=t.split(".").some(function(w){u.push(w);var x=u.join(".");return-1<b.exclude.variables.indexOf(x)});return v},this.isAMDDefine=function(t){return"object"===("undefined"==typeof t?"undefined":_typeof(t))&&t.hasOwnProperty("type")&&"define"===t.type},this.isAMDRequire=function(t){return"object"===("undefined"==typeof t?"undefined":_typeof(t))&&t.hasOwnProperty("type")&&"require"===t.type},this.isNamedAMDModule=function(t){return this.isAMDDefine(t)&&t.hasOwnProperty("name")&&!!t.name},this.getRelevantGlobals=function(t){var u=this;return detectGlobals(t).filter(function(v){if(-1<u._excludedGlobals.indexOf(v.name))return!1;var w=u.getRelevantOccurrences(t,v.nodes);return 0<w.length})},this.getRelevantOccurrences=function(t,u){var v=this;return u?u.filter(function(w){var x=v.trimToEndOfVariableName(w);return!v.isExcludedVariable(x)&&(++v._countGlobals,!0)}):[]},this.processRelevantOccurrences=function(t,u,v){var w=this;return u?u.map(function(x){var y=acorn.getLineInfo(t,x.start),z=w.trimToEndOfVariableName(x),A=w.isExcludedVariable(z);return{varName:z,lineInfo:y,isExcluded:A,fullFilePath:v}}):[]},this.getIDEALink=function(t,u,v){return u&&v?colors.grey.underline("http://localhost:63342/api/file/"+process.cwd()+"/"+t+":"+u+":"+v):colors.underline("http://localhost:63342/api/file/"+process.cwd()+"/"+t)},this.findGlobals=function(t,u){var x=this;try{var v=this.getRelevantGlobals(u),w=[];if(0===v.length)return void k.push({filepath:t,amd:!0,globals:!1,is:h.OK});r&&v.forEach(function(y){var z=x.processRelevantOccurrences(u,y.nodes,t);w=w.concat(z),x._globals=x._globals.concat(z)}),k.push({filepath:t,amd:!0,is:h.ALERT,globals:!0,globalsList:w,msg:"Globals detected"})}catch(y){k.push({filepath:t,amd:!0,is:h.ERR,err:y,msg:"Error finding globals"})}},this.handleFile=function(t,u,v,w){try{if(t)throw new Error(t.message?t.message:t);var x=detectAMD(u),y=x&&x[0];this.isNamedAMDModule(y)?this.markAsAMD(v,u):this.isAMDRequire(y)?this.markAsAMDRequire(v,u):this.markAsNonAMD(v)}catch(z){k.push({filepath:v,is:h.ERR,err:z,msg:"Error parsing file"})}w()},this.printFileSummary=function(){var w=this,t={};t[h.ERR]={color:colors.error,logger:o.error},t[h.ALERT]={color:colors.warn,logger:o.warn},t[h.OK]={color:colors.ok,logger:o.info};var u=_.sortBy(k,"filepath"),v="";u.forEach(function(x){var y=x.is,z=x.filepath,A=x.err,B=x.msg,C=x.globals,D=x.globalsList;if(s||y!==h.OK){var _consoleFns$is=t[y],E=_consoleFns$is.color,F=_consoleFns$is.logger,G=y===h.OK?colors.green(y):E(y),H=w.getFilename(z),I=path.dirname(z),K="";B&&(K+=": "+B),A&&(K+=": \""+A.message+"\""),c.idea&&(K+=" ("+w.getIDEALink(z)+")"),v!==I&&(v=I,n.info(""+I)),F(E(""+(" "+G+" "+H)+K)),C&&D&&D.filter(function(L){return!L.isExcluded}).forEach(function(_ref){var L=_ref.varName,M=_ref.lineInfo,N=_ref.fullFilePath,O=colors.cyan(M.line+":"+M.column),P=" "+O+" "+L;c["idea-globals"]&&(P+=" ("+w.getIDEALink(N,M.line,M.column)+")"),l.warn(P)})}})},this.printGlobalsSummary=function(){if(q){!1!==c.files&&m.info("=====================================");var t=[];_(this._globals).filter(function(u){return!u.isExcluded}).countBy("varName").forEach(function(u,v){return t.push({varName:v,count:u})}),_(t).sortBy(["count","varName"]).forEach(function(_ref2){var u=_ref2.count,v=_ref2.varName;m.info(v+" - "+colors.warn(u))})}},this.printSummary=function(t){if(t)throw t;if(!1!==c.summary){(!1!==c.files||q)&&p.info("=====================================");var u=this._countAMDDefine+this._countAMDRequire,v=100*(u/(u+this._countNonAMD));p.info("Files identified as AMD modules: "+u),p.info(" define() calls: "+this._countAMDDefine),p.info(" require() calls: "+this._countAMDRequire),p.warn(colors.error("Files not converted: "+this._countNonAMD)),p.warn(colors.warn("Illegal globals found: "+this._countGlobals)),p.info((isNaN(v)?0:Math.round(v,2))+"% converted")}},this.getGlobs=function(t){var u=[],v=t+"/";return j.forEach(function(w){u.push(v+w)}),b.exclude.patterns&&b.exclude.patterns.forEach(function(w){u.push("!"+v+w)}),u},this.run=function(){var u=this;this._excludedGlobals=this.setupExcludedGlobals(b.env,Object.keys(globals.builtin));var t=glob.sync(this.getGlobs(a));t.forEach(function(v){var w=fs.readFileSync(v,"utf8");u.handleFile(null,w,v,function(){})}),this.printFileSummary(),this.printGlobalsSummary(),this.printSummary()}}module.exports=ConversionDetector;
"use strict";var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},acorn=require("acorn"),glob=require("globby"),detectAMD=require("./detect-amd"),detectGlobals=require("acorn-globals"),globals=require("globals"),arrayUniq=require("array-uniq"),_=require("lodash"),fs=require("fs"),path=require("path"),colors=require("colors/safe"),winston=require("winston");colors.setTheme({ok:"grey",warn:"yellow",error:"red"});function ConversionDetector(a,b,c){function d(a){return new winston.Logger({level:a})}var f=b.symbols,e=b.patterns||["**/*.js"],g=[],h=d(),i=d(),j=d(),k=d(c["file-log-level"]),l=d(),m=!!c["globals-summary"],n=c.globals||c["idea-globals"],o=!1!==c.ok;(function(){n&&h.add(winston.transports.Console,{showLevel:!1}),m&&i.add(winston.transports.Console,{showLevel:!1}),!1!==c.files&&(j.add(winston.transports.Console,{showLevel:!1}),k.add(winston.transports.Console,{showLevel:!1})),!1!==c.summary&&l.add(winston.transports.Console,{showLevel:!1})})(),this._excludedGlobals=[],this._globals=[],this._countNonAMD=0,this._countGlobals=0,this._countAMDDefine=0,this._countAMDRequire=0,this.setupExcludedGlobals=function(a,b){var c="undefined"==typeof b?[]:b;return a&&Object.keys(a).filter(function(b){return a[b]}).forEach(function(a){var b=globals[a];b&&(c=arrayUniq(c.concat(Object.keys(b))))}),c},this.getFilename=function(a){return path.basename(a)},this.markAsNonAMD=function(a){++this._countNonAMD,g.push({filepath:a,amd:!1,is:f.ERR,msg:"Not an AMD module"})},this.markAsAMD=function(a,b){++this._countAMDDefine,this.findGlobals(a,b)},this.markAsAMDRequire=function(a,b){++this._countAMDRequire,this.findGlobals(a,b)},this.trimToEndOfVariableName=function(a){for(var b,c=[],d=a.parents.length-1;0<=d;d--)if(b=a.parents[d],"Identifier"===b.type)c.push(b.name);else if("MemberExpression"===b.type)c.push(b.property.name||b.property.value);else if("ThisExpression"===b.type)c.push("this");else break;return namePath.join(".")},this.isExcludedVariable=function(a){var c=[],d=a.split(".").some(function(a){c.push(a);var d=c.join(".");return-1<b.exclude.variables.indexOf(d)});return d},this.isAMDDefine=function(a){return"object"===("undefined"==typeof a?"undefined":_typeof(a))&&a.hasOwnProperty("type")&&"define"===a.type},this.isAMDRequire=function(a){return"object"===("undefined"==typeof a?"undefined":_typeof(a))&&a.hasOwnProperty("type")&&"require"===a.type},this.isNamedAMDModule=function(a){return this.isAMDDefine(a)&&a.hasOwnProperty("name")&&!!a.name},this.getRelevantGlobals=function(a){var b=this;return detectGlobals(a).filter(function(c){if(-1<b._excludedGlobals.indexOf(c.name))return!1;var d=b.getRelevantOccurrences(a,c.nodes);return 0<d.length})},this.getRelevantOccurrences=function(a,b){var c=this;return b?b.filter(function(a){var b=c.trimToEndOfVariableName(a);return!c.isExcludedVariable(b)&&(++c._countGlobals,!0)}):[]},this.processRelevantOccurrences=function(a,b,c){var d=this;return b?b.map(function(b){var e=acorn.getLineInfo(a,b.start),f=d.trimToEndOfVariableName(b),g=d.isExcludedVariable(f);return{varName:f,lineInfo:e,isExcluded:g,fullFilePath:c}}):[]},this.getIDEALink=function(a,b,c){return b&&c?colors.grey.underline("http://localhost:63342/api/file/"+process.cwd()+"/"+a+":"+b+":"+c):colors.underline("http://localhost:63342/api/file/"+process.cwd()+"/"+a)},this.findGlobals=function(a,b){var c=this;try{var d=this.getRelevantGlobals(b),e=[];if(0===d.length)return void g.push({filepath:a,amd:!0,globals:!1,is:f.OK});n&&d.forEach(function(d){var f=c.processRelevantOccurrences(b,d.nodes,a);e=e.concat(f),c._globals=c._globals.concat(f)}),g.push({filepath:a,amd:!0,is:f.ALERT,globals:!0,globalsList:e,msg:"Globals detected"})}catch(b){g.push({filepath:a,amd:!0,is:f.ERR,err:b,msg:"Error finding globals"})}},this.handleFile=function(a,b,c,d){try{if(a)throw new Error(a.message?a.message:a);var e=detectAMD(b),h=e&&e[0];this.isNamedAMDModule(h)?this.markAsAMD(c,b):this.isAMDDefine(h)?this.markAsAMD(c,b):this.isAMDRequire(h)?this.markAsAMDRequire(c,b):this.markAsNonAMD(c)}catch(a){g.push({filepath:c,is:f.ERR,err:a,msg:"Error parsing file"})}d()},this.printFileSummary=function(){var a=this,b={};b[f.ERR]={color:colors.error,logger:k.error},b[f.ALERT]={color:colors.warn,logger:k.warn},b[f.OK]={color:colors.ok,logger:k.info};var d=_.sortBy(g,"filepath"),e="";d.forEach(function(d){var g=d.is,i=d.filepath,k=d.err,l=d.msg,m=d.globals,n=d.globalsList;if(o||g!==f.OK){var p=b[g],q=p.color,r=p.logger,s=g===f.OK?colors.green(g):q(g),t=a.getFilename(i),u=path.dirname(i),v="";l&&(v+=": "+l),k&&(v+=": \""+k.message+"\""),c.idea&&(v+=" ("+a.getIDEALink(i)+")"),e!==u&&(e=u,j.info(""+u)),r(q(""+(" "+s+" "+t)+v)),m&&n&&n.filter(function(a){return!a.isExcluded}).forEach(function(b){var d=b.varName,e=b.lineInfo,f=b.fullFilePath,g=colors.cyan(e.line+":"+e.column),i=" "+g+" "+d;c["idea-globals"]&&(i+=" ("+a.getIDEALink(f,e.line,e.column)+")"),h.warn(i)})}})},this.saveResults=function(){var a=c.save;if(a){var b=_.groupBy(g,function(a){return path.dirname(a.filepath)}),d={files:b,globals:this._globals,stats:{}};d.stats.percentageOfCovered=this._percentageOfConverted(),d.stats.countTotalModules=this._totalModuleCount(),d.stats.countNonAMD=this._countNonAMD,d.stats.countGlobals=this._countGlobals,d.stats.countAMDDefine=this._countAMDDefine,d.stats.countAMDRequire=this._countAMDRequire,this._saveToFile(d,a)}},this._saveToFile=function(a,b){fs.writeFile(b,JSON.stringify(a),function(a){if(a)return console.error(a)})},this.printGlobalsSummary=function(){if(m){!1!==c.files&&i.info("=====================================");var a=[];_(this._globals).filter(function(a){return!a.isExcluded}).countBy("varName").forEach(function(b,c){return a.push({varName:c,count:b})}),_(a).sortBy(["count","varName"]).forEach(function(a){var b=a.count,c=a.varName;i.info(c+" - "+colors.warn(b))})}},this._totalModuleCount=function(){return this._countAMDDefine+this._countAMDRequire},this._percentageOfConverted=function(){var a=this._totalModuleCount();return 100*(a/(a+this._countNonAMD))},this.printSummary=function(a){if(a)throw a;if(!1!==c.summary){(!1!==c.files||m)&&l.info("=====================================");var b=this._percentageOfConverted();l.info("Files identified as AMD modules: "+this._totalModuleCount()),l.info(" define() calls: "+this._countAMDDefine),l.info(" require() calls: "+this._countAMDRequire),l.warn(colors.error("Files not converted: "+this._countNonAMD)),l.warn(colors.warn("Illegal globals found: "+this._countGlobals)),l.info((isNaN(b)?0:Math.round(b,2))+"% converted")}},this.getGlobs=function(a){var c=[],d=a+"/";return e.forEach(function(a){c.push(d+a)}),b.exclude.patterns&&b.exclude.patterns.forEach(function(a){c.push("!"+d+a)}),c},this.run=function(){var c=this;this._excludedGlobals=this.setupExcludedGlobals(b.env,Object.keys(globals.builtin));var d=glob.sync(this.getGlobs(a));d.forEach(function(a){var b=fs.readFileSync(a,"utf8");c.handleFile(null,b,a,function(){})}),this.printFileSummary(),this.printGlobalsSummary(),this.printSummary(),this.saveResults()}}module.exports=ConversionDetector;

@@ -1,1 +0,1 @@

'use strict';var _=require('lodash'),acorn=require('acorn'),walk=require('acorn/dist/walk');function reallyParse(a){try{return acorn.parse(a,{ecmaVersion:6,allowReturnOutsideFunction:!0,allowImportExportEverywhere:!0,allowHashBang:!0})}catch(b){return acorn.parse(a,{ecmaVersion:5,allowReturnOutsideFunction:!0,allowImportExportEverywhere:!0,allowHashBang:!0})}}function isAMDDefine(a){return'CallExpression'===a.type&&a.callee&&'Identifier'===a.callee.type&&'define'===a.callee.name}function isAMDRequire(a){return'CallExpression'===a.type&&a.callee&&'Identifier'===a.callee.type&&'require'===a.callee.name}function asAMDNode(a,b){var c=a.arguments[0],d=a.arguments[1],e=a.arguments[2];'ArrayExpression'===c.type&&(e=d,d=c,c=void 0),d||e?'ArrayExpression'!==d.type&&(e=d,d=[]):(e=c,d=void 0,e=void 0),d?'ArrayExpression'===d.type&&(d=_.map(d.elements,function(g){return g.value})):d=[];var f={node:a,type:b,deps:d};return c&&(f.name=c.value),f}function shouldCountRequire(a){return 0<a.deps.length}function detectAMD(a){var b=[],c='string'==typeof a?reallyParse(a):a;return walk.ancestor(c,{CallExpression:function CallExpression(d){if(isAMDDefine(d))b.push(asAMDNode(d,'define'));else if(isAMDRequire(d)){var e=asAMDNode(d,'require');shouldCountRequire(e)&&b.push(e)}}}),b}module.exports=detectAMD;
'use strict';var _=require('lodash'),acorn=require('acorn'),walk=require('acorn/dist/walk');function reallyParse(a){try{return acorn.parse(a,{ecmaVersion:6,allowReturnOutsideFunction:!0,allowImportExportEverywhere:!0,allowHashBang:!0})}catch(b){return acorn.parse(a,{ecmaVersion:5,allowReturnOutsideFunction:!0,allowImportExportEverywhere:!0,allowHashBang:!0})}}function isAMDDefine(a){return'CallExpression'===a.type&&a.callee&&'Identifier'===a.callee.type&&'define'===a.callee.name}function isAMDRequire(a){return'CallExpression'===a.type&&a.callee&&'Identifier'===a.callee.type&&'require'===a.callee.name}function asAMDNode(a,b){var c=a.arguments[0],d=a.arguments[1],e=a.arguments[2];'ArrayExpression'===c.type&&(e=d,d=c,c=void 0),d||e?'ArrayExpression'!==d.type&&(e=d,d=[]):(e=c,d=void 0,e=void 0),d?'ArrayExpression'===d.type&&(d=_.map(d.elements,function(a){return a.value})):d=[];var f={node:a,type:b,deps:d};return c&&(f.name=c.value),f}function shouldCountRequire(a){return 0<a.deps.length}function detectAMD(a){var b=[],c='string'==typeof a?reallyParse(a):a;return walk.ancestor(c,{CallExpression:function CallExpression(a){if(isAMDDefine(a))b.push(asAMDNode(a,'define'));else if(isAMDRequire(a)){var c=asAMDNode(a,'require');shouldCountRequire(c)&&b.push(c)}}}),b}module.exports=detectAMD;
{
"name": "amd-conversion-analyser",
"version": "1.4.0",
"version": "1.5.0",
"license": "Apache-2.0",

@@ -8,6 +8,7 @@ "description": "",

"scripts": {
"compile": "./node_modules/.bin/babel -d dist/ src/",
"compile": "babel -d dist/ src/",
"preversion": "npm run compile",
"prepublishOnly": "npm run compile",
"test": "./node_modules/istanbul/lib/cli.js cover ./node_modules/mocha/bin/_mocha --print detail",
"lint": "./node_modules/.bin/eslint ."
"test": "istanbul cover node_modules/mocha/bin/_mocha --print detail",
"lint": "eslint ."
},

@@ -34,2 +35,6 @@ "bin": {

"email": "mrzymski@atlassian.com"
},
{
"name": "Mateusz Szerszynski",
"email": "mszerszynski@atlassian.com"
}

@@ -43,4 +48,4 @@ ],

"escape-regex-string": "^1.0.4",
"globals": "^9.1.0",
"globby": "^4.0.0",
"globals": "^10.1.0",
"globby": "^6.1.0",
"lodash": "^4.17.4",

@@ -51,18 +56,18 @@ "minimist": "^1.2.0",

"devDependencies": {
"babel-cli": "6.22.2",
"babel-cli": "^6.26.0",
"babel-plugin-uglify": "1.0.2",
"babel-preset-babili": "0.0.10",
"babel-preset-es2015": "6.22.0",
"chai": "^3.3.0",
"babel-preset-env": "^1.6.0",
"babel-preset-minify": "^0.2.0",
"chai": "^4.1.2",
"chai-things": "^0.2.0",
"eslint": "^4.7.2",
"istanbul": "^0.4.2",
"mocha": "^2.3.3",
"mocha": "^3.5.3",
"rewire": "^2.3.4",
"sinon": "^1.17.1",
"eslint": "3.15.0"
"sinon": "^3.3.0"
},
"engines": {
"node": ">=6",
"npm": ">=4"
"node": ">=8",
"npm": ">=5"
}
}

@@ -23,2 +23,3 @@ # AMD conversion analyser

--no-ok // Don't show already converted files
--save <file> // Save results to file
--config <file> // Use this config file (absolute path only)

@@ -25,0 +26,0 @@ --idea // Show a link to open the file directly in IntelliJ IDEA

@@ -0,1 +1,2 @@

'use strict';
const argv = require('minimist')(process.argv.slice(2));

@@ -19,3 +20,4 @@ const path = require('path');

console.log(" --no-ok // Don't show already converted files");
console.log(" --config \<file\> // Use this config file");
console.log(" --save <file> // Save results to file");
console.log(" --config <file> // Use this config file");
console.log(" --idea // Show a link to open the file directly in IntelliJ IDEA");

@@ -50,3 +52,3 @@ console.log(" --idea-globals // Show a link to open the file directly in IntelliJ IDEA at the position of the found global");

} catch(e) {
return false
return false;
}

@@ -53,0 +55,0 @@ });

@@ -0,1 +1,2 @@

'use strict';
let acorn = require("acorn");

@@ -109,7 +110,7 @@ let glob = require("globby");

const parent = node.parents[i];
if (parent.type == "Identifier") {
if (parent.type === "Identifier") {
namePath.push(parent.name);
} else if (parent.type == "MemberExpression") {
} else if (parent.type === "MemberExpression") {
namePath.push(parent.property.name || parent.property.value);
} else if (parent.type == "ThisExpression") {
} else if (parent.type === "ThisExpression") {
namePath.push("this");

@@ -228,10 +229,14 @@ } else {

try {
if (err) throw new Error(err.message ? err.message : err);
const result = detectAMD(content);
const firstNodeInFile = result && result[0];
if (this.isNamedAMDModule(firstNodeInFile)) {
this.markAsAMD(fullFilePath, content);
}
else if (this.isAMDRequire(firstNodeInFile)) {
else if (this.isAMDDefine(firstNodeInFile)) {
this.markAsAMD(fullFilePath, content);
}
else if (this.isAMDRequire(firstNodeInFile)) {
this.markAsAMDRequire(fullFilePath, content);

@@ -300,4 +305,39 @@ }

});
}
};
this.saveResults = function() {
const saveLocation = argv['save'];
if (!saveLocation) {
return;
}
const sortedMessages = _.groupBy(fileMessages,
message => path.dirname(message.filepath)
);
const toSave = {
files: sortedMessages,
globals: this._globals,
stats: {}
};
toSave.stats.percentageOfCovered = this._percentageOfConverted();
toSave.stats.countTotalModules = this._totalModuleCount();
toSave.stats.countNonAMD = this._countNonAMD;
toSave.stats.countGlobals = this._countGlobals;
toSave.stats.countAMDDefine = this._countAMDDefine;
toSave.stats.countAMDRequire = this._countAMDRequire;
this._saveToFile(toSave, saveLocation);
};
this._saveToFile = function(toSave, saveLocation) {
fs.writeFile(saveLocation, JSON.stringify(toSave), function(err) {
if (err) {
return console.error(err);
}
});
};
this.printGlobalsSummary = function () {

@@ -325,2 +365,11 @@ if (!isGlobalsSummaryEnabled) {

this._totalModuleCount = function() {
return this._countAMDDefine + this._countAMDRequire;
};
this._percentageOfConverted = function() {
const totalModuleCount = this._totalModuleCount();
return totalModuleCount / (totalModuleCount + this._countNonAMD) * 100;
};
this.printSummary = function (err) {

@@ -337,6 +386,5 @@ if (err) throw err;

const totalModuleCount = this._countAMDDefine + this._countAMDRequire;
const percentage = totalModuleCount / (totalModuleCount + this._countNonAMD) * 100;
const percentage = this._percentageOfConverted();
summaryLogger.info(`Files identified as AMD modules: ${totalModuleCount}`);
summaryLogger.info(`Files identified as AMD modules: ${this._totalModuleCount()}`);
summaryLogger.info(` define() calls: ${this._countAMDDefine}`);

@@ -382,2 +430,3 @@ summaryLogger.info(` require() calls: ${this._countAMDRequire}`);

this.printSummary();
this.saveResults();
};

@@ -384,0 +433,0 @@ }

@@ -0,1 +1,2 @@

'use strict';
const _ = require('lodash');

@@ -57,3 +58,3 @@ const acorn = require('acorn');

if (!deps) {
deps = []
deps = [];
}

@@ -60,0 +61,0 @@ else if (deps.type === 'ArrayExpression') {

@@ -0,1 +1,2 @@

'use strict';
var path = require("path");

@@ -31,3 +32,3 @@ var chai = require("chai");

node.parents = [node];
})
});

@@ -39,3 +40,2 @@ this.acorn = {getLineInfo: sinon.stub()};

this.fs = {readFileSync: sinon.stub()};
this.dir = {readFiles: sinon.stub()};
this.stubbedInfoLogger = sinon.stub();

@@ -61,3 +61,2 @@ this.stubbedWarnLogger = sinon.stub();

"fs": this.fs,
"dir": this.dir,
"acorn": this.acorn

@@ -157,2 +156,6 @@ });

var globals = acornGlobals(" Foo.Bar.baz ");
console.log(globals.map(g => g.name + ": { nodes: " + g.nodes.map(n => n.name + ":" + n.type + ": { parents: " + n.parents.map(p => p.name + ":" + p.type) + " }") + " }"));
expect(globals.length).to.equal(1);
expect(globals[0].name).to.equal("Foo");
expect(globals[0].nodes.length).to.equal(1);
var result = this.detector.trimToEndOfVariableName(globals[0].nodes[0]);

@@ -360,8 +363,8 @@

expect(result[0]).to.have.deep.property("lineInfo.line", 13)
expect(result[0]).to.have.deep.property("lineInfo.column", 0);
expect(result[1]).to.have.deep.property("lineInfo.line", 1337)
expect(result[1]).to.have.deep.property("lineInfo.column", 666);
expect(result[2]).to.have.deep.property("lineInfo.line", 999)
expect(result[2]).to.have.deep.property("lineInfo.column", 123);
expect(result[0]).to.have.nested.property("lineInfo.line", 13);
expect(result[0]).to.have.nested.property("lineInfo.column", 0);
expect(result[1]).to.have.nested.property("lineInfo.line", 1337);
expect(result[1]).to.have.nested.property("lineInfo.column", 666);
expect(result[2]).to.have.nested.property("lineInfo.line", 999);
expect(result[2]).to.have.nested.property("lineInfo.column", 123);
});

@@ -563,5 +566,4 @@ });

var error = {message: "Y U NO WORK"};
expect(detector.handleFile.bind(detector.handleFile, error, "", "/foo/bar/error.js")).to.throw(error);
detector.handleFile(error, "", "/foo/bar/index.js", next);
detector.handleFile(error, "", "/foo/bar/error.js", next);
detector.handleFile(null, "", "/foo/bar/index.js", next);
detector.printFileSummary();

@@ -568,0 +570,0 @@

@@ -0,1 +1,2 @@

'use strict';
var chai = require("chai");

@@ -89,7 +90,7 @@ chai.should();

expect(result).to.have.lengthOf(5);
expect(result).to.have.deep.property('[0].type', 'define');
expect(result).to.have.deep.property('[1].type', 'require');
expect(result).to.have.deep.property('[2].type', 'define');
expect(result).to.have.deep.property('[3].type', 'define');
expect(result).to.have.deep.property('[4].type', 'require');
expect(result).to.have.nested.property('[0].type', 'define');
expect(result).to.have.nested.property('[1].type', 'require');
expect(result).to.have.nested.property('[2].type', 'define');
expect(result).to.have.nested.property('[3].type', 'define');
expect(result).to.have.nested.property('[4].type', 'require');
});

@@ -96,0 +97,0 @@

@@ -0,1 +1,2 @@

'use strict';
let chai = require("chai");

@@ -73,5 +74,5 @@ chai.should();

sinon.stub(detector, "printSummary", function () {
sinon.stub(detector, "printSummary").callsFake(function () {
originalPrintSummary();
done();
originalPrintSummary();
});

@@ -87,3 +88,3 @@

it("should log the AMD module as OK to console", function () {
it("should log the Named AMD module as OK to console", function () {
expect(stubs.info.withArgs(sinon.match("amdModule.js")).args[0][0])

@@ -93,2 +94,7 @@ .to.have.string(baseConfig.symbols.OK);

it("should log the Unnamed AMD module as OK to console", function () {
expect(stubs.info.withArgs(sinon.match("amdModuleNoName.js")).args[0][0])
.to.have.string(baseConfig.symbols.OK);
});
it("should log the require() call as OK to console", function () {

@@ -127,5 +133,5 @@ expect(stubs.info.withArgs(sinon.match("main.js")).args[0][0])

expect(stubs.info.withArgs(sinon.match("as AMD modules:")).args[0][0])
.to.have.string("as AMD modules: 3");
.to.have.string("as AMD modules: 4");
expect(stubs.info.withArgs(sinon.match("define() calls:")).args[0][0])
.to.have.string("define() calls: 2");
.to.have.string("define() calls: 3");
expect(stubs.info.withArgs(sinon.match("require() calls:")).args[0][0])

@@ -147,3 +153,3 @@ .to.have.string("require() calls: 1");

expect(stubs.info.withArgs(sinon.match("% converted")).args[0][0])
.to.have.string("60% converted");
.to.have.string("67% converted");
});

@@ -186,5 +192,5 @@ });

sinon.stub(detector, "printFileSummary", function () {
sinon.stub(detector, "printFileSummary").callsFake(function () {
originalPrintFileSummary();
done();
originalPrintFileSummary();
});

@@ -206,1 +212,139 @@

});
describe("func test - save", function () {
const saveLocation = 'file.to.save.json';
function createDetector(save = false) {
const argv = {
globals: true,
utf8: false,
};
if (save) {
argv.save = save;
}
const detector = new ConversionDetector(searchDir, baseConfig, argv);
sinon.stub(detector, "_saveToFile");
detector.run();
return detector;
}
it("should call _saveToFile with proper arguments if save was passed", function () {
const detector = createDetector(saveLocation);
assert.isOk(detector._saveToFile.calledOnce);
const args = detector._saveToFile.getCall(0).args;
assert.deepEqual(JSON.parse(JSON.stringify(args[0])), {
"files": {
"./test/data": [
{
"filepath": "./test/data/amdModule.js",
"amd": true,
"globals": false,
"is": "o"
},
{
"filepath": "./test/data/amdModuleNoName.js",
"amd": true,
"globals": false,
"is": "o"
}
],
"./test/data/foo/bar": [
{
"filepath": "./test/data/foo/bar/amdModuleGlobalsAbuse.js",
"amd": true,
"is": "!",
"globals": true,
"globalsList": [
{
"varName": "Bar.baz",
"lineInfo": {
"line": 7,
"column": 20
},
"isExcluded": false,
"fullFilePath": "./test/data/foo/bar/amdModuleGlobalsAbuse.js"
},
{
"varName": "Foo.bar",
"lineInfo": {
"line": 2,
"column": 4
},
"isExcluded": false,
"fullFilePath": "./test/data/foo/bar/amdModuleGlobalsAbuse.js"
}
],
"msg": "Globals detected"
}
],
"./test/data/foo": [
{
"filepath": "./test/data/foo/nonAmdModule.js",
"amd": false,
"is": "x",
"msg": "Not an AMD module"
}
],
"./test/data/main": [
{
"filepath": "./test/data/main/amdUsageInIIFE.js",
"amd": false,
"is": "x",
"msg": "Not an AMD module"
},
{
"filepath": "./test/data/main/main.js",
"amd": true,
"globals": false,
"is": "o"
}
]
},
"globals": [
{
"varName": "Bar.baz",
"lineInfo": {
"line": 7,
"column": 20
},
"isExcluded": false,
"fullFilePath": "./test/data/foo/bar/amdModuleGlobalsAbuse.js"
},
{
"varName": "Foo.bar",
"lineInfo": {
"line": 2,
"column": 4
},
"isExcluded": false,
"fullFilePath": "./test/data/foo/bar/amdModuleGlobalsAbuse.js"
}
],
"stats": {
"percentageOfCovered": 66.66666666666666,
"countTotalModules": 4,
"countNonAMD": 2,
"countGlobals": 2,
"countAMDDefine": 3,
"countAMDRequire": 1
}
});
assert.strictEqual(args[1], saveLocation);
});
it("should call _saveToFile with proper arguments if save was not passed", function () {
const detector = createDetector();
assert.isNotOk(detector._saveToFile.called);
});
});

@@ -0,1 +1,2 @@

'use strict';
var chai = require('chai');

@@ -2,0 +3,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc