@oracle/oraclejet-audit 12.1.0 → 13.0.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/jaf-amd.js +2 -20
- package/jaf.js +1 -1
- package/jafapi.js +1 -1
- package/lib/AstJson.js +1 -1
- package/lib/AstMd.js +1 -1
- package/lib/Cli.js +6 -0
- package/lib/Color.js +6 -0
- package/lib/Comments.js +1 -1
- package/lib/ComponentSvcs.js +1 -1
- package/lib/Components.js +1 -1
- package/lib/Config.js +1 -1
- package/lib/ConfigLib.js +1 -1
- package/lib/CssUtils.js +1 -1
- package/lib/FileSet.js +1 -1
- package/lib/FsUtils.js +1 -1
- package/lib/Issue.js +1 -1
- package/lib/JafEvents.js +1 -1
- package/lib/JafLib.js +1 -1
- package/lib/Json.js +1 -1
- package/lib/JsonLoader.js +1 -1
- package/lib/Md.js +1 -1
- package/lib/MetaLib.js +1 -1
- package/lib/OjCPack.js +6 -0
- package/lib/OjetLib.js +6 -0
- package/lib/Registry.js +1 -1
- package/lib/RuleSet.js +1 -1
- package/lib/Rules.js +1 -1
- package/lib/Scope.js +1 -1
- package/lib/Utils.js +1 -1
- package/lib/ZipUtils.js +1 -1
- package/lib/amdlist.js +6 -0
- package/lib/api.js +1 -1
- package/lib/betalist.js +6 -0
- package/lib/builtinpacks.js +1 -1
- package/lib/checkage.js +6 -0
- package/lib/cliStats.js +1 -1
- package/lib/cmdline.js +1 -1
- package/lib/defaults.js +1 -1
- package/lib/deflist.js +1 -1
- package/lib/dislist.js +1 -1
- package/lib/exportRules.js +1 -1
- package/lib/extends.js +1 -1
- package/lib/grouplist.js +1 -1
- package/lib/groups.js +1 -1
- package/lib/help.js +1 -1
- package/lib/jetver.js +1 -1
- package/lib/manpage.js +6 -0
- package/lib/manual.js +1 -1
- package/lib/metaLoader.js +1 -1
- package/lib/metahist.js +1 -1
- package/lib/msgidLoader.js +1 -1
- package/lib/ns.js +1 -1
- package/lib/outfile.js +1 -1
- package/lib/proflist.js +6 -0
- package/lib/rlolist.js +6 -0
- package/lib/scaffold.js +1 -1
- package/lib/scaffoldRule.js +1 -1
- package/lib/schema.js +1 -1
- package/meta/13.0.0/jetauditmeta.js +9 -0
- package/meta/metaverlist.json +1 -1
- package/package.json +6 -4
- package/profiles/best-practice.json +146 -0
- package/profiles/redwood-strict.json +31 -0
- package/rulepacks/jetwc/jetwc-bootstrap.js +1 -1
- package/rulepacks/jetwc/jetwc-css-oj-complete.js +1 -1
- package/rulepacks/jetwc/jetwc-pack-children.js +1 -1
- package/rulepacks/jetwc/jetwc-schema.js +1 -1
- package/rulepacks/jetwc/jetwc-supproperty-propagation.js +6 -0
- package/rulepacks/jetwc/msgid.json +1 -1
- package/rulepacks/jetwc/rules.json +1 -1
- package/rulepacks/jetwc-lib/jetwcutils-componentFinder.js +1 -1
- package/rulepacks/jetwco/jetwco-bootstrap.js +1 -1
- package/rulepacks/jetwco/jetwco-component-api-controlled-changes.js +1 -1
- package/rulepacks/jetwco/rules.json +1 -1
- package/rules/jaf/jaf-sys-age.js +6 -0
- package/rules/jaf/msgid.json +1 -1
- package/rules/jaf/rules.json +1 -1
- package/rules/jet/helpers/extractStylesFromClass.js +1 -1
- package/rules/jet/msgid.json +1 -1
- package/rules/jet/oj-acc-aria-ojselector-labelledby.js +6 -0
- package/rules/jet/oj-acc-aria-prop.js +1 -1
- package/rules/jet/oj-c-acc-avatar-aria-role.js +6 -0
- package/rules/jet/oj-cca-compjson-bp-jetver.js +1 -1
- package/rules/jet/oj-css-var-override.js +1 -1
- package/rules/jet/oj-html-alta-deprecated.js +1 -1
- package/rules/jet/oj-html-attr-2def.js +1 -1
- package/rules/jet/oj-html-attr-req.js +1 -1
- package/rules/jet/oj-html-cca-tagname.js +1 -1
- package/rules/jet/oj-html-cdn.js +1 -1
- package/rules/jet/oj-html-combo-converter.js +1 -1
- package/rules/jet/oj-html-file-pick-accept.js +1 -1
- package/rules/jet/oj-html-notag-style.js +1 -1
- package/rules/jet/oj-html-ojattr-deprecated.js +1 -1
- package/rules/jet/oj-html-ojattr-enum-deprecated.js +1 -1
- package/rules/jet/oj-html-ojattr-evt-syntax.js +1 -1
- package/rules/jet/oj-html-ojattr-value.js +1 -1
- package/rules/jet/oj-html-ojattr.js +1 -1
- package/rules/jet/oj-html-ojtag-deprecated.js +1 -1
- package/rules/jet/oj-html-pageopts-type.js +6 -0
- package/rules/jet/oj-html-rating-gauge-size.js +6 -0
- package/rules/jet/oj-html-redwood-bp-endslot.js +6 -0
- package/rules/jet/oj-html-slot-deprecated.js +6 -0
- package/rules/jet/oj-html-slot-pref-content.js +1 -1
- package/rules/jet/oj-html-wctag-maintenance.js +6 -0
- package/rules/jet/rules.json +1 -1
- package/schema/component-schema.json +1 -1482
- package/src/JafCore.js +1 -1
- package/types/index.d.ts +26 -8
- package/lib/colors.js +0 -6
package/lib/Rules.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const RuleContext=require("./RuleContext");const REG=require("../lib/RegTypes");const PROP_FILETYPE="filetype";const FILETYPE_CSS="css";var _builtinJetRules=null;var Rules=function(ruleSets,nodeDeps,config,fnMsgId,appCtx){this._appCtx=appCtx;this._msg=appCtx.msg;this._info=appCtx.info;this._debug=appCtx.debug;this._error=appCtx.error;this._assert=appCtx.assert;this._metaLib=appCtx.metaLib;this._reporter=appCtx.reporter;this._Issue=appCtx.Issue;this._semVer=ruleSets.getSemVer();this._utils=appCtx.utils;this._sevLib=appCtx.severity.getSevLib();this._registry=ruleSets.getRegistry();this._ruleCount=ruleSets.getActiveRuleCount();this._rulesetSummary=ruleSets.getRulesetSummary();this._rulePacks=ruleSets.getRulePacks();this._common=this._createCommon();this._shadowRulePacks=ruleSets.getShadowRulePacks();this._ruleSets=ruleSets;this._Stats=appCtx.Stats;this._isUnitTest=appCtx.isUnitTest;if(this._isUnitTest||config.rulesFired){this._Stats.packRulesFired=[];for(let i=0;i<ruleSets._ruleSets.length;i++)this._Stats.packRulesFired.push({pack:ruleSets._ruleSets[i].prefix,rules:{}})}this._useBuiltinJetRules=true;this._config=config;this._nodeDeps=nodeDeps;this._isNode=!!nodeDeps.fs;this._curFile=null;this._getMsgId=fnMsgId;this._sysOpts={verboseMode:appCtx.verboseMode,debugMode:appCtx.debugMode};this._message={msg:this._msg,info:this._info,debug:this._debug,error:this._error,assert:this._assert}};Rules.prototype.fireRules=function(ruleCtx,arg1,filepath,filetype,arg2,isEmbeddedCss){var ruleName,callbacks,typeObj;if(this._curFile!==filepath){this._curFile=filepath;this._fileType=filetype}typeObj=this._registry.getRegisteredCallbacks(ruleCtx.type);if(typeObj){for(ruleName in typeObj){if(this._isRuleDisabledByComment&&this._isRuleDisabledByComment(ruleName)){continue}callbacks=typeObj[ruleName];this._fireRulePreTest(ruleCtx,ruleName,arg1,filepath,arg2,isEmbeddedCss,callbacks)}}};Rules.prototype.setJafLib=function(jl){this._jafLib=jl};Rules.prototype._fireRulePreTest=function(ruleCtx,ruleName,arg1,filepath,arg2,isEmbeddedCss,callbacks){var opts,callback,fileType,i;if(!callbacks){return}for(i=0;i<callbacks.length;i++){callback=callbacks[i];opts=this._getRuleOptionsByName(ruleName,callback.rsi);if(!opts.enabled){return}fileType=opts[PROP_FILETYPE];if(fileType){if(isEmbeddedCss&&!this._isFileTypeOk(fileType,FILETYPE_CSS)){return}if(!this._isFileTypeOk(fileType,this._fileType)){return}}ruleCtx._rsi=callback.rsi;ruleCtx.getMsgId=this._getMsgId;this._fireRule(ruleCtx,ruleName,arg1,arg2,filepath,fileType,callback.cb)}};Rules.prototype._fireRule=function(ruleCtx,ruleName,name,value,filepath,filetype,callback){var rule,msg,ctxType,oFired;ctxType=ruleCtx.type;this._debug("Firing rule "+ruleName+" type="+ctxType+" name="+name+" value="+value);rule=this._getRuleByName(ruleName,ruleCtx._rsi);if(!rule){return}ruleCtx.Issue=this._Issue;ruleCtx.reporter=this._reporter;ruleCtx.filepath=filepath;ruleCtx.filename=filepath;ruleCtx.filetype=filetype;ruleCtx.utils=ruleCtx.utils?ruleCtx.utils:{};ruleCtx.msgLib=this._message;ruleCtx.message=this._message;ruleCtx.ruleName=ruleName;ruleCtx.rulePack=this._rulePacks[ruleCtx._rsi].rulePack;ruleCtx.sysOpts=this._sysOpts;ruleCtx.common=this._common[ruleCtx._rsi];ruleCtx.userDefs=this._config.userDefs;ruleCtx.utils.utils=this._utils;ruleCtx.utils.fsUtils=this._nodeDeps.fsUtils;ruleCtx.utils.metaLib=this._metaLib;ruleCtx.utils.msgLib=this._message;ruleCtx.utils.sevLib=this._sevLib;ruleCtx.utils.semVerUtils=this._semVer;ruleCtx.utils.jafLib=this._jafLib.getJafLib();this._curCtx=ruleCtx;try{if(callback){ruleCtx.rulePack._setCBCtx(ruleCtx);if((ctxType==="attr"||ctxType==="attrexpr"||ctxType.indexOf("|")>0||ctxType==="class"||ctxType==="style"||ctxType.startsWith("<")&&ctxType.includes("="))&&typeof value!=="string"){if(ctxType==="style"){callback(ruleCtx,name,_extractStyles(value.val),value.rawval)}else{callback(ruleCtx,name,value.val,value.rawval)}}else if(ctxType.startsWith("compjson")||ctxType==="comment"){callback(ruleCtx,value)}else{callback(ruleCtx,name,value)}this._Stats.rulesFired++;if(this._isUnitTest||this._config.rulesFired){if(oFired=this._Stats.packRulesFired[ruleCtx._rsi]){oFired=oFired.rules;if(oFired[ruleName]){oFired[ruleName]++}else{oFired[ruleName]=1}}}}else{rule.run(ruleCtx,name,value)}}catch(e){msg=!e||!e.message?"Unknown error (rule "+this._getFileSuffix(ruleCtx.filepath)+" syntax issue?)":e.message;this._error("** running rule "+ruleName+" ["+msg+"]"+"\n - "+ruleCtx.filepath);this._error(e.stack)}};Rules.prototype.makeRuleContext=function(){return new RuleContext};Rules.prototype.isTypeRegistered=function(regType){return this._registry.isRegisteredCallback(regType)};Rules.prototype.isTypeRegisteredAsElemName=function(elem){return this._registry.isRegisteredCallbackRE(elem)};Rules.prototype.setJSCommentCallback=function(fnCB){this._isRuleDisabledByComment=fnCB};Rules.prototype.filterHtmlCallbacks=function(htmlCB){return htmlCB};Rules.prototype.getRulesProse=function(isInternal){var rulePacks,rulePack,rules,rule,ruleName,rsi,opts,haveRules;this._nodeDeps.exportRules.setupRulesToProse(this._config.severity,this._utils);rulePacks=this._rulePacks;for(rsi=0;rsi<rulePacks.length;rsi++){rulePack=rulePacks[rsi];rules=rulePack.rulesJson;this._nodeDeps.exportRules.packToProse(rules,rulePack.path,rsi);haveRules=false;rules=rules.rules;for(ruleName in rules){if(!rules[ruleName].enabled){continue}opts=this._utils.extend(rules[ruleName],isInternal);rule=this._shadowRulePacks[rsi][ruleName];this._nodeDeps.exportRules.ruleToProse(ruleName,rule,opts);haveRules=true}if(!haveRules){this._nodeDeps.exportRules.packToProse()}}return this._nodeDeps.exportRules.getProse()};Rules.prototype.getRulesJson=function(obj){var rulePacks,rulePack,rulesJson,ruleName,rule,ruleOpts,opts,rsi;rulePacks=this._rulePacks;this._nodeDeps.exportRules.setupRulesToJson(obj,this._config.severity,this._utils);for(rsi=0;rsi<rulePacks.length;rsi++){rulePack=rulePacks[rsi];this._nodeDeps.exportRules.packToJson(rulePack);rulesJson=rulePack.rulesJson;for(ruleName in rulesJson.rules){ruleOpts=rulesJson.rules[ruleName];if(!ruleOpts.enabled){continue}opts=this._utils.extend(ruleOpts);rule=this._shadowRulePacks[rsi][ruleName];this._nodeDeps.exportRules.ruleToJson(ruleName,rule,opts)}}return this._nodeDeps.exportRules.getJson()};Rules.prototype.getRulesSonar=function(){var rulePacks,rulePack,ruleName,rules,rule,opts,rsi;this._nodeDeps.exportRules.setupRulesToXml(this._utils);rulePacks=this._rulePacks;for(rsi=0;rsi<rulePacks.length;rsi++){rulePack=rulePacks[rsi];rules=rulePack.rulesJson.rules;for(ruleName in rules){if(!rules[ruleName].enabled){continue}rule=this._shadowRulePacks[rsi][ruleName];opts=rules[ruleName];this._nodeDeps.exportRules.ruleToXml(ruleName,rule,opts)}}return this._nodeDeps.exportRules.getXml()};Rules.prototype.getRuleOptions=function(ruleName,rsi){return this._getRuleOptionsByName(ruleName,rsi)};Rules.prototype.getActiveRuleCount=function(){return this._ruleCount};Rules.prototype.getRuleSetSummaryByIndex=function(rsi){return this._rulesetSummary[rsi]};Rules.prototype.getRulePack=function(rsi){return this._rulePacks[rsi].rulePack};Rules.prototype.getRSIByPrefix=function(prefix){var i,rsi=-1;;for(i=0;i<this._rulesetSummary.length;i++){if(this._rulesetSummary[i].prefix===prefix){rsi=i;break}}return rsi};Rules.prototype.isRuleEnabled=function(ruleName,rsi){if(rsi===undefined){rsi=this.getRSIByRuleName(ruleName);if(rsi<0){return false}}var opts=this._getRuleOptionsByName(ruleName,rsi);return!!(opts&&opts.enabled)};Rules.prototype.getRSIByRuleName=function(ruleName){var rsi,rp,len;len=this._shadowRulePacks.length;for(rsi=0;rsi<len;rsi++){rp=this._shadowRulePacks[rsi];if(rp[ruleName]){break}}return rsi<len?rsi:-1};Rules.prototype.getRuleDescription=function(prefix,ruleName,isShort){var rule,rsi,ret="";rsi=this.getRSIByPrefix(prefix);if(rsi>=0){rule=this._shadowRulePacks[rsi][ruleName];if(rule){ret=isShort?rule.getShortDescription():rule.getDescription()}}return ret};Rules.prototype.getRuleDescriptionEx=function(msgId,ruleName,isShort){var descrip,rule,prefix,msgNum,rsi,msgTab,msgIds,mid,sev,x;var idList=[];if(ruleName){var rp=this._shadowRulePacks;for(rsi=0;rsi<rp.length;rsi++){rule=rp[rsi][ruleName];if(rule){descrip=isShort?rule.getShortDescription():rule.getDescription();if(descrip){msgTab=this._ruleSets.loadMsgIds();if(prefix=this._rulesetSummary[rsi]){prefix=prefix.prefix;if(msgIds=msgTab[prefix]){for(mid in msgIds){if(mid.startsWith(ruleName)){idList.push(msgIds[mid])}}}}break}}}}if(msgId){rsi=this._ruleSets.getRsiFromMsgId(msgId);if(rsi>=0){x=msgId.indexOf("-");prefix=msgId.substring(0,x);msgNum=msgId.substring(x+1);msgTab=this._ruleSets.loadMsgIds();msgIds=msgTab[prefix];if(msgNum.length<4){msgNum="0".repeat(4-msgNum.length)+msgNum}for(mid in msgIds){if(msgIds[mid]===msgNum){x=mid.lastIndexOf("_");ruleName=x>0?mid.substring(0,x):mid;if(descrip=this.getRuleDescription(prefix,ruleName,isShort)){for(mid in msgIds){if(mid.startsWith(ruleName)){idList.push(msgIds[mid])}}break}}}}}if(ruleName){sev=this._getRuleOptionsByName(ruleName,rsi);sev=sev?sev.severity:""}return{descrip:descrip,rule:ruleName,prefix:prefix,sev:sev,idList:idList}};Rules.prototype._showIgnoredRule=function(msg,isError){if(msg){if(!this._ignoredRulesShown){this._info("\n--------- Start-up Rule analysis ---------");this._ignoredRulesShown=true}isError?this._error(msg):this._info(msg)}else if(this._ignoredRulesShown){this._info("------------ End Rule analysis -------------")}};Rules.prototype.fireHookRules=function(ruleCtx,rsi){var ruleName,typeObj,callbacks,callback,opts,rc,i;var _rsi;ruleCtx.Issue=this._Issue;ruleCtx.reporter=this._reporter;ruleCtx.metaLib=this._metaLib;ruleCtx.msgLib=this._message;ruleCtx.message=this._message;_rsi=rsi;typeObj=this._registry.getRegisteredCallbacks(ruleCtx.type);if(!typeObj){return}for(ruleName in typeObj){callbacks=typeObj[ruleName];if(!callbacks){continue}for(i=0;i<callbacks.length;i++){callback=callbacks[i];if(rsi===undefined){_rsi=callback.rsi}else{if(rsi!==callback.rsi){continue}_rsi=rsi}opts=this._getRuleOptionsByName(ruleName,_rsi);if(ruleCtx.type==="file"||ruleCtx.type==="startscript"){if(opts&&opts.filetype){if(!this._isFileTypeOk(opts.filetype,ruleCtx.filetype)){continue}}}ruleCtx.ruleName=ruleName;ruleCtx.rulePack=this._rulePacks[_rsi].rulePack;ruleCtx._rsi=_rsi;ruleCtx.common=this._common[_rsi];ruleCtx.userDefs=this._config.userDefs;ruleCtx.utils.metaLib=this._metaLib;ruleCtx.utils.utils=this._utils;ruleCtx.utils.fsUtils=this._nodeDeps.fsUtils;ruleCtx.utils.msgLib=this._message;ruleCtx.utils.semVerUtils=this._semVer;ruleCtx.sysOpts=this._sysOpts;ruleCtx.getMsgId=this._getMsgId;this._debug("Firing hook rule "+ruleName+" type="+ruleCtx.type);ruleCtx.rulePack._setCBCtx(ruleCtx);rc=callback.cb(ruleCtx);this._Stats.hooksFired++;if((ruleCtx.phase===REG.PHASE_STARTUP||ruleCtx.phase===REG.PHASE_START_AUDIT||ruleCtx.phase===REG.PHASE_FILE)&&typeof rc==="boolean"&&!rc){this._info("Hook rule ('"+ruleCtx.type+"') veto! by '"+ruleName+"'");return rc}}}return true};Rules.prototype._getRuleByName=function(ruleName,rsi){var rs=this._shadowRulePacks[rsi];return rs[ruleName]};Rules.prototype._getRuleOptionsByName=function(ruleName,rsi){var rulePack=this._rulePacks[rsi];return rulePack.rulesJson.rules[ruleName]};Rules.prototype._isGroupActive=function(group){var groups,defs,def,i;groups=this._config.groups;defs=this._config.defGroups;if(this._checkGroups(groups,group)){return true}if(!defs){return false}for(i=0;i<groups.length;i++){def=groups[i];if(this._checkDefGroup(defs,def,group)){return true}}return false};Rules.prototype._loadBuiltinJetRulesDescriptions=function(){var ruleName,rules;try{if(!_builtinJetRules){_builtinJetRules=require("../rules/jet/rules.json")}}catch(e){this._error("Unable to load builtin rule definition file "+e)}if(_builtinJetRules&&_builtinJetRules.rules){rules=_builtinJetRules.rules;for(ruleName in rules){rules[ruleName].$builtin=true}}return _builtinJetRules};Rules.prototype._isFileTypeOk=function(ruleFileType,fileType){var ret=false;if(Array.isArray(ruleFileType)){ret=ruleFileType.indexOf(fileType)>=0}else{ret=ruleFileType===fileType}return ret};Rules.prototype._createCommon=function(){var i,a=[];for(i=0;i<this._rulesetSummary.length;i++){a.push({})}return a};Rules.prototype._getFileSuffix=function(fp){var s="";if(fp){s=this._nodeDeps.path.extname(fp)}return s.length?s:"?"};function _extractStyles(s){var a,isExpr,i,sc=";";s=s.trim();isExpr=_isExpr(s);s=s.replace(/[\'\"\[\]\{\}]/g,"").trim();if(!s.includes(";")){if(isExpr){if(s.includes(",")){sc=","}}}a=s.split(sc);for(i=0;i<a.length;i++){a[i]=a[i].trim();if(!a[i].length){a.splice(i,1);i--}}return a};function _isExpr(s){s=s.trim();return s.startsWith("[[")||s.startsWith("{{")};module.exports=Rules;
|
|
6
|
+
const RuleContext=require("./RuleContext");const REG=require("../lib/RegTypes");const PROP_FILETYPE="filetype";const FILETYPE_CSS="css";var Rules=function(ruleSets,nodeDeps,config,fnMsgId,appCtx){this._appCtx=appCtx;this._msg=appCtx.msg;this._info=appCtx.info;this._debug=appCtx.debug;this._error=appCtx.error;this._assert=appCtx.assert;this._metaLib=appCtx.metaLib;this._reporter=appCtx.reporter;this._Issue=appCtx.Issue;this._semVer=ruleSets.getSemVer();this._utils=appCtx.utils;this._fsUtils=appCtx.fsUtils;this._sevLib=appCtx.severity.getSevLib();this._ojetLib=appCtx.ojetLib;this._registry=ruleSets.getRegistry();this._ruleCount=ruleSets.getActiveRuleCount();this._rulesetSummary=ruleSets.getRulesetSummary();this._rulePacks=ruleSets.getRulePacks();this._common=this._createCommon();this._shadowRulePacks=ruleSets.getShadowRulePacks();this._ruleSets=ruleSets;this._Stats=appCtx.Stats;this._isUnitTest=appCtx.isUnitTest;if(this._isUnitTest||config.rulesFired){this._Stats.packRulesFired=[];for(let i=0;i<ruleSets._ruleSets.length;i++)this._Stats.packRulesFired.push({pack:ruleSets._ruleSets[i].prefix,rules:{}})}this._builtinJetRules=null;this._useBuiltinJetRules=true;this._config=config;this._nd=nodeDeps;this._isNode=!!nodeDeps.fs;this._curFile=null;this._getMsgId=fnMsgId;this._sysOpts={verboseMode:appCtx.verboseMode,debugMode:appCtx.debugMode};this._message={msg:this._msg,info:this._info,debug:this._debug,error:this._error,assert:this._assert}};Rules.prototype.fireRules=function(ruleCtx,arg1,filepath,filetype,arg2,isEmbeddedCss){var ruleName,callbacks,typeObj;if(this._curFile!==filepath){this._curFile=filepath;this._fileType=filetype}typeObj=this._registry.getRegisteredCallbacks(ruleCtx.type);if(typeObj){for(ruleName in typeObj){if(this._isRuleDisabledByComment&&this._isRuleDisabledByComment(ruleName)){continue}callbacks=typeObj[ruleName];this._fireRulePreTest(ruleCtx,ruleName,arg1,filepath,arg2,isEmbeddedCss,callbacks)}}};Rules.prototype.setJafLib=function(jl){this._jafLib=jl};Rules.prototype._fireRulePreTest=function(ruleCtx,ruleName,arg1,filepath,arg2,isEmbeddedCss,callbacks){var opts,callback,fileType,i;if(!callbacks){return}for(i=0;i<callbacks.length;i++){callback=callbacks[i];opts=this._getRuleOptionsByName(ruleName,callback.rsi);if(!opts.enabled){return}fileType=opts[PROP_FILETYPE];if(fileType){if(isEmbeddedCss&&!this._isFileTypeOk(fileType,FILETYPE_CSS)){return}if(!this._isFileTypeOk(fileType,this._fileType)){return}}ruleCtx._rsi=callback.rsi;ruleCtx.getMsgId=this._getMsgId;this._fireRule(ruleCtx,ruleName,arg1,arg2,filepath,fileType,callback.cb)}};Rules.prototype._fireRule=function(ruleCtx,ruleName,name,value,filepath,filetype,callback){var rule,msg,ctxType,oFired;ctxType=ruleCtx.type;this._debug("Firing rule "+ruleName+" type="+ctxType+" name="+name+" value="+value);rule=this._getRuleByName(ruleName,ruleCtx._rsi);if(!rule){return}ruleCtx.Issue=this._Issue;ruleCtx.reporter=this._reporter;ruleCtx.filepath=filepath;ruleCtx.filetype=filetype;ruleCtx.utils=ruleCtx.utils?ruleCtx.utils:{};ruleCtx.ruleName=ruleName;ruleCtx.rulePack=this._rulePacks[ruleCtx._rsi].rulePack;ruleCtx.sysOpts=this._sysOpts;ruleCtx.common=this._common[ruleCtx._rsi];ruleCtx.userDefs=this._config.userDefs;ruleCtx.utils.utils=this._utils;ruleCtx.utils.fsUtils=this._fsUtils;ruleCtx.utils.metaLib=this._metaLib;ruleCtx.utils.msgLib=this._message;ruleCtx.utils.sevLib=this._sevLib;ruleCtx.utils.semVerUtils=this._semVer;ruleCtx.utils.jafLib=this._jafLib.getJafLib();ruleCtx.utils.OjetLib=this._ojetLib;this._curCtx=ruleCtx;try{if(callback){ruleCtx.rulePack._setCBCtx(ruleCtx);if((ctxType==="attr"||ctxType==="attrexpr"||ctxType.indexOf("|")>0||ctxType==="class"||ctxType==="style"||ctxType.startsWith("<")&&ctxType.includes("="))&&typeof value!=="string"){if(ctxType==="style"){callback(ruleCtx,name,_extractStyles(value.val),value.rawval)}else{callback(ruleCtx,name,value.val,value.rawval)}}else if(ctxType.startsWith("compjson")||ctxType==="comment"){callback(ruleCtx,value)}else if(ruleCtx.type==="json"){callback(ruleCtx,value.ast)}else{callback(ruleCtx,name,value)}this._Stats.rulesFired++;if(this._isUnitTest||this._config.rulesFired){if(oFired=this._Stats.packRulesFired[ruleCtx._rsi]){oFired=oFired.rules;if(oFired[ruleName]){oFired[ruleName]++}else{oFired[ruleName]=1}}}}else{rule.run(ruleCtx,name,value)}}catch(e){msg=!e||!e.message?"Unknown error (rule "+this._getFileSuffix(ruleCtx.filepath)+" syntax issue?)":e.message;this._error("** running rule "+ruleName+" ["+msg+"]"+"\n - "+ruleCtx.filepath);this._error(e.stack)}};Rules.prototype.makeRuleContext=function(){return new RuleContext};Rules.prototype.isTypeRegistered=function(regType){return this._registry.isRegisteredCallback(regType)};Rules.prototype.isTypeRegisteredAsElemName=function(elem){return this._registry.isRegisteredCallbackRE(elem)};Rules.prototype.setJSCommentCallback=function(fnCB){this._isRuleDisabledByComment=fnCB};Rules.prototype.filterHtmlCallbacks=function(htmlCB){return htmlCB};Rules.prototype.getRulesProse=function(isInternal){var rulePacks,rulePack,rules,rule,ruleName,names,rsi,opts,haveRules,prefix,msgIds,ids;this._nd.exportRules.setupRulesToProse(this._nd,this._config.severity,this._appCtx);msgIds=this._ruleSets.getMsgIds();rulePacks=this._rulePacks;for(rsi=0;rsi<rulePacks.length;rsi++){rulePack=rulePacks[rsi];rules=rulePack.rulesJson;prefix=rules.prefix;this._nd.exportRules.packToProse(rules,rulePack.path,rsi);haveRules=false;rules=rules.rules;names=_getSortedRuleNames(rules);for(ruleName of names){opts=rules[ruleName];if(!opts.enabled||opts.hasOwnProperty("inservice")&&!opts.inservice){continue}opts=this._utils.extend(opts,isInternal);rule=this._shadowRulePacks[rsi][ruleName];ids=this._getMsgIdsForRule(ruleName,msgIds[prefix],prefix);this._nd.exportRules.ruleToProse(ruleName,rule,opts,ids);haveRules=true}if(!haveRules){this._nd.exportRules.packToProse()}}return this._nd.exportRules.getProse()};Rules.prototype.getRulesJson=function(active,obj){var rulePacks,rulePack,rulesJson,ruleName,rule,ruleOpts,opts,pack,rsi,prefix,msgIds,ids;msgIds=this._ruleSets.getMsgIds();rulePacks=this._rulePacks;this._nd.exportRules.setupRulesToJson(obj,this._config.severity,this._appCtx);for(rsi=0;rsi<rulePacks.length;rsi++){rulePack=rulePacks[rsi];this._nd.exportRules.packToJson(rulePack);rulesJson=rulePack.rulesJson;prefix=rulesJson.prefix;for(ruleName in rulesJson.rules){ruleOpts=rulesJson.rules[ruleName];if(ruleOpts.hasOwnProperty("inservice")&&!ruleOpts.inservice){continue}if(active&&!ruleOpts.enabled){continue}opts=this._utils.extend(ruleOpts);ids=this._getMsgIdsForRule(ruleName,msgIds[prefix],prefix);if(pack=this._shadowRulePacks[rsi]){rule=pack[ruleName]}else{rule=null}if(!active||rule){this._nd.exportRules.ruleToJson(ruleName,rule,opts,ids,active)}}}return this._nd.exportRules.getJson()};Rules.prototype.getRulesSonar=function(){var rulePacks,rulePack,ruleName,rules,rule,opts,prefix,msgIds,ids,rsi;this._nd.exportRules.setupRulesToXml(this._appCtx);msgIds=this._ruleSets.getMsgIds();rulePacks=this._rulePacks;for(rsi=0;rsi<rulePacks.length;rsi++){rulePack=rulePacks[rsi];rules=rulePack.rulesJson.rules;prefix=rulePack.rulesJson.prefix;for(ruleName in rules){opts=rules[ruleName];if(!opts.enabled||opts.hasOwnProperty("inservice")&&!opts.inservice){continue}opts=this._utils.extend(opts);rule=this._shadowRulePacks[rsi][ruleName];ids=this._getMsgIdsForRule(ruleName,msgIds[prefix],prefix);this._nd.exportRules.ruleToXml(ruleName,rule,opts,ids)}}return this._nd.exportRules.getXml()};Rules.prototype.getRuleOptions=function(ruleName,rsi){return this._getRuleOptionsByName(ruleName,rsi)};Rules.prototype.getActiveRuleCount=function(){return this._ruleCount};Rules.prototype.getRuleSetSummaryByIndex=function(rsi){return this._rulesetSummary[rsi]};Rules.prototype.getRulePack=function(rsi){return this._rulePacks[rsi].rulePack};Rules.prototype.getRSIByPrefix=function(prefix){var i,rsi=-1;;for(i=0;i<this._rulesetSummary.length;i++){if(this._rulesetSummary[i].prefix===prefix){rsi=i;break}}return rsi};Rules.prototype.isRuleEnabled=function(ruleName,rsi){if(rsi===undefined){rsi=this.getRSIByRuleName(ruleName);if(rsi<0){return false}}var opts=this._getRuleOptionsByName(ruleName,rsi);return!!(opts&&opts.enabled)};Rules.prototype.getRSIByRuleName=function(ruleName){var rsi,rp,len;len=this._shadowRulePacks.length;for(rsi=0;rsi<len;rsi++){rp=this._shadowRulePacks[rsi];if(rp[ruleName]){break}}return rsi<len?rsi:-1};Rules.prototype.getRuleDescription=function(prefix,ruleName,isShort){var rule,rsi,ret="";rsi=this.getRSIByPrefix(prefix);if(rsi>=0){rule=this._shadowRulePacks[rsi][ruleName];if(rule){ret=isShort?rule.getShortDescription():rule.getDescription()}}return ret};Rules.prototype.getRuleDescriptionEx=function(msgId,ruleName,isShort){var descrip,rule,prefix,msgNum,rsi,msgTab,msgIds,mid,sev,x;var idList=[];if(ruleName){var rp=this._shadowRulePacks;for(rsi=0;rsi<rp.length;rsi++){rule=rp[rsi][ruleName];if(rule){descrip=isShort?rule.getShortDescription():rule.getDescription();if(descrip){msgTab=this._ruleSets.loadMsgIds();if(prefix=this._rulesetSummary[rsi]){prefix=prefix.prefix;if(msgIds=msgTab[prefix]){for(mid in msgIds){if(mid.startsWith(ruleName)){idList.push(msgIds[mid])}}}}break}}}}if(msgId){rsi=this._ruleSets.getRsiFromMsgId(msgId);if(rsi>=0){x=msgId.indexOf("-");prefix=msgId.substring(0,x);msgNum=msgId.substring(x+1);msgTab=this._ruleSets.loadMsgIds();msgIds=msgTab[prefix];if(msgNum.length<4){msgNum="0".repeat(4-msgNum.length)+msgNum}for(mid in msgIds){if(msgIds[mid]===msgNum){x=mid.lastIndexOf("_");ruleName=x>0?mid.substring(0,x):mid;if(descrip=this.getRuleDescription(prefix,ruleName,isShort)){for(mid in msgIds){if(mid.startsWith(ruleName)){idList.push(msgIds[mid])}}break}}}}}if(ruleName){sev=this._getRuleOptionsByName(ruleName,rsi);sev=sev?sev.severity:""}return{descrip:descrip,rule:ruleName,prefix:prefix,sev:sev,idList:idList}};Rules.prototype._getMsgIdsForRule=function(rname,ids,prefix){var r,list=[];prefix=prefix?prefix+"-":"";for(r in ids){if(r.startsWith(rname)){list.push(prefix+ids[r])}}return list};Rules.prototype._showIgnoredRule=function(msg,isError){if(msg){if(!this._ignoredRulesShown){this._info("\n--------- Start-up Rule analysis ---------");this._ignoredRulesShown=true}isError?this._error(msg):this._info(msg)}else if(this._ignoredRulesShown){this._info("------------ End Rule analysis -------------")}};Rules.prototype.fireHookRules=function(ruleCtx,rsi){var ruleName,typeObj,callbacks,callback,opts,rc,i;var _rsi;ruleCtx.Issue=this._Issue;ruleCtx.reporter=this._reporter;_rsi=rsi;typeObj=this._registry.getRegisteredCallbacks(ruleCtx.type);if(!typeObj){return}ruleCtx.userDefs=this._config.userDefs;ruleCtx.utils.metaLib=this._metaLib;ruleCtx.utils.utils=this._utils;ruleCtx.utils.fsUtils=this._fsUtils;ruleCtx.utils.msgLib=this._message;ruleCtx.utils.semVerUtils=this._semVer;ruleCtx.utils.OjetLib=this._ojetLib;ruleCtx.sysOpts=this._sysOpts;ruleCtx.getMsgId=this._getMsgId;for(ruleName in typeObj){callbacks=typeObj[ruleName];if(!callbacks){continue}for(i=0;i<callbacks.length;i++){callback=callbacks[i];if(rsi===undefined){_rsi=callback.rsi}else{if(rsi!==callback.rsi){continue}_rsi=rsi}opts=this._getRuleOptionsByName(ruleName,_rsi);if(ruleCtx.type==="file"||ruleCtx.type==="startscript"){if(opts&&opts.filetype){if(!this._isFileTypeOk(opts.filetype,ruleCtx.filetype)){continue}}}ruleCtx.ruleName=ruleName;ruleCtx.rulePack=this._rulePacks[_rsi].rulePack;ruleCtx._rsi=_rsi;ruleCtx.common=this._common[_rsi];this._debug("Firing hook rule "+ruleName+" type="+ruleCtx.type);ruleCtx.rulePack._setCBCtx(ruleCtx);rc=callback.cb(ruleCtx);this._Stats.hooksFired++;if((ruleCtx.phase===REG.PHASE_STARTUP||ruleCtx.phase===REG.PHASE_START_AUDIT||ruleCtx.phase===REG.PHASE_FILE)&&typeof rc==="boolean"&&!rc){this._info("Hook rule ('"+ruleCtx.type+"') veto! by '"+ruleName+"'");return rc}}}return true};Rules.prototype._getRuleByName=function(ruleName,rsi){var rs=this._shadowRulePacks[rsi];return rs[ruleName]};Rules.prototype._getRuleOptionsByName=function(ruleName,rsi){var rulePack=this._rulePacks[rsi];return rulePack.rulesJson.rules[ruleName]};Rules.prototype._isGroupActive=function(group){var groups,defs,def,i;groups=this._config.groups;defs=this._config.defGroups;if(this._checkGroups(groups,group)){return true}if(!defs){return false}for(i=0;i<groups.length;i++){def=groups[i];if(this._checkDefGroup(defs,def,group)){return true}}return false};Rules.prototype._loadBuiltinJetRulesDescriptions=function(){var ruleName,rules;try{if(!this._builtinJetRules){this._builtinJetRules=require("../rules/jet/rules.json")}}catch(e){this._error("Unable to load builtin rule definition file "+e)}if(this._builtinJetRules&&this._builtinJetRules.rules){rules=this._builtinJetRules.rules;for(ruleName in rules){rules[ruleName].$builtin=true}}return this._builtinJetRules};Rules.prototype._isFileTypeOk=function(ruleFileType,fileType){var ret=false;if(Array.isArray(ruleFileType)){ret=ruleFileType.indexOf(fileType)>=0}else{ret=ruleFileType===fileType}return ret};Rules.prototype._createCommon=function(){var i,a=[];for(i=0;i<this._rulesetSummary.length;i++){a.push({})}return a};Rules.prototype._getFileSuffix=function(fp){var s="";if(fp){s=this._nd.path.extname(fp)}return s.length?s:"?"};Rules.prototype.dumpRegistry=function(){return this._registry.dump()};function _extractStyles(s){var a,isExpr,i,sc=";";s=s.trim();isExpr=_isExpr(s);s=s.replace(/[\'\"\[\]\{\}]/g,"").trim();if(!s.includes(";")){if(isExpr){if(s.includes(",")){sc=","}}}a=s.split(sc);for(i=0;i<a.length;i++){a[i]=a[i].trim();if(!a[i].length){a.splice(i,1);i--}}return a};function _isExpr(s){s=s.trim();return s.startsWith("[[")||s.startsWith("{{")};function _getSortedRuleNames(rules){var rule,names=[];for(rule in rules){names.push(rule)}names.sort();return names};module.exports=Rules;
|
package/lib/Scope.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
var walker=require('./scopewalker');const TS_ANY='TSAnyKeyword';const TS_TYPEREF='TSTypeReference';const TS_ARRAY='TSArrayType';const STRING='string';const NUMBER='number';const BOOLEAN='boolean';const NULL='null';const OBJECT='Object';const FUNCTION='function';const ANY='any';const UNKNOWN='unknown';const PROGRAM='Program';const GLOBAL_SCOPE='_@global';const ANON='$anon';const DOCUMENT_METHODS={createElement:'Element',createTextNode:'Element',getElementById:'Element',getElementsByClassName:'HTMLCollection',getElementsByName:'HTMLCollection',getElementsByTagName:'HTMLCollection',getElementsByTagNameNS:'HTMLCollecion',hasFocus:'boolean',querySelector:'Element',querySelectorAll:'NodeList'};const DOCUMENT_MEMBERS={activeElement:'Element',anchors:'HTMLCollection',body:'Element',childElementCount:'number',dir:'string',documentElement:'Element',documentURI:'string',docType:'DTD',forms:'HTMLCollection',getElementById:'Element',head:'Element',hidden:'boolean',links:'HTMLCollection',scrollingElement:'Element',visibilityState:'string'};const INDENT=3;var _level=-INDENT;function _trace(t,n){function _rj(s,w){s=''+s;if(s.length<w){s=' '.repeat(w-s.length)+s}return s}_level+=t==='E'?INDENT:0;if(t==='E')console.log(`${_rj(n.loc.start.line,4)}] ${' '.repeat(_level)} ${n.type}`);else console.log(`${' '.repeat(4)} ${' '.repeat(_level)} ${n.type}`);_level-=t==='L'?INDENT:0};class Scope{constructor(msgCtx,config,file){this._msgCtx=msgCtx;this._config=config;this._file=file;this.reset()}reset(){this._fStack=[];this._bStack=[];this._imports=[];this._funcStack=[];this._idxStack=0;this._parents=[];this._blockStack=[];this._idxBlkStack=0;this._blkParents=[];this._nextAnonId=0;this._varKind;this._level=-INDENT}build(ast){this.reset();try{walker.traverse(ast,{enter:this._enter.bind(this),leave:this._leave.bind(this)})}catch(e){let stk=e.stack;let x=stk.indexOf('\n');stk=x>=0?stk.substring(x+1):stk;stk=`${'-'.repeat(10)}\n${stk}\n${'-'.repeat(10)}`;this._msgCtx.jafMsg('jaf-ts-walk',`TS walk exception: ${e.message} File: ${this._file}\n\n${stk}`)}return{funcs:this._fStack,blocks:this._bStack}}_buildFuncIndexesToBlocks(){var i,j;for(i=0;i<this._fStack.length;i++){for(j=0;j<this._bStack.length;j++){if(this._bStack[j].func==i){this._fStack[i].blocks.push(j)}}}}getAccessor(){return new _scope(this._fStack,this._bStack)}_enter(node){var type;if(this._msgCtx.isDebug){_trace('E',node)}type=node.type;if(this._isNewScope(node)){this._addNewFunc(node)}else if(type==='VariableDeclarator'||type==='ClassProperty'){this._varDecl(node)}else if(type==='VariableDeclaration'){this._varKind=node.kind}else if(type==='BlockStatement'){this._addNewBlock(node)}else if(type==='ClassDeclaration'){this._inClass=true;this._className=node.id.name}else if(type==='ImportDeclaration'){this._addImport(node)}}_leave(node){if(this._msgCtx.isDebug){_trace('L',node)}if(this._isNewScope(node)){if(this._parents.length){this._parents.pop()}this._funcStack.pop()}else if(node.type==='BlockStatement'){if(this._blkParents.length){this._blkParents.pop()}this._blockStack.pop()}else if(node.type==='ClassDeclaration'){this._inClass=false;this._className=null}}_addNewFunc(node){var type,func,curParent,x;type=node.type;if(type===PROGRAM){func=GLOBAL_SCOPE}else if(node.kind==='method'||node.kind==='constructor'){func=node.key.name}else if(node.id){func=node.id.name}else if(type==='ClassBody'){func=this._className}else{this._getNextAnon()}if(this._parents.length){curParent=this._fStack[this._parents[this._parents.length-1]]}x=this._fStack.push({func:func,node:node,vars:{},args:{},blocks:[],children:[],parent:this._parents.length?this._parents[this._parents.length-1]:-1});x--;this._parents.push(x);if(curParent){curParent.children.push(x)}this._funcStack.push(x);this._addFuncArgs(node)}_addNewBlock(node){var func,curParent,x;var func=this._fStack[this._getCurFunc()];let n=this._fStack[this._getCurFunc()].node;if((n.kind==='method'||n.kind==='constructor')&&this._isMethodRange(n,node)||n.kind!=='method'&&n.kind!=='constructor'&&node.range===n.body.range){return}if(this._blkParents.length){curParent=this._bStack[this._blkParents[this._blkParents.length-1]]}x=this._bStack.push({func:this._getCurFunc(),node:node,lets:{},children:[],parent:this._blkParents.length?this._blkParents[this._blkParents.length-1]:-1});x--;this._blkParents.push(x);if(curParent){curParent.children.push(x)}this._blockStack.push(x);func.blocks.push(x)}_addImport(node){var src,local,o;src=node.source.value;if(!src.startsWith('ojs/')){return}o={src:src};if(node.specifiers.length){node.specifiers.forEach(s=>{if(!local)local=[];local.push(s.local.name)});if(local){o.local=local}}this._imports.push(o)}_getCurFunc(){return this._funcStack[this._funcStack.length-1]}_getCurBlock(){return this._blockStack[this._blockStack.length-1]}_addFuncArgs(node){var vt,curScope;if(node.params){curScope=this._fStack[this._getCurFunc()];node.params.forEach(function(n){if(n.type==='Identifier'){vt=this._getVarType(n);curScope.args[n.name]={type:vt}}else{if(n.type==='AssignmentPattern'){if(n.left&&n.left.name){curScope.args[n.left.name]={type:'???'}}else{console.log('scopes nt = n.type')}}}},this)}}_isNewScope(node){var type=node.type;return type==='FunctionDeclaration'||type==='MethodDefinition'||type==='FunctionExpression'&&!this._inClass||type==='ClassBody'||type==='Program'}_varDecl(node){var curScope,vt,name;function _declVar(vt,self){curScope=self._fStack[self._getCurFunc()];if(node.id){name=node.id.name}else{name=node.key.name}curScope.vars[name]={type:vt,node:node}};vt=this._getVarType(node);if(this._varKind==='let'||this._varKind==='const'){if(this._blockStack.length===0){this._varKind='var'}}if(this._varKind==='var'||node.type==='ClassProperty'){_declVar(vt,this)}else if(this._varKind==='let'||this._varKind==='const'){let b=this._getCurBlock();if(b>=0){let block=this._bStack[b];let br=block.node.range;let start=node.range;if(start[0]>=br[0]&&start[1]<=br[1]){block.lets[node.id.name]={type:vt,node:node}}}else{_declVar(vt,this)}}}_getVarType(node){var vt,ta,et,ty;if(node.type==='ClassProperty'){if(node.value){if(node.value.type==='ArrowFunctionExpression'){return'function'}else if(node.value.type==='CallExpression'){if(node.value.callee.object.name==='ko'){if(node.value.callee.property.name==='observable'){return'KO_Observable'}else if(node.value.callee.property.name==='computed'){return'KO_computed'}else{return'KO_Unknown'}}}}}ta=node.id&&node.id.typeAnnotation?node.id.typeAnnotation:node.typeAnnotation;if(!ta){ty=node.init?this._getInitType(node.init):ANY}else{vt=ta.typeAnnotation.type;if(vt===TS_TYPEREF){if(ta.typeAnnotation.typeName.name){ty=ta.typeAnnotation.typeName.name}else{if(ta.typeAnnotation.typeName.left){if(ta.typeAnnotation.typeName.left.name){ty=ta.typeAnnotation.typeName.left.name;if(ta.typeAnnotation.typeName.right&&ta.typeAnnotation.typeName.right.name){ty+='.'+ta.typeAnnotation.typeName.right.name}}else if(ta.typeAnnotation.typeName.left.left.name){ty+='.'+ta.typeAnnotation.typeName.left.left.name;if(ta.typeAnnotation.typeName.left.right.name){ty+='.'+ta.typeAnnotation.typeName.left.right.name}if(ta.typeAnnotation.typeName.right.name){ty+='.'+ta.typeAnnotation.typeName.right.name}}}}}else if(vt===TS_ARRAY){et=ta.typeAnnotation.elementType.type;if(et===TS_TYPEREF){ty=ta.typeAnnotation.elementType.typeName.name+'[]'}else{ty=et+'[]'}}else{ty=vt}}if(ty){ty=_transformType(ty)}if(!ty){console.log('[ASSERT]: scopes: ty not defined')}return ty}_getInitType(init){var vt,raw;if(init.type==='Literal'&&init.raw){raw=init.raw;if(raw.charAt(0)==='"'||raw.charAt(0)==='\''){vt=STRING}else if(raw==='true'||raw==='false'){vt=BOOLEAN}else if(!isNaN(raw)){vt=NUMBER}else if(raw==='null'){vt=NULL}else{console.log('[ASSERT]: SCOPES - UNKNOWN VAR INIT LITERAL = '+raw);vt=UNKNOWN}}else if(init.type==='ObjectExpression'){vt=OBJECT}else if(init.type==='NewExpression'){if(init.callee&&init.callee.name){vt=init.callee.name}}else if(init.type==='CallExpression'){if(init.callee&&init.callee.object){let o=init.callee.object;if(o.type==='Identifier'&&o.name==='document'){o=init.callee.property;if(o=DOCUMENT_METHODS[o.name]){return o}else{return'unknown document function'}}if(o.type==='MemberExpression'){vt=this._unravelCallME(o)}if(init.callee&&init.callee.object&&init.callee.object.type==='FunctionExpression'){vt='function'}}}else if(init.type==='MemberExpression'){if(init.object.type==='TSAsExpression'){vt=UNKNOWN}}else if(init.type==='TSAsExpression'){if(init.typeAnnotation&&init.typeAnnotation.type==='TSTypeReference'){vt=init.typeAnnotation.typeName.name}else{vt=UNKNOWN}}else if(init.type==='TSTypeAssertion'){if(init.typeAnnotation){vt=init.typeAnnotation.type}}else{vt=init.type}if(!vt){vt=UNKNOWN}return vt}_isMethodRange(n,node){return n.value&&n.value.body&&n.value.body.range===node.range}_unravelCallME(o){var prop;if(o.object.type==='ThisExpression'){prop=o.property.name;return this._getClassPropType(o,prop)}}_getClassPropType(o,prop){var c,ret;c=this._getContainingClass(o);if(c&&c.vars){ret=c.vars[prop];if(ret){ret=ret.type}}return ret}_getContainingClass(node){var c=this._getCurFunc(node);if(c<0){return}do{c=this._fStack[c];if(c.node.type==='ClassBody'){break}c=c.parent}while(c>=0);return c}_dumpEnter(node){let funcName=node.id?node.id.name:'anon';console.log(`ENTER=${funcName} ${node.type}`)}_dumpLeave(node){let funcName=node.id?node.id.name:'anon';console.log(`LEAVE=${funcName} ${node.type}`)}dumpStacks(){this.dumpFuncStack();this.dumpBlockStack()}dumpFuncStack(){var st,v,o,s,i,title;console.log('\n-------- Function/Class Scope Map --------');st=this._fStack;for(i=0;i<st.length;i++){o=st[i];s=(o.children.length?'children='+_dumpArrayIndices(o.children):'')+' blocks='+_dumpArrayIndices(o.blocks);console.log(`\n[${i}] "${o.func}" ${_dumpStackType(o)} parent=${o.parent} ${s}`);title=false;if(_hasProps(o.args)){for(v in o.args){console.log((!title?' Args: ':' ')+v+': '+o.args[v].type);title=true}}else{console.log(' Args: none')}title=false;if(_hasProps(o.vars)){for(v in o.vars){console.log((!title?' Vars: ':' ')+v+': '+o.vars[v].type+' ('+(o.vars[v].node.type==='ClassProperty'?'class prop':'var')+')');title=true}}else{console.log(' Vars: none')}}}dumpBlockStack(){var st,v,o,ch,i,title;console.log('\n-------- Internal Block Scope Map --------');st=this._bStack;if(!st.length){console.log('\nNo blocks.');return''}for(i=0;i<st.length;i++){o=st[i];ch=o.children.length?'children='+_dumpArrayIndices(o.children):'';console.log(`\n[${i}] ${this._dumpBlkOwner(o)}="${this._fStack[o.func].func}" parent=${o.parent} ${ch}`);title=false;if(_hasProps(o.lets)){for(v in o.lets){console.log((!title?' Lets: ':' ')+v+': '+o.lets[v].type);title=true}}else{console.log(' Lets: none')}}}_dumpBlkOwner(o){var f=this._fStack[o.func];return f.node.type==='FunctionDeclaration'?'func':'meth'}_getNextAnon(){return ANON+ ++this._nextAnonId}};function _hasProps(obj){var ret=false;for(var prop in obj){if(obj.hasOwnProperty(prop)){ret=true;break}}return ret};function _dumpArrayIndices(a){var ret='[';a.forEach(function(v,i){ret+=(i?', ':'')+v});return ret+']'}function _dumpStackType(o){var s='';switch(o.node.type){case'ClassBody':s='class';break;case'MethodDefinition':s='method';break;case'FunctionDeclaration':s='func';break;}return s.length?'('+s+')':s};function _transformType(ty){const list={TSStringKeyword:'string',TSNumberKeyword:'number',TSBooleanKeyword:'boolean',TSNullKeyword:'null',TSObjectKeyword:'object',TSUnknownKeyword:'unknown',TSAnyKeyword:'any'};return list[ty]||ty};class _scope{constructor(fs,bs){this._fstk=fs;this._bstk=bs}getVarType(node){var name,func,block,v;name=node.name;if(!node.name){return null}block=this.getContainingBlock(node);if(block){v=block.lets[name];if(v){return v.type}while(block.parent>=0){block=this._bstk[block.parent];if(block){v=block.lets[name];if(v){return v.type}}}}func=this.getContainingFunc(node);do{if(func.vars&&func.vars[name]){v=func.vars[name].type}else if(func.args&&func.args[name]){v=func.args[name].type}if(v){break}if(func.parent>=0){func=this._fstk[func.parent]}else{func=null}}while(func);return v}getContainingFunc(node){var start,fnRange,fnIndex,func,fr,i;start=node.range[0];for(i=0;i<this._fstk.length;i++){func=this._fstk[i];fr=func.node.range;if(start>=fr[0]&&start<=fr[1]){if(fnRange){if(fr[0]>=fnRange[0]&&fr[1]<=fnRange[1]){fnRange=fr;fnIndex=i}}else{fnRange=fr;fnIndex=i}}}return typeof fnIndex==='number'?this._fstk[fnIndex]:null}getContainingBlock(node){var nrange,brange,range,bindex,blocks,block,i;if(!this._bstk.length)return;var blocks=this.getContainingFunc(node).blocks;nrange=node.range;for(i=0;i<blocks.length;i++){block=this._bstk[i];brange=block.node.range;if(nrange[0]>=brange[0]&&nrange[1]<=brange[1]){if(range){if(brange[0]>=range[0]&&brange[1]<=range[1]){range=nrange;bindex=i}}else{range=brange;bindex=i}}}return typeof bindex==='number'?this._bstk[bindex]:null}getContainingClass(node){}getGlobals(){return this._fstk[0]}getFuncStack(){return this._fstk}getBlockStack(){return this._bstk}};module.exports=Scope;
|
|
6
|
+
var walker=require('./scopewalker');const TS_ANY='TSAnyKeyword';const TS_TYPEREF='TSTypeReference';const TS_ARRAY='TSArrayType';const STRING='string';const NUMBER='number';const BOOLEAN='boolean';const NULL='null';const OBJECT='Object';const FUNCTION='function';const ANY='any';const UNKNOWN='unknown';const PROGRAM='Program';const GLOBAL_SCOPE='_@global';const ANON='$anon';const DOCUMENT_METHODS={createElement:'Element',createTextNode:'Element',getElementById:'Element',getElementsByClassName:'HTMLCollection',getElementsByName:'HTMLCollection',getElementsByTagName:'HTMLCollection',getElementsByTagNameNS:'HTMLCollecion',hasFocus:'boolean',querySelector:'Element',querySelectorAll:'NodeList'};const DOCUMENT_MEMBERS={activeElement:'Element',anchors:'HTMLCollection',body:'Element',childElementCount:'number',dir:'string',documentElement:'Element',documentURI:'string',docType:'DTD',forms:'HTMLCollection',getElementById:'Element',head:'Element',hidden:'boolean',links:'HTMLCollection',scrollingElement:'Element',visibilityState:'string'};const INDENT=3;var _level=-INDENT;function _trace(t,n){function _rj(s,w){s=''+s;if(s.length<w){s=' '.repeat(w-s.length)+s}return s}_level+=t==='E'?INDENT:0;if(t==='E')console.log(`${_rj(n.loc.start.line,4)}] ${' '.repeat(_level)} ${n.type}`);else console.log(`${' '.repeat(4)} ${' '.repeat(_level)} ${n.type}`);_level-=t==='L'?INDENT:0};class Scope{constructor(msgCtx,config,file){this._msgCtx=msgCtx;this._config=config;this._file=file;this.reset()}reset(){this._fStack=[];this._bStack=[];this._imports=[];this._funcStack=[];this._idxStack=0;this._parents=[];this._blockStack=[];this._idxBlkStack=0;this._blkParents=[];this._nextAnonId=0;this._varKind;this._level=-INDENT}build(ast){this.reset();try{walker.traverse(ast,{enter:this._enter.bind(this),leave:this._leave.bind(this)})}catch(e){let stk=e.stack;let x=stk.indexOf('\n');stk=x>=0?stk.substring(x+1):stk;stk=`${'-'.repeat(10)}\n${stk}\n${'-'.repeat(10)}`;this._msgCtx.jafMsg('jaf-ts-walk',`TS walk exception: ${e.message} File: ${this._file}\n\n${stk}`)}return{funcs:this._fStack,blocks:this._bStack}}_buildFuncIndexesToBlocks(){var i,j;for(i=0;i<this._fStack.length;i++){for(j=0;j<this._bStack.length;j++){if(this._bStack[j].func==i){this._fStack[i].blocks.push(j)}}}}getAccessor(){return new _scope(this._fStack,this._bStack)}_enter(node){var type;if(this._msgCtx.isDebug){_trace('E',node)}type=node.type;if(this._isNewScope(node)){this._addNewFunc(node)}else if(type==='VariableDeclarator'||type==='ClassProperty'){this._varDecl(node)}else if(type==='VariableDeclaration'){this._varKind=node.kind}else if(type==='BlockStatement'){this._addNewBlock(node)}else if(type==='ClassDeclaration'){this._inClass=true;this._className=node.id.name}else if(type==='ImportDeclaration'){this._addImport(node)}}_leave(node){if(this._msgCtx.isDebug){_trace('L',node)}if(this._isNewScope(node)){if(this._parents.length){this._parents.pop()}this._funcStack.pop()}else if(node.type==='BlockStatement'){if(this._blkParents.length){this._blkParents.pop()}this._blockStack.pop()}else if(node.type==='ClassDeclaration'){this._inClass=false;this._className=null}}_addNewFunc(node){var type,func,curParent,x;type=node.type;if(type===PROGRAM){func=GLOBAL_SCOPE}else if(node.kind==='method'||node.kind==='constructor'){func=node.key.name}else if(node.id){func=node.id.name}else if(type==='ClassBody'){func=this._className}else{this._getNextAnon()}if(this._parents.length){curParent=this._fStack[this._parents[this._parents.length-1]]}x=this._fStack.push({func:func,node:node,vars:{},args:{},blocks:[],children:[],parent:this._parents.length?this._parents[this._parents.length-1]:-1});x--;this._parents.push(x);if(curParent){curParent.children.push(x)}this._funcStack.push(x);this._addFuncArgs(node)}_addNewBlock(node){var func,curParent,x;var func=this._fStack[this._getCurFunc()];let n=this._fStack[this._getCurFunc()].node;if((n.kind==='method'||n.kind==='constructor')&&this._isMethodRange(n,node)||n.kind!=='method'&&n.kind!=='constructor'&&node.range===n.body.range){return}if(this._blkParents.length){curParent=this._bStack[this._blkParents[this._blkParents.length-1]]}x=this._bStack.push({func:this._getCurFunc(),node:node,lets:{},children:[],parent:this._blkParents.length?this._blkParents[this._blkParents.length-1]:-1});x--;this._blkParents.push(x);if(curParent){curParent.children.push(x)}this._blockStack.push(x);func.blocks.push(x)}_addImport(node){var src,local,o;src=node.source.value;if(!src.startsWith('ojs/')){return}o={src:src};if(node.specifiers.length){node.specifiers.forEach(s=>{if(!local)local=[];local.push(s.local.name)});if(local){o.local=local}}this._imports.push(o)}_getCurFunc(){return this._funcStack[this._funcStack.length-1]}_getCurBlock(){return this._blockStack[this._blockStack.length-1]}_addFuncArgs(node){var vt,curScope;if(node.params){curScope=this._fStack[this._getCurFunc()];node.params.forEach(function(n){if(n.type==='Identifier'){vt=this._getVarType(n);curScope.args[n.name]={type:vt}}else{if(n.type==='AssignmentPattern'){if(n.left&&n.left.name){curScope.args[n.left.name]={type:'???'}}else{console.log('scopes nt = n.type')}}}},this)}}_isNewScope(node){var type=node.type;return type==='FunctionDeclaration'||type==='MethodDefinition'||type==='FunctionExpression'&&!this._inClass||type==='ClassBody'||type==='Program'}_varDecl(node){var curScope,vt,name;function _declVar(vt,self){curScope=self._fStack[self._getCurFunc()];if(node.id){name=node.id.name}else{name=node.key.name}curScope.vars[name]={type:vt,node:node}};vt=this._getVarType(node);if(this._varKind==='let'||this._varKind==='const'){if(this._blockStack.length===0){this._varKind='var'}}if(this._varKind==='var'||node.type==='ClassProperty'){_declVar(vt,this)}else if(this._varKind==='let'||this._varKind==='const'){let b=this._getCurBlock();if(b>=0){let block=this._bStack[b];let br=block.node.range;let start=node.range;if(start[0]>=br[0]&&start[1]<=br[1]){block.lets[node.id.name]={type:vt,node:node}}}else{_declVar(vt,this)}}}_getVarType(node){var vt,ta,et,ty;if(node.type==='ClassProperty'){if(node.value){if(node.value.type==='ArrowFunctionExpression'){return'function'}else if(node.value.type==='CallExpression'){if(node.value.callee.object.name==='ko'){if(node.value.callee.property.name==='observable'){return'KO_Observable'}else if(node.value.callee.property.name==='computed'){return'KO_computed'}else{return'KO_Unknown'}}}}}ta=node.id&&node.id.typeAnnotation?node.id.typeAnnotation:node.typeAnnotation;if(!ta){ty=node.init?this._getInitType(node.init):ANY}else{vt=ta.typeAnnotation.type;if(vt===TS_TYPEREF){if(ta.typeAnnotation.typeName.name){ty=ta.typeAnnotation.typeName.name}else{if(ta.typeAnnotation.typeName.left){if(ta.typeAnnotation.typeName.left.name){ty=ta.typeAnnotation.typeName.left.name;if(ta.typeAnnotation.typeName.right&&ta.typeAnnotation.typeName.right.name){ty+='.'+ta.typeAnnotation.typeName.right.name}}else if(ta.typeAnnotation.typeName.left.left.name){ty+='.'+ta.typeAnnotation.typeName.left.left.name;if(ta.typeAnnotation.typeName.left.right.name){ty+='.'+ta.typeAnnotation.typeName.left.right.name}if(ta.typeAnnotation.typeName.right.name){ty+='.'+ta.typeAnnotation.typeName.right.name}}}}}else if(vt===TS_ARRAY){et=ta.typeAnnotation.elementType.type;if(et===TS_TYPEREF){ty=ta.typeAnnotation.elementType.typeName.name+'[]'}else{ty=et+'[]'}}else{ty=vt}}if(ty){ty=_transformType(ty)}if(!ty){console.log('[ASSERT]: scopes: ty not defined')}return ty}_getInitType(init){var vt,raw;if(init.type==='Literal'&&init.raw){raw=init.raw;if(raw.charAt(0)==='"'||raw.charAt(0)==='\''){vt=STRING}else if(raw==='true'||raw==='false'){vt=BOOLEAN}else if(!isNaN(raw)){vt=NUMBER}else if(raw==='null'){vt=NULL}else{console.log('[ASSERT]: SCOPES - UNKNOWN VAR INIT LITERAL = '+raw);vt=UNKNOWN}}else if(init.type==='ObjectExpression'){vt=OBJECT}else if(init.type==='NewExpression'){if(init.callee&&init.callee.name){vt=init.callee.name}}else if(init.type==='CallExpression'){if(init.callee&&init.callee.object){let o=init.callee.object;if(o.type==='Identifier'&&o.name==='document'){o=init.callee.property;if(o=DOCUMENT_METHODS[o.name]){return o}else{return'unknown document function'}}if(o.type==='MemberExpression'){vt=this._unravelCallME(o)}if(init.callee&&init.callee.object&&init.callee.object.type==='FunctionExpression'){vt='function'}}}else if(init.type==='MemberExpression'){if(init.object.type==='TSAsExpression'){vt=UNKNOWN}}else if(init.type==='TSAsExpression'){if(init.typeAnnotation&&init.typeAnnotation.type==='TSTypeReference'){vt=init.typeAnnotation.typeName.name}else{vt=UNKNOWN}}else if(init.type==='TSTypeAssertion'){if(init.typeAnnotation){vt=init.typeAnnotation.type}}else if(init.type==='AwaitExpression'){vt=ANY}else{vt=init.type}if(!vt){vt=UNKNOWN}return vt}_isMethodRange(n,node){return n.value&&n.value.body&&n.value.body.range===node.range}_unravelCallME(o){var prop;if(o.object.type==='ThisExpression'){prop=o.property.name;return this._getClassPropType(o,prop)}}_getClassPropType(o,prop){var c,ret;c=this._getContainingClass(o);if(c&&c.vars){ret=c.vars[prop];if(ret){ret=ret.type}}return ret}_getContainingClass(node){var c=this._getCurFunc(node);if(c<0){return}do{c=this._fStack[c];if(c.node.type==='ClassBody'){break}c=c.parent}while(c>=0);return c}_dumpEnter(node){let funcName=node.id?node.id.name:'anon';console.log(`ENTER=${funcName} ${node.type}`)}_dumpLeave(node){let funcName=node.id?node.id.name:'anon';console.log(`LEAVE=${funcName} ${node.type}`)}dumpStacks(){this.dumpFuncStack();this.dumpBlockStack()}dumpFuncStack(){var st,v,o,s,i,title;console.log('\n-------- Function/Class Scope Map --------');st=this._fStack;for(i=0;i<st.length;i++){o=st[i];s=(o.children.length?'children='+_dumpArrayIndices(o.children):'')+' blocks='+_dumpArrayIndices(o.blocks);console.log(`\n[${i}] "${o.func}" ${_dumpStackType(o)} parent=${o.parent} ${s}`);title=false;if(_hasProps(o.args)){for(v in o.args){console.log((!title?' Args: ':' ')+v+': '+o.args[v].type);title=true}}else{console.log(' Args: none')}title=false;if(_hasProps(o.vars)){for(v in o.vars){console.log((!title?' Vars: ':' ')+v+': '+o.vars[v].type+' ('+(o.vars[v].node.type==='ClassProperty'?'class prop':'var')+')');title=true}}else{console.log(' Vars: none')}}}dumpBlockStack(){var st,v,o,ch,i,title;console.log('\n-------- Internal Block Scope Map --------');st=this._bStack;if(!st.length){console.log('\nNo blocks.');return''}for(i=0;i<st.length;i++){o=st[i];ch=o.children.length?'children='+_dumpArrayIndices(o.children):'';console.log(`\n[${i}] ${this._dumpBlkOwner(o)}="${this._fStack[o.func].func}" parent=${o.parent} ${ch}`);title=false;if(_hasProps(o.lets)){for(v in o.lets){console.log((!title?' Lets: ':' ')+v+': '+o.lets[v].type);title=true}}else{console.log(' Lets: none')}}}_dumpBlkOwner(o){var f=this._fStack[o.func];return f.node.type==='FunctionDeclaration'?'func':'meth'}_getNextAnon(){return ANON+ ++this._nextAnonId}};function _hasProps(obj){var ret=false;for(var prop in obj){if(obj.hasOwnProperty(prop)){ret=true;break}}return ret};function _dumpArrayIndices(a){var ret='[';a.forEach(function(v,i){ret+=(i?', ':'')+v});return ret+']'}function _dumpStackType(o){var s='';switch(o.node.type){case'ClassBody':s='class';break;case'MethodDefinition':s='method';break;case'FunctionDeclaration':s='func';break;}return s.length?'('+s+')':s};function _transformType(ty){const list={TSStringKeyword:'string',TSNumberKeyword:'number',TSBooleanKeyword:'boolean',TSNullKeyword:'null',TSObjectKeyword:'object',TSUnknownKeyword:'unknown',TSAnyKeyword:'any'};return list[ty]||ty};class _scope{constructor(fs,bs){this._fstk=fs;this._bstk=bs}getVarType(node){var name,func,block,v;if(!(name=node.name)){return null};block=this.getContainingBlock(node);if(block){v=block.lets[name];if(v){return v.type}while(block.parent>=0){block=this._bstk[block.parent];if(block){v=block.lets[name];if(v){return v.type}}}}func=this.getContainingFunc(node);do{if(func.vars&&func.vars[name]){v=func.vars[name].type}else if(func.args&&func.args[name]){v=func.args[name].type}if(v){break}if(func.parent>=0){func=this._fstk[func.parent]}else{func=null}}while(func);return v}getContainingFunc(node){var start,fnRange,fnIndex,func,fr,i;start=node.range[0];for(i=0;i<this._fstk.length;i++){func=this._fstk[i];fr=func.node.range;if(start>=fr[0]&&start<=fr[1]){if(fnRange){if(fr[0]>=fnRange[0]&&fr[1]<=fnRange[1]){fnRange=fr;fnIndex=i}}else{fnRange=fr;fnIndex=i}}}return typeof fnIndex==='number'?this._fstk[fnIndex]:null}getContainingBlock(node){var nrange,brange,range,bindex,blocks,block,i;if(!this._bstk.length)return;var blocks=this.getContainingFunc(node).blocks;nrange=node.range;for(i=0;i<blocks.length;i++){block=this._bstk[i];brange=block.node.range;if(nrange[0]>=brange[0]&&nrange[1]<=brange[1]){if(range){if(brange[0]>=range[0]&&brange[1]<=range[1]){range=nrange;bindex=i}}else{range=brange;bindex=i}}}return typeof bindex==='number'?this._bstk[bindex]:null}getContainingClass(node){}getGlobals(){return this._fstk[0]}getFuncStack(){return this._fstk}getBlockStack(){return this._bstk}};module.exports=Scope;
|
package/lib/Utils.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const daysOfWeek=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];const WHITESPACE=" \t\n\r\x0B";const NL="\n";const CR="\r";const DOT=".";function Utils(nd){this._nd=nd;this._tabHandler=null};Utils.prototype.isObject=function(value){return typeof value==="object"&&!Array.isArray(value)};Utils.prototype.isArrayContentsType=function(ar,type){var i,elemType,ret=true;var isAr=Array.isArray(type);for(i=0;i<ar.length;i++){elemType=this.getType(ar[i]);if(isAr&&!type.includes(elemType)||!isAr&&elemType!==type){ret=false;break}}return ret};Utils.prototype.extend=function(from,internal,to){var prop,what;to=to||{};for(prop in from){if(!internal&&(prop.startsWith("_")||prop==="$builtin")){continue}what=from[prop];if(Array.isArray(what)){to[prop]=what.slice()}else{to[prop]=what}}return to};Utils.prototype.hasAnyProps=function(obj){var ret=false;if(obj){for(var prop in obj){if(obj.hasOwnProperty(prop)){ret=true;break}}}return ret};Utils.prototype.isProperty=function(obj,propName){var a,i;a=this.splitString(propName,DOT);for(i=0;i<a.length;i++){if(this.getType(obj)!=="object"||!obj.hasOwnProperty(a[i])){break}obj=obj[a[i]]}return i>=a.length};Utils.prototype.getProperty=function(obj,propName){var a,i;a=this.splitString(propName,DOT);for(i=0;i<a.length;i++){if(this.getType(obj)!=="object"||!obj.hasOwnProperty(a[i])){break}obj=obj[a[i]]}return i>=a.length?obj:undefined};Utils.prototype.splitString=function(s,sep){var a=s.split(sep);a.forEach(function(val,index){a[index]=a[index].trim()});return a};Utils.prototype.getType=function(val){var t=typeof val;if(val===undefined){t="undefined"}else if(val===null){t="null"}else if(t==="object"){if(Array.isArray(val)){t="array"}else if(this.isObject(val)){t="object"}else{console.log("[ASSERT] unknown object type' "+t+"'");t="?"}}return t};Utils.prototype.format=function(msg,vars){var v,k,k2,i;for(v in vars){k="${"+v+"}";k2=new RegExp("\\$\\{"+v+"\\}","g");i=msg.indexOf(k);if(i>=0){msg=msg.replace(k2,vars[v])}}return msg};Utils.prototype.removeMarkup=function(m){var s;if(!m){return m}s=m.replace(/<[^>]+>/g,"");s=s.replace(/\s\s+/g," ");return s};Utils.prototype.getRowColFromIndex=function(data,disp,fileType,tabs){var row=1,col=1,i,c,len=data.length;var oTabs=tabs?tabs:this._tabHandler;for(i=0;i<len;i++){if(i===disp)break;c=data.charAt(i);if(c==="\n"){row++;col=1}else if(c==="\t"){if(oTabs){col=oTabs.getTabCol(col,fileType)}else{col++}}else if(c!=="\r"){col++}}return{row:row,col:col}};Utils.prototype.decommentJson=function(text){return this._nd.decomment(text)};Utils.prototype.parseJson=function(data,comments){var obj,ret;comments=typeof comments!=="undefined"?!!comments:true;if(comments){data=this._nd.decomment(data)}let x=this.eatWhitespace(data);if(x>=0){let c=data.charAt(x);if(c!=="{"&&c!=="["){return this._convertJsonPosToRowCol(
|
|
6
|
+
const daysOfWeek=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];const WHITESPACE=" \t\n\r\x0B";const NL="\n";const CR="\r";const DOT=".";const SP=" ";function Utils(nd){this._nd=nd;this._tabHandler=null};Utils.prototype.isObject=function(value){return typeof value==="object"&&!Array.isArray(value)};Utils.prototype.isArrayContentsType=function(ar,type){var i,elemType,ret=true;var isAr=Array.isArray(type);for(i=0;i<ar.length;i++){elemType=this.getType(ar[i]);if(isAr&&!type.includes(elemType)||!isAr&&elemType!==type){ret=false;break}}return ret};Utils.prototype.extend=function(from,internal,to){var prop,what;to=to||{};for(prop in from){if(!internal&&(prop.startsWith("_")||prop==="$builtin")){continue}what=from[prop];if(Array.isArray(what)){to[prop]=what.slice()}else{to[prop]=what}}return to};Utils.prototype.hasAnyProps=function(obj){var ret=false;if(obj){for(var prop in obj){if(obj.hasOwnProperty(prop)){ret=true;break}}}return ret};Utils.prototype.isProperty=function(obj,propName){var a,i;a=this.splitString(propName,DOT);for(i=0;i<a.length;i++){if(this.getType(obj)!=="object"||!obj.hasOwnProperty(a[i])){break}obj=obj[a[i]]}return i>=a.length};Utils.prototype.getProperty=function(obj,propName){var a,i;a=this.splitString(propName,DOT);for(i=0;i<a.length;i++){if(this.getType(obj)!=="object"||!obj.hasOwnProperty(a[i])){break}obj=obj[a[i]]}return i>=a.length?obj:undefined};Utils.prototype.splitString=function(s,sep){var a=s.split(sep);a.forEach(function(val,index){a[index]=a[index].trim()});return a};Utils.prototype.getType=function(val){var t=typeof val;if(val===undefined){t="undefined"}else if(val===null){t="null"}else if(t==="object"){if(Array.isArray(val)){t="array"}else if(this.isObject(val)){t="object"}else{console.log("[ASSERT] unknown object type' "+t+"'");t="?"}}return t};Utils.prototype.format=function(msg,vars){var v,k,k2,i;for(v in vars){k="${"+v+"}";k2=new RegExp("\\$\\{"+v+"\\}","g");i=msg.indexOf(k);if(i>=0){msg=msg.replace(k2,vars[v])}}return msg};Utils.prototype.removeMarkup=function(m){var s;if(!m){return m}s=m.replace(/<[^>]+>/g,"");s=s.replace(/\s\s+/g," ");return s};Utils.prototype.getRowColFromIndex=function(data,disp,fileType,tabs){var row=1,col=1,i,c,len=data.length;var oTabs=tabs?tabs:this._tabHandler;for(i=0;i<len;i++){if(i===disp)break;c=data.charAt(i);if(c==="\n"){row++;col=1}else if(c==="\t"){if(oTabs){col=oTabs.getTabCol(col,fileType)}else{col++}}else if(c!=="\r"){col++}}return{row:row,col:col}};Utils.prototype.decommentJson=function(text){return this._nd.decomment(text)};Utils.prototype.parseJson=function(data,comments){var obj,ret;comments=typeof comments!=="undefined"?!!comments:true;if(comments){data=this._nd.decomment(data)}let x=this.eatWhitespace(data);if(x>=0){let c=data.charAt(x);if(c!=="{"&&c!=="["){return this._convertJsonPosToRowCol(`Invalid JSON - unexpected start character '${c}' at position ${x}`,data)}}try{obj=JSON.parse(data);ret={obj:obj,msg:null,startIndex:undefined,endIndex:undefined}}catch(e){if(e.toString().startsWith("SyntaxError")){ret=this._convertJsonPosToRowCol(e.message,data)}else{ret.msg=e.message}ret.obj=null}return ret};Utils.prototype._convertJsonPosToRowCol=function(msg,data){var x,n,rc;x=msg.indexOf("position");if(x<0){if(msg.startsWith("Unexpected end of JSON")){msg+=` at position ${data.length-1}`;x=msg.indexOf("position")}else{n=data.length-1;return{msg:msg,line:0,row:0,startIndex:0,endIndex:0}}}n=parseInt(msg.substring(x+8).trim());rc=this.getRowColFromIndex(data,n);x=msg.indexOf("at");if(x>=0){msg=msg.substring(0,x).trimRight()}x=msg.indexOf("token");if(x>=0){x+=6;let c=msg.charAt(x);let q=c==="'"?"\"":"'";msg=msg.substring(0,x)+q+c+q+msg.substring(x+1)}return{msg:msg,line:rc.row,col:rc.col,startIndex:n,endIndex:n}};Utils.prototype.eatLine=function(str,index){var ret,i,c;index=index||0;if(index>str.length){ret=""}for(i=index;i<str.length;i++){c=str.charAt(i);if(c=="\n"){ret=str.substring(i+1);break}}return ret};Utils.prototype.getLineStart=function(data,index){var c;if(data.length&&index>0&&index<data.length){while(--index){c=data.charAt(index);if(c===NL||c===CR){return index+1}}}return 0};Utils.prototype.getIndexToWhitespace=function(str,startIndex){var i,len,ret=-1;startIndex=startIndex>=0?startIndex:0;len=str?str.length:0;for(i=startIndex;i<len;i++){if(this.isWhitespace(str.charAt(i))){ret=i;break}}return ret};Utils.prototype.eatWhitespace=function(str,startIndex){var i,len,ret=-1;startIndex=startIndex>=0?startIndex:0;len=str?str.length:0;for(i=startIndex;i<len;i++){if(WHITESPACE.indexOf(str[i])<0){ret=i;break}}return ret};Utils.prototype.isWhitespace=function(c){return WHITESPACE.indexOf(c)>=0};Utils.prototype.isAlpha=function(c){return c>="a"&&c<="z"||c>="A"&&c<="Z"};Utils.prototype.isDigit=function(c){return c>="0"&&c<="9"};Utils.prototype.isAlphaNum=function(c){return this.isAlpha(c)||this.isDigit(c)};Utils.prototype.getCurrentDate=function(dateObj){var date,dayOfweek,tmp;date=dateObj?dateObj:new Date;dayOfweek=daysOfWeek[date.getDay()];date=date.toString();tmp=date.split(" ");tmp[0]=dayOfweek;return dayOfweek+" "+tmp[1]+" "+tmp[2]+", "+tmp[3]};Utils.prototype.getCurrentTime=function(dateObj){var time,hours,mins,zone;var ampm="am";time=dateObj?dateObj:new Date;hours=time.getHours();mins=time.getMinutes();if(hours>12){hours-=12;ampm="pm"}zone=time.toLocaleTimeString("en-us",{timeZoneName:"short"}).split(" ")[2];return hours+":"+(mins<=9?"0":"")+mins+ampm+" "+zone};Utils.prototype.lineWrap=function(text,width=95,clean=true){if(Array.isArray(text)){let i;for(i=0;i<text.length;i++){let s=text[i];let c=s[s.length-1];if(c!==NL&&c!==SP){text[i]=s+SP}}text=text.join("")}if(clean){text=text.replace(/\<p\>/g,NL);text=text.replace(/\<br\>/g,NL);text=text.replace(/\<b\>/g,"");text=text.replace(/\<i\>/g,"");text=text.replace(/\<\/b\>/g,"");text=text.replace(/\<\/i\>/g,"");text=text.replace(/</g,"<");text=text.replace(/>/g,">")}return this.breakLines(text,width)};Utils.prototype.breakLines=function(s,width){var lines=[];var line,start,end,c,x,y;var len=s.length;s=s.trimRight();len=s.length;if(len<width||len+1===width&&s.charAt(s.length-1)===DOT){lines.push(s);return lines}if(len+1===width&&s.charAt(s.length-1)===DOT){lines.push(s);return lines}start=0;while(start<len){x=this.eatWhitespace(s,start);if(x>0){start=x}end=start+width;line=s.substring(start,end+1);if(end>=len){if((x=line.indexOf(NL))>=0){lines.push(line.substring(0,x));start+=x+1;continue}lines.push(line);return lines}if(this.isWhitespace(line.charAt(line.length-1))){for(x=line.length-1;this.isWhitespace(s.charAt(x));x--){}x+=start}else{x=end;c=s.charAt(end+1);if(this.isAlphaNum(c)){for(;x>=start;x--){if(this.isWhitespace(s.charAt(x))){break}}}}x++;if(start<x){line=s.substring(start,x).trimRight()}else{line=s.substring(start,end).trimRight();x=end++}if((y=line.indexOf(NL))>=0){line=line.substring(0,y);x=start+y}lines.push(line);start=x}return lines};Utils.prototype.setTabHandler=function(oTabs){this._tabHandler=oTabs};module.exports=Utils;
|
package/lib/ZipUtils.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const TEMP_ZIP_TEMPLATE='@@ziptmp-XXXXXX.zip';
|
|
6
|
+
const TEMP_ZIP_TEMPLATE='@@ziptmp-XXXXXX.zip';var ZipUtils=function(nd,fsUtils){if(!this._unzipper){this._unzipper=require('adm-zip')}this._zip=null;this._nd=nd;this._fsUtils=fsUtils};ZipUtils.prototype.loadZip=function(zipPath){var ret;this._assertNoCurrentZip();this._zip=null;try{this._zip=new this._unzipper(zipPath);ret=true}catch(e){ret=e}return ret};ZipUtils.prototype.extractAll=function(to,zipPath,overwrite){var ret=false;try{this._assertNoCurrentZip();this._zip=null;this._zip=new this._unzipper(zipPath);if(this._zip){this._zip.extractAllTo(to,!!overwrite);ret=true}}catch(e){ret={message:e}}this._zip=null;return ret};ZipUtils.prototype.extractFileFromZip=function(filePath,zipPath){var text;try{if(zipPath){this._assertNoCurrentZip();this._zip=null;this._zip=new this._unzipper(zipPath)}if(this._zip){text=this._zip.readAsText(filePath);text=text?text.trim():''}}catch(e){text=e}return text};ZipUtils.prototype.getContents=function(zipPath){var entries,ret=[];if(typeof zipPath==='string'){try{this._assertNoCurrentZip();this._zip=null;this._zip=new this._unzipper(zipPath)}catch(e){ret=e}}if(this._zip){ret=[];entries=this._zip.getEntries();this._hierIndex=0;this._createHierarchy(entries,'',ret)}return ret};ZipUtils.prototype._createHierarchy=function(entries,subdir,ar){var entry,arDir,temp,x;for(;this._hierIndex<entries.length;this._hierIndex++){entry=entries[this._hierIndex];if(entry.isDirectory){if(entry.entryName.startsWith(subdir)||!subdir){arDir=[];temp=entry.entryName.substr(0,entry.entryName.length-1);x=temp.lastIndexOf('/');temp=x>=0?temp.substring(x+1):temp;ar.push({name:temp,path:entry.entryName,isFile:false,files:arDir});this._hierIndex++;this._createHierarchy(entries,entry.entryName,arDir)}else{this._hierIndex--;return}}else{if(entry.entryName.startsWith(subdir)||!subdir){ar.push({name:entry.name,isFile:true})}else{this._hierIndex--;return}}}};ZipUtils.prototype.writeBufferToFile=function(buffer,fpath){var ret;try{this._lastFile=fpath;this._nd.fs.writeFileSync(fpath,buffer);ret=true}catch(e){this._lastFile=null;ret=e}return ret};ZipUtils.prototype.deleteFile=function(fpath){var ret=null;try{fpath=fpath?fpath:this._lastFile;if(fpath){this._nd.fs.unlinkSync(fpath)}}catch(e){ret=e}this._zip=null;return ret};ZipUtils.prototype.getLastFilepath=function(){return this._lastFile};ZipUtils.prototype.createTempZipFilename=function(){return this._fsUtils.getUniqueFileName(TEMP_ZIP_TEMPLATE)};ZipUtils.prototype._assertNoCurrentZip=function(){if(this._zip){this._assert('loadZip but Zip EXISTS')}};module.exports=ZipUtils;
|
package/lib/amdlist.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2018, 2022, Oracle and/or its affiliates.
|
|
3
|
+
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
|
+
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
|
+
*/
|
|
6
|
+
const AVAIL_TITLE="---- Available in AMD mode ----";const UNAVAIL_TITLE="---- Unavailable in AMD mode ----";function show(nd,arg,appCtx){var packs;if(packs=nd.builtinpacks.getPackMetadata(nd,appCtx)){let prefixes=nd.builtinpacks.getPrefixes();arg=arg?arg.toLowerCase():arg;for(let pack of prefixes){if(!arg||arg===pack)_display(packs[pack],appCtx.colors)}}};function _display(pack,clr){var rules,rule,opts;let sorted=[],avail=[],unavail=[],max=0;console.log(`\n\n${clr.BRIGHTRED("\u25CF")} ${clr.CYAN("Pack")} ${clr.BRIGHTRED(`${pack.prefix}`)} ${clr.CYAN(" - Rules Available/Unavailable in AMD mode by default")}\n`);rules=pack.rules;_getSortedRulesByName(rules,sorted);for(rule of sorted){let ar;opts=rules[rule];ar=opts.hasOwnProperty("amd")&&!opts.amd?unavail:avail;ar.push(rule);ar.push(opts.hasOwnProperty("inservice")?opts.inservice:true);ar.push(opts.hasOwnProperty("enabled")?opts.enabled:true);max=rule.length>max?rule.length:max}console.log(clr.BRIGHTYELLOW(`● Available in AMD mode - ${avail.length/3}`));console.log(clr.BRIGHTYELLOW(`● Unavailable in AMD mode - ${unavail.length/3}\n`));if(!avail.length){return}_displayRules(unavail,false,max,clr);_displayRules(avail,true,max,clr);console.log("")};function _displayRules(list,avail,max,clr){if(!list.length){return}let rule,inserv,enabled,inserv_s,enabled_s,i;console.log(" "+clr.BRIGHTCYAN(avail?AVAIL_TITLE:UNAVAIL_TITLE));for(i=0;i<list.length;i++){rule=list[i++];inserv=list[i++];enabled=list[i];inserv_s=inserv?clr.BRIGHTGREEN(`${inserv}`):clr.RED(`${inserv}`);enabled_s=enabled?clr.BRIGHTGREEN(`${enabled}`):clr.RED(`${enabled}`);console.log(clr.BRIGHTYELLOW(`● ${rule}`)+_spacer(rule,max)+" "+clr.BRIGHTCYAN("In service:")+" "+inserv_s+" "+(inserv?" ":"")+clr.BRIGHTCYAN("Enabled:")+enabled_s)}};function _getSortedRulesByName(rules,sorted){var rule;for(rule in rules){sorted.push(rule)}sorted.sort()};function _spacer(s,max){return" ".repeat(max-s.length+2)};module.exports.show=show;
|
package/lib/api.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const OUTFMT=require("./outFormat");const UNDEF="undefined";
|
|
6
|
+
const OUTFMT=require("./outFormat");const UNDEF="undefined";function Api(nodeDeps,JafCore){this._core=JafCore;this._stats=JafCore.getStats();this._nd=nodeDeps};Api.prototype.startSync=function(apiContext){var core=this._core;core._ctxCB=apiContext;if(apiContext.config){let t=typeof apiContext.config;if(t==="string"){core._configPath=this._nd.path.join(core._curDir,apiContext.config)}else if(t==="object"){core._configPath=apiContext.config}else{core._error("Invalid config argument in init() : type is "+t);return 1}}if(apiContext.format&&apiContext.format!==OUTFMT.PROSE){apiContext.format=OUTFMT.PROSE}return core.start()};Api.prototype.start=function(apiContext,AmdMeta,AmdRulePacks){var t,_self,rc;this._core._isAsync=true;this._core._ctxCB=apiContext;_self=this;return new Promise(function(resolve,reject){let core=_self._core;setTimeout(()=>{try{if(apiContext.config){t=typeof apiContext.config;if(t==="string"){core._configPath=_self._nd.path.join(core._curDir,apiContext.config)}else if(t==="object"){core._configPath=apiContext.config}else{core._error("Invalid config argument in init() : type is "+t);reject(1)}}if(!core._isAMD){core._isAsync=false;core._isAsyncTemp=true;rc=_self.startSync(apiContext);core._isAsync=true;rc===0?resolve(rc):reject(core._messageStack)}else{if(apiContext.format&&apiContext.format!==OUTFMT.PROSE){apiContext.format=OUTFMT.PROSE}core._isAsync=false;core._isAsyncTemp=true;core._AmdMeta=AmdMeta;core._AmdRulePacks=AmdRulePacks;if(AmdRulePacks&&!Array.isArray(AmdRulePacks)){core._error("init() : AMD rule packs must be specified as an array!");reject(1);return}rc=_self.startSync(apiContext);core._isAsync=true;rc===0?resolve(rc):reject(core._messageStack)}}catch(e){reject(core._messageStack)}},0)})};Api.prototype.auditSync=function(filespec){var core=this._core;core._isAsync=false;this._stats.clearAll();if(core._regListenerTypesSet||core._rules&&core._rules.getActiveRuleCount()===0){if(core._rules){core._emitApiRunSummary()}return}if(filespec){if(!Array.isArray(filespec)){filespec=[filespec]}core._fileSet.setFiles(filespec,core._config.getExclude(),core._getMsgCtx())}core._startLifeCycle();core._emitApiRunSummary()};Api.prototype.audit=function(filespec){var rc,_self,core=this._core;core._isAsync=true;this._stats.clearAll();if(filespec){if(!Array.isArray(filespec)){filespec=[filespec]}core._fileSet.setFiles(filespec,core._config.getExclude(),core._getMsgCtx())}_self=this;return new Promise((resolve,reject)=>{setTimeout(()=>{try{_self._core._isAsync=false;rc=_self._core._startLifeCycle();_self._core._isAsync=true;_self._core._emitApiRunSummary();rc?resolve(0):reject(1)}catch(e){let m=`[JAF-9010] Internal Error:\n${_shortStackMsg(e)}`;core._error(m);reject(m)}},0)})};Api.prototype.on=function(evName,fn,obj){if(this._core._listenerSetup()){this._core._events.setListener(evName,fn,obj)}};Api.prototype.removeListener=function(evName,fn){if(this._core._listenerSetup()){this._core._events.removeListener(evName,fn)}};Api.prototype.removeAllListeners=function(evName){if(this._core._listenerSetup()){this._core._events.removeAllListeners(evName)}};Api.prototype.getDescription=function(arg1,arg2,arg3){var issue,short,ruleName,sig=0,ret="";var core=this._core;var arg1Type=core._Utils.getType(arg1);var arg2Type=core._Utils.getType(arg2);if(arg1Type==="object"){issue=arg1;if(arg2==="boolean"||arg2Type===UNDEF){short=arg2;sig=1;ruleName=issue.rule;msgId=issue.msgId}}else if(arg1Type==="string"){if(arg2Type==="string"){msgId=arg1;ruleName=arg2;short=!!arg3;sig=2}}var loadedRule,rsi,msgId,fn;if(sig){rsi=core._ruleSets.getRsiFromMsgId(msgId);if(rsi<0){return""}loadedRule=core._ruleSets.getLoadedRule(rsi,ruleName);fn=short?loadedRule.getShortDescription.bind(loadedRule):loadedRule.getDescription.bind(loadedRule);ret=fn()}return ret};Api.prototype.getRulesetInfo=function(fmt,active){var ret,core=this._core;active=typeof active==="undefined"?true:active;if(fmt===OUTFMT.JSON)ret=core._rules.getRulesJson(active);else if(fmt===OUTFMT.PROSE||fmt===OUTFMT.LINE)ret=core._rules.getRulesProse(active);else ret=core._rules.getRulesSonar(active);return ret};Api.prototype.enableMsgId=function(msgid,state){var ret=false;var core=this._core;if(core._config.setMessages(msgid,state)){core._reporter.setMessageFilter(core._config._config.messages);ret=true}return ret};Api.prototype.getConfig=function(){return this._core._config.getConfig()};Api.prototype.getSevLib=function(){return this._core._severity.getSevLib()};Api.prototype.getInfo=function(){return this._core._getInfo()};Api.prototype.setMarker=function(mark){return this._core.setMarker(mark)};Api.prototype.getMarker=function(){return this._core.getMarker()};Api.prototype.setVsCodeExtHint=function(isVsCodeExt){this._core._VsCodeExtHint=isVsCodeExt};function _shortStackMsg(e){let x,x2=0,m=e.stack||e;if((x=m.indexOf("\n"))>0){if((x2=m.indexOf("\n",x+1))<0){x2=x}}if(x2){m=m.substring(0,x2)}return m};module.exports=Api;
|
package/lib/betalist.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2018, 2022, Oracle and/or its affiliates.
|
|
3
|
+
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
|
+
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
|
+
*/
|
|
6
|
+
const PRODUCTION="production";const OOS="Not in service";const DISABLED="disabled";function show(nd,arg,appCtx){var packs;if(packs=nd.builtinpacks.getPackMetadata(nd,appCtx)){let prefixes=nd.builtinpacks.getPrefixes();arg=arg?arg.toLowerCase():arg;for(let pack of prefixes){if(!arg||arg===pack)_display(packs[pack],appCtx.colors)}}};function _display(pack,clr){var rules,rule,opts;let sorted=[],list=[],max=0;console.log(`\n\n${clr.BRIGHTRED("\u25CF")} ${clr.CYAN("Pack")} ${clr.BRIGHTRED(`${pack.prefix}`)} ${clr.CYAN(" - Rules Not in Production Status")}\n`);rules=pack.rules;_getSortedRulesByName(rules,sorted);for(rule of sorted){opts=rules[rule];if(opts.status!==undefined&&opts.status!==PRODUCTION){list.push(rule);list.push(opts.status);max=rule.length>max?rule.length:max;list.push(opts.hasOwnProperty("inservice")?opts.inservice:true);list.push(opts.hasOwnProperty("enabled")?opts.enabled:true)}}_displayRules(list,max,clr);console.log("")};function _displayRules(list,max,clr){console.log(" "+clr.BRIGHTCYAN("--- Non-Production Rules : ")+clr.BRIGHTGREEN(""+list.length/4));for(let i=0;i<list.length;i++){let rule,status,insrvc,enabled,avail;rule=list[i++];status=list[i++];insrvc=list[i++];enabled=list[i];if(!(insrvc&&enabled)){avail=" ("+(!insrvc?clr.BRIGHTRED(OOS):"")+(!insrvc&&!enabled?", ":"")+(!enabled?DISABLED:"")+")"}else{avail=""}console.log(clr.BRIGHTYELLOW(`● ${rule}`)+_spacer(rule,max)+" "+clr.BRIGHTCYAN(status)+avail)}};function _getSortedRulesByName(rules,sorted){for(let rule in rules){sorted.push(rule)}sorted.sort()};function _spacer(s,max){return" ".repeat(max-s.length+2)};module.exports.show=show;
|
package/lib/builtinpacks.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const PREFIX=["jet","jaf","jetwc","jetwco","csp","wdt"];const RP_PREFIX=["csp","jetwc","jetwco","spoc","wdt"];const RULES_JSON="rules.json";var
|
|
6
|
+
const PREFIX=["jet","jaf","jetwc","jetwco","csp","wdt","spoc"];const RP_PREFIX=["csp","jetwc","jetwco","spoc","wdt"];const RULES_JSON="rules.json";var _rDir;var _rpDir;function getPackMetadata(nd,appCtx){var prefix,o,i;var _packs={};_init(nd,appCtx);for(i=0;i<PREFIX.length;i++){prefix=PREFIX[i];if(o=_loadRulesJson(RP_PREFIX.includes(prefix)?_rpDir:_rDir,prefix,nd,appCtx)){_packs[o.prefix]=o.rjson}else{_packs=null;break}}return _packs};function getPrefixes(){return PREFIX};function getRulepackFolderPrefixes(){return RP_PREFIX};function _loadRulesJson(dir,prefix,nd,appCtx){var rjson,fp;fp=nd.path.join(dir,prefix,RULES_JSON);if(appCtx.fsUtils.fileExists(fp)){rjson=nd.jsonLoader.load(fp,nd,m=>{appCtx.error(m)},true,appCtx.utils)}else{appCtx.error(`Internal error: rule manifest for ${prefix} not found`);return null}if(rjson){return{prefix:prefix,rjson:rjson}}};function _init(nd){_rDir=nd.path.join(__dirname,"../rules");_rpDir=nd.path.join(__dirname,"../rulepacks")};module.exports={getPackMetadata,getPrefixes,getRulepackFolderPrefixes};
|
package/lib/checkage.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2018, 2022, Oracle and/or its affiliates.
|
|
3
|
+
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
|
+
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
|
+
*/
|
|
6
|
+
const BUILT="2022-07-12T01:49:42.958Z";function CheckAge(msgCtx){this._jetRels=-1;this._msgCtx=msgCtx}CheckAge.prototype.checkAge=function(){var ret=true;var monthsToRelease=0;var curDate=new Date;var buildDate=BUILT!=="@BUILT@"?new Date(BUILT):curDate;var buildMonth=buildDate.getMonth()+1;var months=_getElapsedMonths(buildDate,curDate);this._jetRels=_getReleases(buildMonth,months);if(months&&months<7){if(buildMonth<2){monthsToRelease=1}else{monthsToRelease=8-buildMonth}}if(months>monthsToRelease){this._emitMsg(months);ret=false}return ret};CheckAge.prototype.getJetReleaseCount=function(){return this._jetRels};CheckAge.prototype._emitMsg=function(old){var INDENT=" ".repeat(8);var s,h,p;if(this._jetRels){s=""+this._jetRels;if(this._jetRels===1){h="has";p=""}else{h="have";p="s"}}else{s="at least one";h="has";p=""}var s=`\nThis version of JAF is ${old} months old, and there ${h} been ${s} scheduled public\n`+`${INDENT}major JET release${p}, together with JAF updates and fixes. It is strongly\n`+INDENT+"recommended that you install the latest version of JAF. [JAF-9100]\n";this._msgCtx.warn(s,true)};function _getElapsedMonths(start,end){return end.getMonth()-start.getMonth()+12*(end.getFullYear()-start.getFullYear())};function _getReleases(buildMonth,months){var toNextRel,releases=0;if(buildMonth===1){toNextRel=0}else if(buildMonth>1&&buildMonth<7){toNextRel=7-buildMonth}else if(buildMonth===7){toNextRel=0}else{toNextRel=13-buildMonth}if((releases=months-toNextRel)>=0){releases=1+Math.floor(releases/6)}else{releases=0}return releases};module.exports=CheckAge;
|
package/lib/cliStats.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const Histo=require("./Histo");
|
|
6
|
+
const Histo=require("./Histo");class cliStats{constructor(nd,stats,severity,oConsole,info,isUnitTest,appCtx,useStdErr){this._nd=nd;this._severity=severity;this._clr=appCtx.colors;this._isColor=this._clr.isColor();this._console=oConsole;this._info=info;this._isUnitTest=isUnitTest;this._useStdErr=useStdErr;this._stats=stats}displayStatsAndHisto(elapsed){var clr=this._clr;var msg,msg2,sevs,n,m,l;var stats=this._stats;n=stats.errorFiles||stats.parseErrors;m=stats.totalIssues;msg="JET Audit: "+m+" issue"+(m!==1?"s":"")+(m!==1?" were":" was")+" found"+(m?" in "+stats.totalIssueFiles+" file"+(stats.totalIssueFiles!==1?"s":""):"")+".";msg="\n"+(m?clr.BLACKONRED(msg):clr.GREEN(msg));if(n){n=stats.errorFiles;m=stats.parseErrors;msg2=(n?" "+n+" file"+(n!==1?"s":"")+" could not be read.":"")+(m?" "+m+" parse error"+(m!==1?"s":"")+" "+(m===1?"was":"were")+" found.":"");msg+=clr.BLACKONRED(msg2)}this._console(msg);if(this._useStdErr){process.stderr.write(msg+"\n")}n=stats.totalFilesSelected;msg=_right(n,6)+" file"+(n===1?" ":"s ")+(n===1?"was":"were")+" selected.";n=stats.totalFilesAudited;msg+="\n"+_right(n,6)+" file"+(n===1?" ":"s ")+(n===1?"was":"were")+" audited.";n=stats.totalUrlsAudited;msg+="\n"+_right(n,6)+" URL"+(n===1?" ":"s ")+(n===1?"was":"were")+" audited.";n=stats.rulesFired;msg+="\n"+_right(n,6)+" rule"+(n===1?" ":"s ")+(n===1?"was":"were")+" fired.";n=stats.hooksFired;msg+="\n"+_right(n,6)+" hook rule"+(n===1?" ":"s ")+(n===1?"was":"were")+" fired.";sevs=this._severity.getMappedArray()||this._severity.getSevList();sevs=sevs.filter((val,x)=>sevs.indexOf(val)===x);l=0;sevs.forEach(v=>{n=v.length;l=n>l?n:l});l+=2;let sev,sevTotals;sevTotals=this._getSevTotals(stats.totalSevStats);var histo=new Histo(sevTotals,40,clr);msg+="\n\n"+"-".repeat(10)+"Severities"+"-".repeat(10);for(sev in sevTotals){n=sevTotals[sev];msg+="\n"+_left(sev,l)+": "+_right(n,6)+" |"+histo.bar(n)}msg+="\n"+"-".repeat(30);if(elapsed){msg+="\n[Elapsed: "+elapsed[0]+(elapsed[1]/1000000000).toString().substr(1,3)+"s]"}this._console(msg)}displayErrorsAndAsserts(){var clr=this._clr;var stats=this._stats;var msg="";if(stats.errors){msg+="[Error]: "+stats.errors+" error";msg+=(stats.errors===1?" was":"s were")+" found."}if(stats.warnings){if(msg.length){msg+="\n"}msg+="[Warn]: "+stats.warnings+" warning";msg+=(stats.warnings===1?" was":"s were")+" found."}if(stats.asserts){if(msg.length){msg+="\n"}msg+="[Warn]: "+stats.asserts+" assert";msg+=(stats.asserts===1?" was":"s were")+" found."}msg+="\n";if(!this._isUnitTest){this._info("\n"+clr.BLACKONRED(msg))}else{this._nd.fs.writeSync(process.stdout.fd,"\n"+clr.BLACKONRED(msg))}if(this._useStderr){process.stderr.write(msg+"\n")}}_getSevTotals(totalSevStats){var sevMap,sevTotals,sev,val,n=0;var sevTotals={};if(sevMap=this._severity.getInvertedSevMap()){for(sev in sevMap){val=sevMap[sev];if(!Array.isArray(val)){n+=totalSevStats[val]}else{val.forEach(v=>{n+=totalSevStats[v]})}sevTotals[sev]=n;n=0}}else{sevTotals=totalSevStats}return sevTotals}};function _right(num,len){var s=""+num;return len>s.length?" ".repeat(len-s.length)+s:s};function _left(num,len){var s=""+num;return len>s.length?s+" ".repeat(len-s.length):s};module.exports=cliStats;
|
package/lib/cmdline.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const OUTFMT=require("../lib/outFormat");const MACROS=require("../lib/macros");const ARG_CONFIG="--config";const ARG_CONFIG_SHORT="-c";const ARG_BASE="--base";const ARG_BASE_SHORT="-b";const ARG_SEVERITY="--severity";const ARG_SEVERITY_SHORT="-s";const ARG_FORMAT="--format";const ARG_FORMAT_SHORT="-t";const ARG_FOLLOWLINKS="--followlinks";const ARG_FOLLOWLINKS_SHORT="-fl";const ARG_NOFOLLOWLINKS="--nofollowlinks";const ARG_NOFOLLOWLINKS_SHORT="-nfl";const ARG_SHOWRULES="--rules";const ARG_SHOWRULES_SHORT="-r";const ARG_SHOWRULESJSON="--rulesjson";const ARG_SHOWRULESJSON_SHORT="-rj";const ARG_SHOWRULESSONAR="--rulessonar";const ARG_SHOWRULESSONAR_SHORT="-rs";const ARG_SHOWRULES_INTERNAL="-rx";const ARG_OUTPATH="--outpath";const ARG_OUTPATH_SHORT="-o";const ARG_NO_OUT="--noout";const ARG_NO_OUT_SHORT="-no";const ARG_NOCOLOR="--nocolor";const ARG_NOCOLOR_SHORT="-nc";const ARG_GROUPS="--groups";const ARG_GROUPS_SHORT="-g";const ARG_GROUPS_EQ="--groups=";const ARG_GROUPS_EQ_SHORT="-g=";const ARG_MSGID="--msgid";const ARG_MSGID_SHORT="-id";const ARG_WATCH="--watch";const ARG_WATCH_SHORT="-w";const ARG_VERSION="--version";const ARG_VERSION_SHORT="-v";const ARG_JETLIST="--jetlist";const ARG_JETLIST_SHORT="-jl";const ARG_DEFLIST="--default";const ARG_DEFLIST_ALT="--deflist";const ARG_DEFLIST_SHORT="-def";const ARG_GROUPLIST="--grouplist";const ARG_GROUPLIST_SHORT="-gl";const ARG_XGROUPLIST="--xgrouplist";const ARG_XGROUPLIST_SHORT="-xgl";const ARG_DISLIST="--dislist";const ARG_DISLIST_SHORT="-dl";const ARG_JETVER="--jetver";const ARG_JETVER_SHORT="-jv";const ARG_NAMESPACE_LIST="--nslist";const ARG_NAMESPACE_LIST_SHORT="-nsl";const ARG_METAHIST="--metahist";const ARG_METAHIST_SHORT="-mh";const ARG_RC="--retcode";const ARG_RC_EQ="--retcode=";const ARG_RC_SHORT="-rc";const ARG_RC_EQ_SHORT="-rc=";const ARG_DRYRUN="--dryrun";const ARG_DRYRUN_SHORT="-dr";const ARG_DAC="--daconfig";const ARG_DAC_SHORT="-dac";const ARG_REG="--reg";const ARG_REG_SHORT="-reg";const ARG_HELP="--help";const ARG_HELP_SHORT="-h";const ARG_HELP_SHORT_S="-hs";const ARG_EXTRA="--extra";const ARG_EXTRA_SHORT="-e";const ARG_DEBUG="--debug";const ARG_DEBUG_SHORT="-d";const ARG_SCAFFOLD="--init";const ARG_SCAFFOLD_SHORT="-i";const ARG_SCAFFOLD_RULE="--initrule";const ARG_SCAFFOLD_RULE_SHORT="-ir";const ARG_UNIT_TEST="-ut";const ARG_OJET="--ojet";const ARG_OJET_SHORT="-ojet";const ARG_EXPERIMENTAL="--x";const ARG_EXPERIMENTAL_SHORT="-x";module.exports.checkArgs=function(nodeDeps,rtf,showHelp,showVersion,msgCtx){var argLen,argOrig,arg,dontRun,temp,x,bArgsOk=true,bWantHelp=false,debugTitle;rtf.jetauditdir=nodeDeps.process.argv[1];rtf.jetauditdir=nodeDeps.path.dirname(rtf.jetauditdir);_checkBaseOptions(rtf,nodeDeps);if(rtf.debugSet){_dumpCmdLine()}argLen=process.argv.length;for(var i=2;i<argLen;i++){argOrig=process.argv[i];arg=argOrig.toLowerCase().trim();if(arg.length===0){continue}if(arg.charAt(0)!=="-"){if(!rtf.srcStack){rtf.srcStack=[]}arg=process.argv[i];arg=_handleQuotes(arg);arg=nodeDeps.path.normalize(arg);arg=nodeDeps.path.resolve(arg);rtf.srcStack.push(arg);if(rtf.debugMode||rtf.verboseMode){if(!debugTitle){msgCtx.info("Command line files specified:");debugTitle=true}msgCtx.info(" "+arg)}continue}if(_isBaseOption(arg)){continue}else if(arg===ARG_MSGID||arg===ARG_MSGID_SHORT){rtf.msgIdMode=rtf.msgIdModeSet=true}else if(arg===ARG_VERSION||arg===ARG_VERSION_SHORT){showVersion();dontRun=true}else if(arg===ARG_HELP||arg===ARG_HELP_SHORT||arg===ARG_HELP_SHORT_S){if(i+1<argLen){temp=process.argv[i+1];if(temp.charAt(0)==="-"){showHelp();dontRun=true;if(!_isBaseOption(temp))msgCtx.error(`Unexpected '${temp}'`);break}i++;if(arg===ARG_HELP||arg===ARG_HELP_SHORT){rtf.manCheckL=temp}else{rtf.manCheckS=temp}rtf.isManual=true;if(rtf.st_configSet){break}}else{showHelp();dontRun=true;break}}else if(arg===ARG_JETLIST||arg===ARG_JETLIST_SHORT){rtf.jetverList=true;break}else if(arg.startsWith(ARG_DEFLIST)||arg.startsWith(ARG_DEFLIST_SHORT)||arg.startsWith(ARG_DEFLIST_ALT)){rtf.defList=true;break}else if(arg===ARG_NAMESPACE_LIST||arg===ARG_NAMESPACE_LIST_SHORT){rtf.cmdNSList=true;break}else if(arg===ARG_DISLIST||arg===ARG_DISLIST_SHORT){rtf.disList=true;rtf.cmdArg=checkPackArg(i,argLen,msgCtx.error);break}else if(arg===ARG_GROUPLIST||arg===ARG_GROUPLIST_SHORT){rtf.groupList=true;rtf.cmdArg=checkPackArg(i,argLen,msgCtx.error);break}else if(arg===ARG_XGROUPLIST||arg===ARG_XGROUPLIST_SHORT){rtf.xgroupList=true;rtf.cmdArg=checkPackArg(i,argLen,msgCtx.error)}else if(arg===ARG_METAHIST||arg===ARG_METAHIST_SHORT){rtf.cmdMetaHist=true;break}else if(arg===ARG_CONFIG||arg===ARG_CONFIG_SHORT){i++;if(i<argLen){arg=process.argv[i];rtf.configPath=nodeDeps.path.normalize(arg);rtf.configPath=nodeDeps.path.resolve(rtf.configPath);rtf.st_configSet=true;if(rtf.isManual||rtf.xgroupList){break}}else{msgCtx.error("Invalid --config option");bArgsOk=false;bWantHelp=true}}else if(arg===ARG_BASE||arg===ARG_BASE_SHORT){i++;if(i<argLen){rtf.base=process.argv[i];if(rtf.base===MACROS.cwd||nodeDeps.fsUtils.getFileType(rtf.base)==="d"){rtf.st_baseSet=true}else{msgCtx.error(`'--base' ${rtf.base} is not a directory or the '$jafcwd' macro!!`);bArgsOk=false;bWantHelp=true}}else{msgCtx.error("Invalid --base option");bArgsOk=false;bWantHelp=true}}else if(arg===ARG_SEVERITY||arg===ARG_SEVERITY_SHORT){i++;if(i<argLen){rtf.severitySet=true;rtf.cliSev=process.argv[i]}else{msgCtx.error("Invalid --severity option");bArgsOk=false;bWantHelp=true}}else if(arg===ARG_JETVER||arg===ARG_JETVER_SHORT){i++;argOrig=i<argLen?process.argv[i]:null;arg=nodeDeps.jetver.validate(argOrig);if(arg){msgCtx.error(arg);bArgsOk=false;break}arg=nodeDeps.jetver.getBestVersion(argOrig);if(!arg){msgCtx.error(`'${argOrig}' is not a valid JET version`);bArgsOk=false;break}rtf.jetverSet=arg;if((rtf.verboseMode||rtf.debugMode)&&arg!==argOrig){msgCtx._info(`[Info]: JET version '${argOrig}' was promoted to '${arg}'`)}}else if(arg===ARG_FORMAT||arg===ARG_FORMAT_SHORT){i++;if(i<argLen){argOrig=process.argv[i];arg=argOrig.toLowerCase();if(arg!==OUTFMT.JSON&&arg!==OUTFMT.PROSE&&arg!==OUTFMT.LINE){msgCtx.error(`Invalid --format(-t) option '${argOrig}'`);bArgsOk=false;bWantHelp=true}else{rtf.outFormat=arg;rtf.st_formatSet=true}}else{msgCtx.error("Invalid --format option");bArgsOk=false;bWantHelp=true}}else if(arg===ARG_OUTPATH||arg===ARG_OUTPATH_SHORT){i++;if(rtf.st_outPathSet){msgCtx.error("--outPath and --noout are mutually exclusive");bArgsOk=false;bWantHelp=true}else{if(i<argLen){arg=process.argv[i];arg=nodeDeps.path.normalize(arg);rtf.outPath=nodeDeps.path.resolve(arg);rtf.st_outPathSet=true}else{msgCtx.error("Invalid --outPath option");bArgsOk=false;bWantHelp=true}}}else if(arg===ARG_NO_OUT||arg===ARG_NO_OUT_SHORT){if(rtf.st_outPathSet){msgCtx.error("--outPath and --noout are mutually exclusive");bArgsOk=false;bWantHelp=true}else{rtf.outPath="$noout";rtf.st_outPathSet=true}}else if(arg===ARG_FOLLOWLINKS||arg===ARG_FOLLOWLINKS_SHORT){rtf.followLinks=rtf.followLinksSet=true}else if(arg===ARG_NOFOLLOWLINKS||arg===ARG_NOFOLLOWLINKS_SHORT){rtf.followLinks=false;rtf.followLinksSet=true}else if(arg.startsWith(ARG_GROUPS_EQ)||arg.startsWith(ARG_GROUPS_EQ_SHORT)){x=arg.indexOf("=");if(temp=_convertToArray(argOrig.substring(x+1))){rtf.groupsSet=temp}else{msgCtx.error(`Invalid 'groups' declaration '${argOrig}`);bArgsOk=false;bWantHelp=true}}else if(arg===ARG_GROUPS||arg===ARG_GROUPS_SHORT){rtf.groupsSet=_checkGroups(process.argv,i+1);if(!rtf.groupsSet.groups||rtf.groupsSet.groups.length===0){msgCtx.error(!rtf.groupsSet.groups?`groups missing after flag ${argOrig}`:`Invalid ${argOrig} specification`);bArgsOk=false;bWantHelp=true}i=rtf.groupsSet.next;rtf.groupsSet=rtf.groupsSet.groups}else if(arg.startsWith(ARG_RC_EQ)||arg.startsWith(ARG_RC_EQ_SHORT)||arg===ARG_RC||arg===ARG_RC_SHORT){arg=argOrig;x=arg.indexOf("=");if(x>0){temp=argOrig.substring(0,x);arg=argOrig.substring(x+1)}else{temp=arg;i++;if(i<argLen){arg=process.argv[i]}else{msgCtx.error(`missing arguments after '${argOrig}'`);bArgsOk=false;bWantHelp=true}}if(bArgsOk){temp=_processRetCode(temp,arg);if(temp||typeof temp==="number"){rtf.retCode=temp;rtf.st_retCodeSet=true}else{msgCtx.error(`'${argOrig}' : ${arg.length?"'${arg}' is invalid":"missing argument?"}`);bArgsOk=false;bWantHelp=true}}}else if(arg===ARG_SHOWRULES||arg===ARG_SHOWRULES_SHORT){rtf.dumpRulesSet=true}else if(arg===ARG_SHOWRULESJSON||arg===ARG_SHOWRULESJSON_SHORT){rtf.dumpRulesJsonSet=true}else if(arg===ARG_SHOWRULESSONAR||arg===ARG_SHOWRULESSONAR_SHORT){rtf.dumpRulesSonarSet=true}else if(arg===ARG_SHOWRULES_INTERNAL){rtf.dumpRulesInternalSet=true}else if(arg===ARG_DRYRUN||arg===ARG_DRYRUN_SHORT){rtf.dryRunSet=rtf.dacSet=rtf.verboseMode=rtf.verboseSet=rtf.dumpRulesSet=true}else if(arg===ARG_DAC||arg===ARG_DAC_SHORT){rtf.dacSet=true}else if(arg===ARG_REG||arg===ARG_REG_SHORT){rtf.regListenerTypesSet=true}else if(arg===ARG_UNIT_TEST){rtf.unitTest=true}else if(arg===ARG_OJET||arg===ARG_OJET_SHORT){rtf.isOJETCLI=true}else if(arg===ARG_EXPERIMENTAL||arg===ARG_EXPERIMENTAL_SHORT){rtf.experimentalSet=true}else if(arg===ARG_WATCH||arg===ARG_WATCH_SHORT){if(rtf.experimentalSet){rtf.watchSet=true}}else if(arg===ARG_SCAFFOLD||arg===ARG_SCAFFOLD_SHORT){rtf.scaffoldSet=true}else if(arg===ARG_SCAFFOLD_RULE||arg===ARG_SCAFFOLD_RULE_SHORT){i++;if(i<argLen){rtf.scaffoldRuleSet=process.argv[i]}else{msgCtx.error("Invalid --initrule argument: rule name missing ");bArgsOk=false;bWantHelp=true}}else if(arg==="-z"){}else{msgCtx.error(`Invalid command flag '${argOrig}'`);bArgsOk=false;bWantHelp=true}}if(!dontRun&&bWantHelp){showHelp()}return dontRun?"end":bArgsOk};module.exports.displayCmdLineOptionsSet=function(rtf,msgCtx){var s="\n** Command line options:\n";if(rtf.dryRunSet){s+=" - Dry run ON\n"}if(rtf.dacSet){s+=" - Display active config ON\n"}if(rtf.verboseMode){s+=" - Verbose mode ON\n"}if(rtf.debugMode){s+=" - Debug mode ON\n"}if(rtf.watchSet){s+=" - watch mode ON\n"}if(rtf.groupsSet){s+=` - Groups set to ${rtf.groupsSet}\n`}if(rtf.st_retCodeSet){s+=` - retCode set to ${rtf.retCode}\n`}if(rtf.colorSet){s+=` - Color mode ${rtf.colorMode}? "ON" : "OFF"}\n`}if(rtf.msgIdModeSet){s+=` - Show msg ID's(${rtf.msgIdModeSet}? "ON" : "OFF"}\n`}if(rtf.st_formatSet){s+=` - Output in ${rtf.outFormat.toUpperCase()} format\n`}if(rtf.st_configSet){s+=` - Config set to ${rtf.configPath}\n`}if(rtf.severitySet){s+=` - Severity set to '${rtf.severity}'\n`}if(rtf.st_outPathSet){s+=` - Outpath set to ${rtf.outPath==="$noout"?"'none'":rtf.outPath}\n`}if(rtf.st_baseSet){s+=` - Base set to ${rtf.base}\n`}if(rtf.jetverSet){s+=` - JET version set to ${rtf.jetverSet}\n`}if(rtf.followLinksSet){s+=` - following stylesheet links is ${rtf.followLinks?"ON":"OFF"}\n`}if(rtf.dumpRulesSet||rtf.dumpRulesJsonSet||rtf.dumRulesSonarSet){s+=" - Dump Rules ON\n"}msgCtx.console(s+"\n")};module.exports.isCmdLineOptionsSet=function(rtf){return rtf.verboseMode||rtf.debugMode||rtf.colorSet||rtf.dumpRulesSet||rtf.dumpRulesJsonSet||rtf.dumpRulesSonarSet||rtf.dumpRulesInternalSet||rtf.msgIdModeSet||rtf.severitySet||rtf.watchSet||rtf.jetverSet||rtf.followLinksSet||rtf.dryRunSet||rtf.jetverList||rtf.cmdNSList||rtf.groupList||rtf.xgroupList||rtf.disList||rtf.cmdMetaHist||rtf.st_baseSet||rtf.st_formatSet||rtf.st_configSet||rtf.st_outPathSet||rtf.st_retCodeSet};function _checkBaseOptions(rtf,nd){var i,arg,argLen=process.argv.length;for(i=2;i<argLen;i++){arg=process.argv[i];if(arg.length===0||arg.charAt(0)!=="-"){continue}arg=arg.toLowerCase();if(arg===ARG_EXTRA||arg===ARG_EXTRA_SHORT){rtf.verboseMode=rtf.verboseSet=true}else if(arg===ARG_DEBUG||arg===ARG_DEBUG_SHORT){rtf.debugMode=rtf.debugSet=true}else if(arg===ARG_NOCOLOR||arg===ARG_NOCOLOR_SHORT){rtf.colorMode=false;rtf.colorSet=true;nd.colors.enable(false)}}};function _isBaseOption(arg){return arg===ARG_EXTRA||arg===ARG_EXTRA_SHORT||arg===ARG_DEBUG||arg===ARG_DEBUG_SHORT||arg===ARG_NOCOLOR||arg===ARG_NOCOLOR_SHORT};function _checkGroups(args,i){var arg,a,x,last,bound,groups;x=i;for(;;i++){if(i>=args.length||args[i].charAt(0)==="-"||last){break}arg=args[i].trim();if(x===i){bound=arg.startsWith("[")||arg.startsWith("(")}last=bound&&(arg.endsWith("]")||arg.endsWith(")"));arg=arg.replace(/[\[\(\)\]]/g,"").trim();if(!arg.length){break}arg=arg.replace(/,/g," ");arg=arg.replace(/ +(?= )/g,"").trim();if(!groups){groups=[]}a=arg.split(" ");groups=groups.concat(a)}return{next:bound?i:x,groups:groups}};function _processRetCode(arg,val){var temp,ret;if(val==="auto"||val==="errors"){ret=val}else{temp=parseInt(val);if(!isNaN(temp)){ret=temp}else{if(temp=_convertToArray(val)){ret=temp}}}return ret};function checkPackArg(i,argLen,error){var temp,lcTemp;if(i+1<argLen){temp=process.argv[i+1];lcTemp=temp.toLowerCase();if(temp.charAt(0)==="-"){if(!_isBaseOption(temp)&&lcTemp!==ARG_CONFIG&&lcTemp!==ARG_CONFIG_SHORT){error(`Unexpected '${temp}' - expected nothing, or a built-in pack prefix`)}temp=undefined}}return temp};function _convertToArray(s){var a,n,i;if(s.charAt(0)==="["){s=s.substring(1);if(!s.length){return null}}if(s.charAt(s.length-1)==="]"){s=s.substring(0,s.length-1)}s=s.trim();if(!s.length){return null}s=s.replace(/\,/g," ");s=s.replace(/\s\s+/g," ").trim();a=s.split(" ");n=0;for(i=0;i<a.length;i++){if(a[i].length){n++}else{a=a.splice(i,1);i--}}return n?a:null};function _handleQuotes(s){return s.replace(/[\"\']/g,"")};function _dumpCmdLine(){var s="";for(var i=0;i<process.argv.length;i++){s+=`[${i}]: |${process.argv[i]}|\n`}console.log(s)}
|
|
6
|
+
const OUTFMT=require("../lib/outFormat");const MACROS=require("../lib/macros");const ARG_CONFIG="--config";const ARG_CONFIG_SHORT="-c";const ARG_BASE="--base";const ARG_BASE_SHORT="-b";const ARG_SEVERITY="--severity";const ARG_SEVERITY_SHORT="-s";const ARG_FORMAT="--format";const ARG_FORMAT_SHORT="-t";const ARG_FOLLOWLINKS="--followlinks";const ARG_FOLLOWLINKS_SHORT="-fl";const ARG_NOFOLLOWLINKS="--nofollowlinks";const ARG_NOFOLLOWLINKS_SHORT="-nfl";const ARG_SHOWRULES="--rules";const ARG_SHOWRULES_SHORT="-r";const ARG_SHOWRULESJSON="--rulesjson";const ARG_SHOWRULESJSON_SHORT="-rj";const ARG_SHOWRULESSONAR="--rulessonar";const ARG_SHOWRULESSONAR_SHORT="-rs";const ARG_SHOWRULES_INTERNAL="-rx";const ARG_OUTPATH="--outpath";const ARG_OUTPATH_SHORT="-o";const ARG_NO_OUT="--noout";const ARG_NO_OUT_SHORT="-no";const ARG_NOCOLOR="--nocolor";const ARG_NOCOLOR_SHORT="-nc";const ARG_GROUPS="--groups";const ARG_GROUPS_SHORT="-g";const ARG_GROUPS_EQ="--groups=";const ARG_GROUPS_EQ_SHORT="-g=";const ARG_MSGID="--msgid";const ARG_MSGID_SHORT="-id";const ARG_WATCH="--watch";const ARG_WATCH_SHORT="-w";const ARG_VERSION="--version";const ARG_VERSION_SHORT="-v";const ARG_JETLIST="--jetlist";const ARG_JETLIST_SHORT="-jl";const ARG_DEFLIST="--default";const ARG_DEFLIST_ALT="--deflist";const ARG_DEFLIST_SHORT="-def";const ARG_GROUPLIST="--grouplist";const ARG_GROUPLIST_SHORT="-gl";const ARG_XGROUPLIST="--xgrouplist";const ARG_XGROUPLIST_SHORT="-xgl";const ARG_DISLIST="--dislist";const ARG_DISLIST_SHORT="-dl";const ARG_JETVER="--jetver";const ARG_JETVER_SHORT="-jv";const ARG_NAMESPACE_LIST="--nslist";const ARG_NAMESPACE_LIST_SHORT="-nsl";const ARG_PROFILES_LIST="--profiles";const ARG_PROFILES_LIST_SHORT="-prof";const ARG_AMDLIST="--amdlist";const ARG_AMDLIST_SHORT="-amd";const ARG_RLOLIST="--loadorder";const ARG_RLOLIST_SHORT="-rlo";const ARG_BETALIST="--betalist";const ARG_BETALIST_SHORT="-bl";const ARG_METAHIST="--metahist";const ARG_METAHIST_SHORT="-mh";const ARG_RC="--retcode";const ARG_RC_EQ="--retcode=";const ARG_RC_SHORT="-rc";const ARG_RC_EQ_SHORT="-rc=";const ARG_DRYRUN="--dryrun";const ARG_DRYRUN_SHORT="-dr";const ARG_DAC="--daconfig";const ARG_DAC_SHORT="-dac";const ARG_REG="--reg";const ARG_REG_SHORT="-reg";const ARG_HELP="--help";const ARG_HELP_SHORT="-h";const ARG_HELP_SHORT_S="-hs";const ARG_EXTRA="--extra";const ARG_EXTRA_SHORT="-e";const ARG_DEBUG="--debug";const ARG_DEBUG_SHORT="-d";const ARG_SCAFFOLD="--init";const ARG_SCAFFOLD_SHORT="-i";const ARG_SCAFFOLD_RULE="--initrule";const ARG_SCAFFOLD_RULE_SHORT="-ir";const ARG_UNIT_TEST="-ut";const ARG_OJET="--ojet";const ARG_OJET_SHORT="-ojet";const ARG_EXPERIMENTAL="--x";const ARG_EXPERIMENTAL_SHORT="-x";module.exports.checkArgs=function(nodeDeps,rtf,showHelp,showVersion,appCtx){var argLen,argOrig,arg,dontRun,temp,x,bArgsOk=true,bWantHelp=false,debugTitle;rtf.jetauditdir=nodeDeps.process.argv[1];rtf.jetauditdir=nodeDeps.path.dirname(rtf.jetauditdir);_checkBaseOptions(rtf,appCtx.colors);if(rtf.debugSet){_dumpCmdLine()}argLen=process.argv.length;for(var i=2;i<argLen;i++){argOrig=process.argv[i];arg=argOrig.toLowerCase().trim();if(arg.length===0){continue}if(arg.charAt(0)!=="-"){if(!rtf.srcStack){rtf.srcStack=[]}arg=process.argv[i];arg=_handleQuotes(arg);arg=nodeDeps.path.normalize(arg);arg=nodeDeps.path.resolve(arg);rtf.srcStack.push(arg);if(rtf.debugMode||rtf.verboseMode){if(!debugTitle){appCtx.info("Command line files specified:");debugTitle=true}appCtx.info(" "+arg)}continue}if(arg.endsWith("?")){temp=arg.replace(/[\-\?]/g,"");rtf.manCheckL=temp;rtf.isManual=true;rtf.isManPage=true;break}if(_isBaseOption(arg)){continue}else if(arg===ARG_MSGID||arg===ARG_MSGID_SHORT){rtf.msgIdMode=rtf.msgIdModeSet=true}else if(arg===ARG_VERSION||arg===ARG_VERSION_SHORT){showVersion();dontRun=true}else if(arg===ARG_HELP||arg===ARG_HELP_SHORT||arg===ARG_HELP_SHORT_S){if(i+1<argLen){temp=process.argv[i+1];if(temp.charAt(0)==="-"){showHelp();dontRun=true;if(!_isBaseOption(temp))appCtx.error(`Unexpected '${temp}'`);break}i++;if(arg===ARG_HELP||arg===ARG_HELP_SHORT){rtf.manCheckL=temp}else{rtf.manCheckS=temp}rtf.isManual=true;if(rtf.st_configSet){break}}else{showHelp();dontRun=true;break}}else if(arg===ARG_JETLIST||arg===ARG_JETLIST_SHORT){rtf.jetverList=true;break}else if(arg.startsWith(ARG_DEFLIST)||arg.startsWith(ARG_DEFLIST_SHORT)||arg.startsWith(ARG_DEFLIST_ALT)){rtf.defList=true;break}else if(arg===ARG_NAMESPACE_LIST||arg===ARG_NAMESPACE_LIST_SHORT){rtf.cmdNSList=true;break}else if(arg===ARG_PROFILES_LIST||arg===ARG_PROFILES_LIST_SHORT){rtf.profList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,false);break}else if(arg===ARG_DISLIST||arg===ARG_DISLIST_SHORT){rtf.disList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,true);break}else if(arg===ARG_AMDLIST||arg===ARG_AMDLIST_SHORT){rtf.amdList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,true);break}else if(arg===ARG_RLOLIST||arg===ARG_RLOLIST_SHORT){rtf.rloList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,true);break}else if(arg===ARG_BETALIST||arg===ARG_BETALIST_SHORT){rtf.betaList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,true);break}else if(arg===ARG_GROUPLIST||arg===ARG_GROUPLIST_SHORT){rtf.groupList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,true);break}else if(arg===ARG_XGROUPLIST||arg===ARG_XGROUPLIST_SHORT){rtf.xgroupList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,true)}else if(arg===ARG_METAHIST||arg===ARG_METAHIST_SHORT){rtf.cmdMetaHist=true;break}else if(arg===ARG_CONFIG||arg===ARG_CONFIG_SHORT){i++;if(i<argLen){arg=process.argv[i];rtf.configPath=nodeDeps.path.normalize(arg);rtf.configPath=nodeDeps.path.resolve(rtf.configPath);rtf.st_configSet=true;if(rtf.isManual||rtf.xgroupList){break}}else{appCtx.error("Invalid --config option");bArgsOk=false;bWantHelp=true}}else if(arg===ARG_BASE||arg===ARG_BASE_SHORT){i++;if(i<argLen){rtf.base=process.argv[i];if(rtf.base===MACROS.cwd||appCtx.utils.getFileType(rtf.base)==="d"){rtf.st_baseSet=true}else{appCtx.error(`'--base' ${rtf.base} is not a directory or the '$jafcwd' macro!!`);bArgsOk=false;bWantHelp=true}}else{appCtx.error("Invalid --base option");bArgsOk=false;bWantHelp=true}}else if(arg===ARG_SEVERITY||arg===ARG_SEVERITY_SHORT){i++;if(i<argLen){rtf.severitySet=true;rtf.cliSev=process.argv[i]}else{appCtx.error("Invalid --severity option");bArgsOk=false;bWantHelp=true}}else if(arg===ARG_JETVER||arg===ARG_JETVER_SHORT){i++;argOrig=i<argLen?process.argv[i]:null;arg=nodeDeps.jetver.validate(argOrig);if(arg){appCtx.error(arg);bArgsOk=false;break}arg=nodeDeps.jetver.getBestVersion(argOrig);if(!arg){appCtx.error(`'${argOrig}' is not a valid JET version`);bArgsOk=false;break}rtf.jetverSet=arg;if((rtf.verboseMode||rtf.debugMode)&&arg!==argOrig){appCtx._info(`[Info]: JET version '${argOrig}' was promoted to '${arg}'`)}}else if(arg===ARG_FORMAT||arg===ARG_FORMAT_SHORT){i++;if(i<argLen){argOrig=process.argv[i];arg=argOrig.toLowerCase();if(arg!==OUTFMT.JSON&&arg!==OUTFMT.PROSE&&arg!==OUTFMT.LINE){appCtx.error(`Invalid --format(-t) option '${argOrig}'`);bArgsOk=false;bWantHelp=true}else{rtf.outFormat=arg;rtf.st_formatSet=true}}else{appCtx.error("Invalid --format option");bArgsOk=false;bWantHelp=true}}else if(arg===ARG_OUTPATH||arg===ARG_OUTPATH_SHORT){i++;if(rtf.st_outPathSet){appCtx.error("--outPath and --noout are mutually exclusive");bArgsOk=false;bWantHelp=true}else{if(i<argLen){arg=process.argv[i];arg=nodeDeps.path.normalize(arg);rtf.outPath=nodeDeps.path.resolve(arg);rtf.st_outPathSet=true}else{appCtx.error("Invalid --outPath option");bArgsOk=false;bWantHelp=true}}}else if(arg===ARG_NO_OUT||arg===ARG_NO_OUT_SHORT){if(rtf.st_outPathSet){appCtx.error("--outPath and --noout are mutually exclusive");bArgsOk=false;bWantHelp=true}else{rtf.outPath="$noout";rtf.st_outPathSet=true}}else if(arg===ARG_FOLLOWLINKS||arg===ARG_FOLLOWLINKS_SHORT){rtf.followLinks=rtf.followLinksSet=true}else if(arg===ARG_NOFOLLOWLINKS||arg===ARG_NOFOLLOWLINKS_SHORT){rtf.followLinks=false;rtf.followLinksSet=true}else if(arg.startsWith(ARG_GROUPS_EQ)||arg.startsWith(ARG_GROUPS_EQ_SHORT)){x=arg.indexOf("=");if(temp=_convertToArray(argOrig.substring(x+1))){rtf.groupsSet=temp}else{appCtx.error(`Invalid 'groups' declaration '${argOrig}`);bArgsOk=false;bWantHelp=true}}else if(arg===ARG_GROUPS||arg===ARG_GROUPS_SHORT){rtf.groupsSet=_checkGroups(process.argv,i+1);if(!rtf.groupsSet.groups||rtf.groupsSet.groups.length===0){appCtx.error(!rtf.groupsSet.groups?`groups missing after flag ${argOrig}`:`Invalid ${argOrig} specification`);bArgsOk=false;bWantHelp=true}i=rtf.groupsSet.next;rtf.groupsSet=rtf.groupsSet.groups}else if(arg.startsWith(ARG_RC_EQ)||arg.startsWith(ARG_RC_EQ_SHORT)||arg===ARG_RC||arg===ARG_RC_SHORT){arg=argOrig;x=arg.indexOf("=");if(x>0){temp=argOrig.substring(0,x);arg=argOrig.substring(x+1)}else{temp=arg;i++;if(i<argLen){arg=process.argv[i]}else{appCtx.error(`missing arguments after '${argOrig}'`);bArgsOk=false;bWantHelp=true}}if(bArgsOk){temp=_processRetCode(temp,arg);if(temp||typeof temp==="number"){rtf.retCode=temp;rtf.st_retCodeSet=true}else{appCtx.error(`'${argOrig}' : ${arg.length?"'${arg}' is invalid":"missing argument?"}`);bArgsOk=false;bWantHelp=true}}}else if(arg===ARG_SHOWRULES||arg===ARG_SHOWRULES_SHORT){rtf.dumpRulesSet=true}else if(arg===ARG_SHOWRULESJSON||arg===ARG_SHOWRULESJSON_SHORT){rtf.dumpRulesJsonSet=true}else if(arg===ARG_SHOWRULESSONAR||arg===ARG_SHOWRULESSONAR_SHORT){rtf.dumpRulesSonarSet=true}else if(arg===ARG_SHOWRULES_INTERNAL){rtf.dumpRulesInternalSet=true}else if(arg===ARG_DRYRUN||arg===ARG_DRYRUN_SHORT){rtf.dryRunSet=rtf.dacSet=rtf.verboseMode=rtf.verboseSet=rtf.dumpRulesSet=true}else if(arg===ARG_DAC||arg===ARG_DAC_SHORT){rtf.dacSet=true}else if(arg===ARG_REG||arg===ARG_REG_SHORT){rtf.regListenerTypesSet=true}else if(arg===ARG_UNIT_TEST){rtf.unitTest=true}else if(arg===ARG_OJET||arg===ARG_OJET_SHORT){rtf.isOJETCLI=true}else if(arg===ARG_EXPERIMENTAL||arg===ARG_EXPERIMENTAL_SHORT){rtf.experimentalSet=true}else if(arg===ARG_WATCH||arg===ARG_WATCH_SHORT){if(rtf.experimentalSet){rtf.watchSet=true}}else if(arg===ARG_SCAFFOLD||arg===ARG_SCAFFOLD_SHORT){rtf.scaffoldSet=true}else if(arg===ARG_SCAFFOLD_RULE||arg===ARG_SCAFFOLD_RULE_SHORT){i++;if(i<argLen){rtf.scaffoldRuleSet=process.argv[i]}else{appCtx.error("Invalid --initrule argument: rule name missing ");bArgsOk=false;bWantHelp=true}}else if(arg==="-z"){}else{console.log("");appCtx.error(`Invalid command flag '${argOrig}' (Use ojaf -h to get help)`);bArgsOk=false;dontRun=true}}return dontRun?"end":bArgsOk};module.exports.displayCmdLineOptionsSet=function(rtf,appCtx){var s="\n** Command line options:\n";if(rtf.dryRunSet){s+=" - Dry run ON\n"}if(rtf.dacSet){s+=" - Display active config ON\n"}if(rtf.verboseMode){s+=" - Verbose mode ON\n"}if(rtf.debugMode){s+=" - Debug mode ON\n"}if(rtf.watchSet){s+=" - watch mode ON\n"}if(rtf.groupsSet){s+=` - Groups set to ${rtf.groupsSet}\n`}if(rtf.st_retCodeSet){s+=` - retCode set to ${rtf.retCode}\n`}if(rtf.colorSet){s+=` - Color mode ${rtf.colorMode}? "ON" : "OFF"}\n`}if(rtf.msgIdModeSet){s+=` - Show msg ID's(${rtf.msgIdModeSet}? "ON" : "OFF"}\n`}if(rtf.st_formatSet){s+=` - Output in ${rtf.outFormat.toUpperCase()} format\n`}if(rtf.st_configSet){s+=` - Config set to ${rtf.configPath}\n`}if(rtf.severitySet){s+=` - Severity set to '${rtf.severity}'\n`}if(rtf.st_outPathSet){s+=` - Outpath set to ${rtf.outPath==="$noout"?"'none'":rtf.outPath}\n`}if(rtf.st_baseSet){s+=` - Base set to ${rtf.base}\n`}if(rtf.jetverSet){s+=` - JET version set to ${rtf.jetverSet}\n`}if(rtf.followLinksSet){s+=` - following stylesheet links is ${rtf.followLinks?"ON":"OFF"}\n`}if(rtf.dumpRulesSet||rtf.dumpRulesJsonSet||rtf.dumRulesSonarSet){s+=" - Dump Rules ON\n"}appCtx.console(s+"\n")};module.exports.isCmdLineOptionsSet=function(rtf){return rtf.verboseMode||rtf.debugMode||rtf.colorSet||rtf.dumpRulesSet||rtf.dumpRulesJsonSet||rtf.dumpRulesSonarSet||rtf.dumpRulesInternalSet||rtf.msgIdModeSet||rtf.severitySet||rtf.watchSet||rtf.jetverSet||rtf.followLinksSet||rtf.dryRunSet||rtf.jetverList||rtf.cmdNSList||rtf.groupList||rtf.xgroupList||rtf.disList||rtf.cmdMetaHist||rtf.amdList||rtf.rloList||rtf.betaList||rtf.profList||rtf.st_baseSet||rtf.st_formatSet||rtf.st_configSet||rtf.st_outPathSet||rtf.st_retCodeSet};function _checkBaseOptions(rtf,clr){var i,arg,argLen=process.argv.length;for(i=2;i<argLen;i++){arg=process.argv[i];if(arg.length===0||arg.charAt(0)!=="-"){continue}arg=arg.toLowerCase();if(arg===ARG_EXTRA||arg===ARG_EXTRA_SHORT){rtf.verboseMode=rtf.verboseSet=true}else if(arg===ARG_DEBUG||arg===ARG_DEBUG_SHORT){rtf.debugMode=rtf.debugSet=true;rtf.debugMode=rtf.debugSet=rtf.verboseMode=true}else if(arg===ARG_NOCOLOR||arg===ARG_NOCOLOR_SHORT){rtf.colorMode=false;rtf.colorSet=true;clr.enable(false)}}};function _isBaseOption(arg){return arg===ARG_EXTRA||arg===ARG_EXTRA_SHORT||arg===ARG_DEBUG||arg===ARG_DEBUG_SHORT||arg===ARG_NOCOLOR||arg===ARG_NOCOLOR_SHORT};function _checkGroups(args,i){var arg,a,x,last,bound,groups;x=i;for(;;i++){if(i>=args.length||args[i].charAt(0)==="-"||last){break}arg=args[i].trim();if(x===i){bound=arg.startsWith("[")||arg.startsWith("(")}last=bound&&(arg.endsWith("]")||arg.endsWith(")"));arg=arg.replace(/[\[\(\)\]]/g,"").trim();if(!arg.length){break}arg=arg.replace(/,/g," ");arg=arg.replace(/ +(?= )/g,"").trim();if(!groups){groups=[]}a=arg.split(" ");groups=groups.concat(a)}return{next:bound?i:x,groups:groups}};function _processRetCode(arg,val){var temp,ret;if(val==="auto"||val==="errors"){ret=val}else{temp=parseInt(val);if(!isNaN(temp)){ret=temp}else{if(temp=_convertToArray(val)){ret=temp}}}return ret};function checkNextArg(i,argLen,error,argType){var temp,lcTemp;if(i+1<argLen){temp=process.argv[i+1];lcTemp=temp.toLowerCase();if(temp.charAt(0)==="-"){if(!_isBaseOption(temp)&&lcTemp!==ARG_CONFIG&&lcTemp!==ARG_CONFIG_SHORT){error(`Unexpected '${temp}' - expected nothing, or a ${argType?"built-in pack prefix":"profile name"}`)}temp=undefined}}return temp};function _convertToArray(s){var a,n,i;if(s.charAt(0)==="["){s=s.substring(1);if(!s.length){return null}}if(s.charAt(s.length-1)==="]"){s=s.substring(0,s.length-1)}s=s.trim();if(!s.length){return null}s=s.replace(/\,/g," ");s=s.replace(/\s\s+/g," ").trim();a=s.split(" ");n=0;for(i=0;i<a.length;i++){if(a[i].length){n++}else{a=a.splice(i,1);i--}}return n?a:null};function _handleQuotes(s){return s.replace(/[\"\']/g,"")};function _dumpCmdLine(){var s="";for(var i=0;i<process.argv.length;i++){s+=`[${i}]: |${process.argv[i]}|\n`}console.log(s)}
|
package/lib/defaults.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const defaults={JETVER:'
|
|
6
|
+
const defaults={JETVER:'13.0.0'.replace(/(\d*\.\d*)(\.\d*)+$/g,'$1')+'.0',THEME:'Alta',ECMAVER:11};module.exports=defaults;
|
package/lib/deflist.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const defs=require("./defaults");const indent=" ";function _show(nd){var
|
|
6
|
+
const defs=require("./defaults");const indent=" ";function _show(nd,clr){var s="\n"+clr.BRIGHTGREEN("--- Default JAF Values ---")+"\n\n"+`${indent}${clr.BRIGHTYELLOW("\u25CF jetVer ")}: ${clr.CYAN(`${defs.JETVER}`)}\n`+`${indent}${clr.BRIGHTYELLOW("\u25CF theme ")}: ${clr.CYAN("'Redwood' if jetVer >= 12.0.0, else 'Alta'")}\n`+`${indent}${clr.BRIGHTYELLOW("\u25CF ecmaVer ")}: ${clr.CYAN(`${defs.ECMAVER}`)}\n\n`+`${indent}${clr.BRIGHTYELLOW("\u25CF builtinJetRules ")}: ${clr.CYAN(`true`)}\n`+`${indent}${clr.BRIGHTYELLOW("\u25CF severity ")}: ${clr.CYAN("'all'")}\n`+`${indent}${clr.BRIGHTYELLOW("\u25CF groups ")}: ${clr.CYAN("'all'")}\n`+`${indent}${clr.BRIGHTYELLOW("\u25CF base ")}: ${clr.CYAN("location of configuration file")}\n`+`${indent}${clr.BRIGHTYELLOW("\u25CF files ")}: ${clr.CYAN(".html files in the 'base' directory")}\n`+`${indent}${clr.BRIGHTYELLOW("\u25CF format ")}: ${clr.CYAN("`prose'")}\n`+`${indent}${clr.BRIGHTYELLOW("\u25CF comments ")}: ${clr.CYAN("false")}\n`+`${indent}${clr.BRIGHTYELLOW("\u25CF followLinks ")}: ${clr.CYAN("true")}\n`+`${indent}${clr.BRIGHTYELLOW("\u25CF tempDir ")}: ${clr.CYAN("the current working directory")}\n`;console.log(s)};module.exports.showList=_show;
|
package/lib/dislist.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
|
|
6
|
+
function show(nd,arg,appCtx){var packs;if(packs=nd.builtinpacks.getPackMetadata(nd,appCtx)){let prefixes=nd.builtinpacks.getPrefixes();arg=arg?arg.toLowerCase():arg;for(let pack of prefixes){if(!arg||arg===pack)_display(packs[pack],appCtx.colors)}}};function _display(pack,clr){var rules,rule,opts,oos,summary=[];console.log(`\n\n${clr.BRIGHTRED("\u25CF")} ${clr.CYAN("Pack")} ${clr.BRIGHTRED(`${pack.prefix}`)} ${clr.CYAN(" - Rules disabled by default")}`);rules=pack.rules;for(rule in rules){opts=rules[rule];oos=opts.hasOwnProperty("inservice")&&!opts.inservice;if(oos||opts.hasOwnProperty("enabled")&&!opts.enabled){summary.push(rule+(oos?"_":""))}}if(summary.length){summary=summary.sort()}else{console.log(clr.BRIGHTYELLOW(`● None - all enabled.`));return}for(rule of summary){oos=rule.endsWith("_");rule=oos?rule.substring(0,rule.length-1):rule;console.log(clr.BRIGHTYELLOW(`● ${rule}`)+clr.RED(`${oos?" (out of service)":""}`))}};module.exports.show=show;
|
package/lib/exportRules.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const ELLIPSIS="...";const INDENT=" ";const INDENT2=" ";const INDENT3=" ";const proseIndent=4;const SPACER=" ".repeat(proseIndent);const SPACER2=" ".repeat(proseIndent+3);const SPACER3=" ".repeat(proseIndent+5);const NL="\n";var utils;var out;var severity;var jsonRules;var haveProseRules=false;function getXml(){return out+"</rules>"};function getProse(){return out};function getJson(){return out};function ruleToXml(ruleName,rule,options){var ruleName,val,opt,xml,i;xml=INDENT+"<rule>\n";xml+=INDENT2+"<key>"+ruleName+"</key>\n";xml+=INDENT2+"<name>"+_limitLength(_escapeChevrons(rule.getShortDescription()),utils)+"</name>\n";xml+=INDENT2+"<description>\n";xml+=INDENT3+"<![CDATA["+_escapeCData(rule.getDescription())+"]]>\n";xml+=INDENT2+"</description>\n";for(opt in options){val=options[opt];if(opt==="severity"){xml+=INDENT2+"<severity>"+val.toUpperCase()+"</severity>\n"}else if(opt==="status"){val=val.toUpperCase();val=val==="PRODUCTION"?"READY":val;xml+=INDENT2+"<status>"+val+"</status>\n"}else if(opt==="group"){if(typeof val==="string"){xml+=INDENT2+"<tag>"+val+"</tag>\n"}else{for(i=0;i<val.length;i++){xml+=INDENT2+"<tag>"+val[i]+"</tag>\n"}}}}out+=xml+INDENT+"</rule>\n"};function setupRulesToXml(
|
|
6
|
+
const ELLIPSIS="...";const JAF_OPTS=["inservice","enabled","group","severity","filetype","status","theme","jetver","amd","runonce","$hook","$required","$internal"];var MAX_OPT_LEN=0;const INDENT=" ";const INDENT2=" ";const INDENT3=" ";const proseIndent=4;const optsIndent=10;const SPACER=" ".repeat(proseIndent);const SPACER2=" ".repeat(proseIndent+3);const SPACER3=" ".repeat(proseIndent+5);const SPACER4=" ".repeat(SPACER3.length+optsIndent);const NL="\n";var clr;var utils;var fsUtils;var out;var severity;var jsonRules;var haveProseRules=false;function getXml(){return out+"</rules>"};function getProse(){return out};function getJson(){return out};function ruleToXml(ruleName,rule,options,msgIds){var ruleName,val,opt,xml,id,i;xml=INDENT+"<rule>\n";xml+=INDENT2+"<key>"+ruleName+"</key>\n";xml+=INDENT2+"<name>"+_limitLength(_escapeChevrons(rule.getShortDescription()),utils)+"</name>\n";xml+=INDENT2+"<description>\n";xml+=INDENT3+"<![CDATA["+_escapeCData(rule.getDescription())+"]]>\n";xml+=INDENT2+"</description>\n";xml+=INDENT2+"<messages>\n";for(id of msgIds){xml+=INDENT3+"<msgid>"+id+"</msgid>\n"}xml+=INDENT2+"</messages>\n";for(opt in options){val=options[opt];if(opt==="severity"){xml+=INDENT2+"<severity>"+val.toUpperCase()+"</severity>\n"}else if(opt==="status"){val=val.toUpperCase();val=val==="PRODUCTION"?"READY":val;xml+=INDENT2+"<status>"+val+"</status>\n"}else if(opt==="group"){if(typeof val==="string"){xml+=INDENT2+"<tag>"+val+"</tag>\n"}else{for(i=0;i<val.length;i++){xml+=INDENT2+"<tag>"+val[i]+"</tag>\n"}}}}out+=xml+INDENT+"</rule>\n"};function setupRulesToXml(appCtx){utils=appCtx.utils;fsUtils=appCtx.fsUtils;clr=appCtx.colors;out="<rules>\n"};function setupRulesToProse(nd,severity,appCtx){utils=appCtx.utils;fsUtils=appCtx.fsUtils;clr=appCtx.colors;out=`\n------------ Rules Currently Active (rule severity: ${severity}) ---------------\n`;for(let opt of JAF_OPTS){MAX_OPT_LEN=opt.length>MAX_OPT_LEN?opt.length:MAX_OPT_LEN}};function setupRulesToJson(obj,sev,appCtx){out=obj||{};severity=sev;out.rulesets=[];utils=appCtx.utils;fsUtils=appCtx.fsUtils;clr=appCtx.colors};function packToProse(rules,path,rsi){if(!rules){out+=SPACER2+"* No enabled rules available for this severity."+NL+NL}else{out+="["+(rsi+1)+"] "+rules.title+NL;out+=SPACER+"version : "+rules.version+NL;out+=SPACER+"prefix : "+rules.prefix+NL;out+=SPACER+"path : "+path+NL}haveProseRules=false};function ruleToProse(ruleName,rule,opts,msgIds){var opts,opt,ar,n,i;out+=!haveProseRules?SPACER+"Rules:"+NL:"";out+=SPACER2+clr.BRIGHTYELLOW("* "+ruleName+" :")+NL;out+=SPACER3+clr.BRIGHTCYAN("messages: ");out+=msgIds.join(", ")+NL;out+=SPACER3+clr.BRIGHTCYAN("options : ");n=0;for(opt in opts){if(_isJafOption(opt)){if(Array.isArray(ar=opts[opt])){ar=ar.join(", ")}out+=(!n?"":SPACER4)+clr.BRIGHTGREEN(opt)+" : "+_optSpace(opt)+clr.BRIGHTCYAN(ar)+NL}n++}for(opt in opts){if(!_isJafOption(opt)){out+=(!n?"":SPACER4)+clr.BRIGHTGREEN(opt)+" : "+_optSpace(opt)+clr.BRIGHTCYAN(opts[opt])+NL;n++}}let lines=utils.lineWrap(rule.getShortDescription());out+=SPACER3+clr.BRIGHTCYAN("short")+" : "+clr.BRIGHTCYAN(lines[0])+NL;for(i=1;i<lines.length;i++){out+=SPACER4+clr.BRIGHTCYAN(lines[i])+NL}lines=utils.lineWrap(rule.getDescription());out+=SPACER3+clr.BRIGHTCYAN("long")+" : "+clr.BRIGHTWHITE(lines[0])+NL;for(i=1;i<lines.length;i++){out+=SPACER4+clr.BRIGHTWHITE(lines[i])+NL}out+=NL;haveProseRules=true};function getJson(){out.meta={"severity":severity};return out};function packToJson(rulePack){var ruleset;ruleset={};out.rulesets.push(ruleset);ruleset.title=rulePack.rulesJson.title;ruleset.path=rulePack.path;ruleset.prefix=rulePack.rulesJson.prefix;ruleset.version=rulePack.rulesJson.version;ruleset.rules=jsonRules={}};function ruleToJson(ruleName,rule,opts,msgIds,active){jsonRules[ruleName]=opts;if(active||rule){opts.messages=msgIds;opts.shortDescription=rule.getShortDescription();opts.description=rule.getDescription()}else{opts.shortDescription=opts.description=""}};function _isJafOption(opt){return JAF_OPTS.includes(opt)};function _optSpace(opt){return" ".repeat(MAX_OPT_LEN-opt.length)};function _limitLength(s,utils){if(s.length>200){for(let i=196;i>0;i--){if(utils.isWhitespace(s.charAt(i))){return s.substring(0,i+1)+ELLIPSIS}}s=ELLIPSIS}return s};function _escapeChevrons(s){let ret=s.replace(/\</g,"<");ret=ret.replace(/\>/g,">");return ret.replace(/ /g," ")};function _escapeCData(s){var i,bChange;while(true){bChange=false;i=s.indexOf("<oj-");if(i>=0){s=s.substr(0,i)+"<"+s.substr(i+1);bChange=true;i=s.indexOf(">",i+1);if(i>=0){s=s.substr(0,i)+">"+s.substr(i+1)}i=s.indexOf("</oj-",i);if(i>=0){s=s.substr(0,i)+"<"+s.substr(i+1);bChange=true;i=s.indexOf(">",i+1);if(i>=0){s=s.substr(0,i)+">"+s.substr(i+1)}}}i=s.indexOf("<!DOCTYPE");if(i>=0){s=s.substr(0,i)+"<"+s.substr(i+1);i=s.indexOf(">",i+1);if(i>=0){s=s.substr(0,i)+">"+s.substr(i+1);bChange=true}}if(!bChange){break}}return s.replace(/ /g," ")};module.exports={getXml:getXml,getProse:getProse,getJson:getJson,ruleToXml:ruleToXml,ruleToProse:ruleToProse,packToProse:packToProse,packToJson:packToJson,ruleToJson:ruleToJson,setupRulesToXml:setupRulesToXml,setupRulesToProse:setupRulesToProse,setupRulesToJson:setupRulesToJson};
|
package/lib/extends.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const TSCONFIG="tsconfig.json";const MERGEABLE_BY_DEFAULT={components:true,componentUrls:true,exclude:true,files:true,groups:true,message:true,nameSpaces:true,options:true,ruleMods:true,ruleNames:true,rulePacks:true,typescript:true};const MERGEABLE_BY_OPTION={};const EXOPT_IGNORE="ignore";const EXOPT_MERGE="merge";const MSG={OBJ:"Config '%s' is not an object - %p",ARRAY:"Config '%s' is not an array - %p",STR:"Config '%s' is not a string - %p",STR_OR_AR_STR:"Config '%s' is not a string or an array of strings - %p",AR_OBJ:"Config '%s' is not an array of objects - %p",AR_STR:"Config '%s' is not an array of strings - %p",AR_STR_OBJ:"Config '%s' is not an array of strings or objects - %p",BOOL:"Config '%s' is not a boolean - %p",EXT_OPT:"Config 'extendOptions.%s' cannot be 'merge' - %p",EXT_OPT_VAL:"Config 'extendOptions.%s' not 'ignore' or 'merge' - %p",UNKNOWN:"Unknown config prop - '%s' - %p"};const REPL_PROP="%s";const REPL_PATH="%p";class Extends{constructor(configLib,configInst,cfg,path,nd,msgCtx,utils){this._path=path;this._cfg=cfg;this._fp=cfg.base;this._nd=nd;this._msgCtx=msgCtx;this._utils=utils;this._cwd=nd.process.cwd();this._cfgLib=configLib;this._cfgInst=configInst;this._stack=[];this._extendOpts=null;this._error=msgCtx.error;this._info=msgCtx.info;this._mergeHandlers={components:this._mergePropComponents.bind(this),componentUrls:this._mergePropCompUrls.bind(this),exclude:this._mergePropExclude.bind(this),files:this._mergePropFiles.bind(this),groups:this._mergePropGroups.bind(this),messages:this._mergePropMessages,nameSpaces:this._mergePropNameSpaces.bind(this),options:this._mergePropOptions.bind(this),ruleMods:this._mergePropRuleMods,ruleNames:this._mergePropRuleNames.bind(this),rulePacks:this._mergePropRulePacks,typescript:this._mergePropTypescript.bind(this)}}extend(){var debug;if(debug=this._cfg.options&&(this._cfg.options.verbose||this._cfg.options.debug)){this._msgCtx.info("[Info]: Merging configurations...","I",true)}if(!this._createStack()){return null}if(debug){this._dumpStack()}if(!this._isError){this._checkMergePropTypes()}if(this._isError){return null}if(!this._stack.length){return this._cfg}return this._mergeStack()}_createStack(cfg,fp){var json,fp,first,o;if(first=!cfg){cfg=this._cfg;fp=this._path?this._path:this._fp}else{fp=cfg.extends}if(!fp){return true}if(first){json=cfg}else{fp=this._getAbsolutePath(fp);if(!this._nd.fsUtils.fileExists(fp)){this._error(`Configuration file not found : ${fp}`);return false}if(this._isCircular(fp)){this._error(`Circular configuration 'extends' detected : ${fp}`);return false}try{json=this._nd.fs.readFileSync(fp,"utf8");json=this._nd.decomment(json);json=this._preprocessRawJson(json,fp);if(!json){return false}o=this._utils.parseJson(json,false);if(o.msg){this._error(`Config 'extends' error : ${o.msg} : ${fp}`);return false}else{json=o.obj}}catch(e){this._error(`Error reading 'extends' config : ${fp}`);return false}}this._stack.push({path:fp,cfg:json});if(json.extends){if(!this._createStack(json,json.extends)){return false}}return true}_preprocessRawJson(txt,fp){var json=this._cfgInst.processIncludes(txt,fp);if(this._cfgInst.isOk()){json=this._cfgInst.processTokens(json);if(this._cfgInst.isOk()){}}return this._cfgInst.isOk()?json:null}_mergeStack(){if(!this._fixupPaths()){return null}for(let i=this._stack.length-1;i>0;i--){if(!this._mergePair(this._stack[i-1],this._stack[i])){return null}}if(this._isMergeProp("files")){if(this._stack[0].cfg.hasOwnProperty("files")){this._stack[0].cfg.files=_removeDupes(this._stack[0].cfg.files)}}if(this._isMergeProp("exclude")){if(this._stack[0].cfg.hasOwnProperty("exclude")){this._stack[0].cfg.exclude=_removeDupes(this._stack[0].cfg.exclude)}}return this._stack[0].cfg}_mergePair(parSE,chSE){var props,parent,child,merger,ret=true;parent=parSE.cfg;child=chSE.cfg;this._extendOpts=parSE.cfg.extendOptions||{};props=Object.keys(child);props.forEach(prop=>{if(prop.startsWith("_")||prop==="base"||prop==="extends"||prop==="tokens"||this._extendOpts[prop]===EXOPT_IGNORE){return}if(!parent.hasOwnProperty(prop)){parent[prop]=child[prop];return}if(!this._isMergeProp(prop)){return}if(merger=this._mergeHandlers[prop]){if(!merger(parSE,chSE)){ret=false}}});if(!ret){return ret}this._msgCtx.info(`[Info]: Inherited config '${chSE.path}'`,"I",true);return true}_checkMergePropTypes(){var cfg,se,prop,prop2,val;for(let i=0;i<this._stack.length;i++){se=this._stack[i];cfg=se.cfg;if(!this._cfgLib.checkPropNames(cfg,se.path)){this._isError=true}if(cfg.extendOptions){if(this._utils.isObject(cfg.extendOptions)){this._extendOpts=cfg.extendOptions;for(prop in this._extendOpts){val=this._extendOpts[prop];if(val===EXOPT_MERGE&&!MERGEABLE_BY_OPTION[prop]){this._emitErrorMsg(MSG.EXT_OPT,prop,se.path);return}else if(val!==EXOPT_MERGE&&val!==EXOPT_IGNORE){this._emitErrorMsg(MSG.EXT_OPT_VAL,prop,se.path);return}}}else{this._emitErrorMsg(MSG.OBJ,"extendOptions",se.path);return}}else{this._extendOpts={}}for(prop in cfg){if(!this._isMergeProp(prop)){continue}val=cfg[prop];if(prop==="components"||prop==="componentUrls"){if(typeof val!=="string"&&!Array.isArray(val)||!this._utils.isArrayContentsType(val,"string")){this._emitErrorMsg(MSG.STR_OR_AR_STR,prop,se.path)}}else if(prop==="files"){if(!Array.isArray(val)){this._emitErrorMsg(prop,prop,se.path)}if(!this._utils.isArrayContentsType(val,["string","object"])){this._emitErrorMsg(MSG.AR_STR_OBJ,prop,se.path)}}else if(prop==="exclude"){if(!Array.isArray(val)||!this._utils.isArrayContentsType(val,"string")){this._emitErrorMsg(MSG.STR_OR_AR_STR,prop,se.path)}}else if(prop==="groups"){if(!Array.isArray(val)){this._emitErrorMsg(MSG.STR,prop,se.path)}}else if(prop==="messages"){if(!this._utils.isObject(val)){this._emitErrorMsg(MSG.OBJ,prop,se.path)}if(se.messages.reject){if(!Array.isArray(se.messages.reject)){this._emitErrorMsg(MSG.OBJ,"messages.reject",se.path)}}if(se.messages.accept){if(!Array.isArray(se.messages.accept)){this._emitErrorMsg(MSG.OBJ,"messages.accept",se.path)}}}else if(prop==="nameSpaces"){if(!Array.isArray(val)){this._emitErrorMsg(MSG.AR_STR,prop,se.path)}}else if(prop==="options"){if(!this._utils.isObject(val)){this._emitErrorMsg(MSG.OBJ,prop,se.path)}}else if(prop==="ruleMods"){if(!this._utils.isObject(val)){this._emitErrorMsg(MSG.OBJ,prop,se.path);continue}for(prop2 in val){if(prop2==="enable"||prop2==="disable"){if(!Array.isArray(val[prop2])){this._emitErrorMsg(MSG.AR_OBJ,prop2==="enable"?"ruleMods.enable":"ruleMods.disable",se.path)}}else{if(!this._utils.isObject(val[prop2])){this._emitErrorMsg(MSG.AR_OBJ,prop+"."+prop2,se.path)}}}}else if(prop==="ruleNames"){if(!Array.isArray(val)||!this._utils.isArrayContentsType(val,"string")){this._emitErrorMsg(MSG.AR_STR,prop,se.path)}}else if(prop==="rulePacks"){if(!Array.isArray(val)||!this._utils.isArrayContentsType(val,"object")){this._emitErrorMsg(MSG.AR_OBJ,prop,se.path)}}else if(prop==="sevMap"){if(!this._utils.isObject(val)){this._emitErrorMsg(MSG.OBJ,prop,se.path)}if(val.sevMsg&&!this._utils.isObject(val.sevMsg)){this._emitErrorMsg(MSG.OBJ,prop+".sevMsg",se.path)}if(val.sevSet&&!this._utils.isObject(val.sevSet)){this._emitErrorMsg(MSG.OBJ,prop+".sevSet",se.path)}}else if(prop==="tokens"){if(!this._utils.isObject(val)){this._emitErrorMsg(MSG.OBJ,prop,se.path)}}else if(prop==="typescript"){if(!this._utils.isObject(val)){this._emitErrorMsg(MSG.OBJ,prop,se.path)}for(prop2 in val){if(prop2==="tsconfig"&&typeof val[prop2]!=="string"){this._emitErrorMsg(MSG.STR,"typescript.tsconfig",se.path)}if(prop2==="compile"&&typeof val[prop2]!=="boolean"){this._emitErrorMsg(MSG.BOOL,"typescript.compile",se.path)}}}else{this._error(`JAF ERROR: unhandled 'extends' property '${prop}' - ${se.path}`);this._isError=true}}}}_fixupPaths(){var se,ret=true;for(let i=this._stack.length-1;i>=0;i--){se=this._stack[i];if(!(this._cleanBase(se)&&this._fixupConfig(se))){ret=false;break}}return ret}_cleanBase(se){var src,ft;var nd=this._nd;src=se.cfg.base;if(src==="$jafcwd"){src=this._cwd}else{if(!src){src=this._nd.path.dirname(se.path)}src=nd.path.normalize(src);if(!nd.path.isAbsolute(src)){src=nd.path.join(nd.path.dirname(se.path),src)}ft=nd.fsUtils.getFileType(src);if(ft!=="d"){this._msgCtx.error(`Config file 'base' is not a directory - '${src}' in ${se.path}`);return false}}se.cfg.base=src;this._info(`[Info]: Using config base '${src}' in ${se.path}`,"I");return true}_fixupConfig(se){var nd,cfg,src,dir,ft,i;nd=this._nd;cfg=se.cfg;if(cfg.files){if(!this._cfgLib.validateFileList(cfg.files)){this._bErrors=true;return}if(src=se.cfg.files){for(i=0;i<src.length;i++){if(!src[i].startsWith("http")){src[i]=nd.path.normalize(src[i]);src[i]=nd.path.resolve(cfg.base,src[i])}}}}if(cfg.exclude){if(!this._cfgLib.validateFileList(cfg.exclude)){this._bErrors=true;return}if(src=cfg.exclude){for(i=0;i<src.length;i++){src[i]=nd.path.normalize(src[i]);src[i]=nd.path.resolve(cfg.base,src[i])}}}src=cfg.components;if(src){for(i=0;i<src.length;i++){dir=nd.path.normalize(src[i]);dir=nd.path.resolve(cfg.base,dir);cfg.components[i]=dir}}src=cfg.outPath;if(src&&src!=="$noout"){src=nd.path.normalize(src);src=nd.path.resolve(cfg.base,src);cfg.outPath=src}src=cfg.rulePacks;if(src){for(i=0;i<src.length;i++){dir=src[i].path;dir=nd.path.normalize(dir);src[i].path=nd.path.resolve(cfg.base,dir);if(src[i].path.endsWith(".zip")){continue}ft=nd.fsUtils.getFileType(src[i].path);if(ft!=="d"){this._error("'rulePacks (entry "+(i+1)+"): path' is not a directory - \""+src[i].path+"\"");this._bErrors=true}}}if(cfg.typescript&&cfg.typescript.tsconfig){src=cfg.typescript.tsconfig;if(src&&typeof src==="string"){if(!nd.path.isAbsolute(src)){dir=nd.path.normalize(src);dir=nd.path.resolve(cfg.base,dir)}else{dir=src}if(!dir.endsWith(TSCONFIG)){dir=nd.path.join(dir,TSCONFIG)}cfg.typescript.tsconfig=dir}}if(this._bErrors){this._error(`Errors found in inherited config '${se.path}'`)}return!this._bErrors}_getAbsolutePath(fp){if(this._nd.path.isAbsolute(fp)){return fp}let p=this._nd.path.join(this._cfg.base,fp);if(!this._nd.path.isAbsolute(p)){p=this._nd.path.join(this._dir,p)}return p}_isCircular(fp){var ret;for(let i=0;i<this._stack.length;i++){if(this._stack[i].path===fp){ret=true;break}}return ret}_isMergeProp(p){return MERGEABLE_BY_DEFAULT[p]||this._extendOpts[p]===EXOPT_MERGE}_mergePropFiles(parSE,chSE){return this._mergePropFilesExclude(parSE,chSE,"files")}_mergePropExclude(parSE,chSE){return this._mergePropFilesExclude(parSE,chSE,"exclude")}_mergePropFilesExclude(parSE,chSE,prop){var parent,child,ch,i;var parent=parSE.cfg[prop];var child=chSE.cfg[prop];for(i=0;i<child.length;i++){ch=child[i];if(!parent.includes(ch)){parent.push(ch)}}return true}_mergePropOptions(parSE,chSE){return this._mergeObjects(parSE,chSE,"options")}_mergePropGroups(parSE,chSE){return this._mergeArrays(parSE,chSE,"groups")}_mergePropTokens(parSE,chSE){return this._mergeObjects(parSE,chSE,"tokens")}_mergePropNameSpaces(parSE,chSE){return this._mergeArrays(parSE,chSE,"nameSpaces")}_mergePropRuleMods(parSE,chSE){var parent,child,pname,parPack,rule,rval,prval,i;var parent=parSE.cfg.ruleMods;var child=chSE.cfg.ruleMods;for(pname in child){rval=child[pname];if(!parent[pname]){parent[pname]=rval;continue}if(pname==="enable"||pname==="disable"){prval=parent[pname];for(i=0;i<rval.length;i++){if(!prval.includes(rval[i])){prval.push(rval[i])}}continue}parPack=parent[pname];for(rule in rval){if(!parPack[rule]){parPack[rule]=rval[rule]}}}return true}_mergePropRuleNames(parSE,chSE){return this._mergeArrays(parSE,chSE,"ruleNames")}_mergePropRulePacks(parSE,chSE){var parent=parSE.cfg.rulePacks;var child=chSE.cfg.rulePacks;for(let i=0;i<child.length;i++){let ch=child[i];let b=false;for(let j=0;j<parent.length;j++){let par=parent[j];if(ch.path===par.path){b=true;break}}if(!b){parent.push(ch)}}return true}_mergePropMessages(parSE,chSE){var parent=parSE.cfg.messages;var child=chSE.cfg.messages;var parReject=parent.reject;var chReject=child.reject;if(!parReject&&chReject){parent.reject=chReject}else if(parReject&&chReject){parent.reject=_removeDupes(parReject.concat(chReject))}var parAccept=parent.accept;var chAccept=child.accept;if(!parAccept&&chAccept){parent.accept=chAccept}else if(parAccept&&chAccept){parent.accept=_removeDupes(parAccept.concat(chAccept))}return true}_mergePropComponents(parSE,chSE){return this._mergeArrays(parSE,chSE,"components")}_mergePropCompUrls(parSE,chSE){return this._mergeArrays(parSE,chSE,"componentUrls")}_mergePropTypescript(parSE,chSE){return this._mergeObjects(parSE,chSE,"typescript")}_mergeObjects(parSE,chSE,prop){var parent,child;parent=parSE.cfg[prop];child=chSE.cfg[prop];for(let prop in child){if(!parent.hasOwnProperty(prop)){parent[prop]=child[prop]}}return true}_mergeArrays(parSE,chSE,prop){var parent,child,isPS,isCS,isPA,isCA,val;parent=parSE.cfg[prop];child=chSE.cfg[prop];isPS=typeof parent==="string";isCS=typeof child==="string";if(isPS&&isCS&&parent===child){return}isPA=Array.isArray(parent);isCA=Array.isArray(child);parent=isPA?parent:[parent];child=isCA?child:[child];for(let i=0;i<child.length;i++){val=child[i];if(!parent.includes(val)){parent.push(val)}}return true}_emitErrorMsg(s,prop,path){var s=s||MSG.UNKNOWN;if(prop){s=s.replace(REPL_PROP,prop)}this._error(s.replace(REPL_PATH,path));this._isError=true}_parseError(msg){this._parseError=msg}_dumpStack(){this._msgCtx.info("[Info]: Config 'extends' stack","I",true);for(let i=0;i<this._stack.length;i++){this._msgCtx.info(`[Info]: ${this._stack[i].path}`,"I",true)}}}function _removeDupes(ar){return Array.isArray(ar)?ar.filter((val,x)=>ar.indexOf(val)===x):ar};module.exports=Extends;
|
|
6
|
+
const TSCONFIG="tsconfig.json";const PROFILE_DIR="profiles";const MERGEABLE_BY_DEFAULT={components:true,componentUrls:true,exclude:true,files:true,groups:true,message:true,nameSpaces:true,options:true,ruleMods:true,ruleNames:true,rulePacks:true,sevMap:true,typescript:true};const MERGEABLE_BY_OPTION={};const EXOPT_IGNORE="ignore";const EXOPT_MERGE="merge";const MSG={OBJ:"Config '%s' is not an object - %p",ARRAY:"Config '%s' is not an array - %p",STR:"Config '%s' is not a string - %p",STR_OR_AR_STR:"Config '%s' is not a string or an array of strings - %p",AR_OBJ:"Config '%s' is not an array of objects - %p",AR_STR:"Config '%s' is not an array of strings - %p",AR_STR_OBJ:"Config '%s' is not an array of strings or objects - %p",BOOL:"Config '%s' is not a boolean - %p",EXT_OPT:"Config 'extendOptions.%s' cannot be 'merge' - %p",EXT_OPT_VAL:"Config 'extendOptions.%s' not 'ignore' or 'merge' - %p",UNKNOWN:"Unknown config prop - '%s' - %p"};const REPL_PROP="%s";const REPL_PATH="%p";const DUMMY_FP="$_$";class Extends{constructor(configLib,configInst,cfg,path,nd,msgCtx,utils,fsUtils,isAMD){this._path=path;this._cfg=cfg;this._fp=cfg.base;this._nd=nd;this._msgCtx=msgCtx;this._utils=utils;this._fsUtils=fsUtils;this._cwd=nd.process.cwd();this._cfgLib=configLib;this._cfgInst=configInst;this._isAMD=isAMD;this._stack=[];this._extendOpts=null;this._profResult=null;this._error=msgCtx.error;this._info=msgCtx.info;this._isDebug=msgCtx.isDebug;this._isVerbose=msgCtx.isVerbose;this._mergeHandlers={components:this._mergePropComponents.bind(this),componentUrls:this._mergePropCompUrls.bind(this),exclude:this._mergePropExclude.bind(this),files:this._mergePropFiles.bind(this),groups:this._mergePropGroups.bind(this),messages:this._mergePropMessages,nameSpaces:this._mergePropNameSpaces.bind(this),options:this._mergePropOptions.bind(this),ruleMods:this._mergePropRuleMods.bind(this),ruleNames:this._mergePropRuleNames.bind(this),rulePacks:this._mergePropRulePacks,sevMap:this._mergePropSevMap.bind(this),typescript:this._mergePropTypescript.bind(this)}}extend(){if(!this._isDebug){this._isDebug=this._cfg.options&&this._cfg.options.debug}if(!this._isVerbose){this._isVerbose=this._cfg.options&&this._cfg.options.verbose}if(this._isDebug||this._isVerbose){this._msgCtx.info("[Info]: Merging configurations...","I",true)}if(!this._createStack()){return null}if(this._isDebug){this._dumpStack()}if(!this._isError){this._checkMergePropTypes();if(this._isError){return null}}if(!this._checkStackEnableDisableConflicts()||!this._checkUnsupportedProfileProps()||!this._checkProfileExtend()||!this._checkExtendOptionsProfile()||this._isError){return null}if(!this._stack.length){return this._cfg}return this._mergeStack()}_createStack(fp){var cfg,json,fp,first,stkEntry,profile;if(first=!fp){cfg=this._cfg;fp=this._isAMD?DUMMY_FP:this._path?this._path:this._fp}if(!fp){return true}if(this._utils.isObject(fp)){if(!(fp=this._resolveProfilePath(fp))){return false}if(fp.profile){profile=fp.profile}fp=fp.path}else if(!first&&typeof fp==="string"&&this._isAMD){this._error("Config cannot extend a non-profile config in AMD mode");return false}if(first){json=cfg}else if(this._isAMD){if(profile){if(json=this._nd.AmdProfLoader(profile)){json=this._parseJson(json)}if(!json){return false}}else{this._error("Config extends must contain a 'profile' propery in AMD mode");return false}fp=null}else{fp=this._getAbsolutePath(fp);if(!this._fsUtils.fileExists(fp)){let err=profile?`Configuration profile '${profile}' not found`:`Configuration file not found : ${fp}`;this._error(err);return false}if(this._isCircular(fp)){this._error(`Circular configuration 'extends' detected : ${fp}`);return false}try{if(!(json=this._readParseConfig(fp))){return false}}catch(e){this._error(`Error reading 'extends' config : ${fp}`);return false}}if(fp===DUMMY_FP){fp=null}stkEntry={path:fp,cfg:json};if(profile){stkEntry.profile=profile}this._stack.push(stkEntry);if(profile){if(!this._profResult){this._profResult={profiles:[profile]};if(json.ruleMods){if(json.ruleMods.enable){this._profResult.enable=json.ruleMods.enable}else{this._profResult.enable=[]}if(json.ruleMods.disable){this._profResult.disable=json.ruleMods.disable}else{this._profResult.disable=[]}}}else{this._profResult.profiles.push(profile)}}if(json.extends){if(!this._createStack(json.extends)){return false}}return true}_readParseConfig(fp){var json;json=this._nd.fs.readFileSync(fp,"utf8");json=this._nd.decomment(json);if(!(json=this._preprocessRawJson(json,fp))){return null}return this._parseJson(json,fp)}_parseJson(json,fp){var o;o=this._utils.parseJson(json,false);if(o.msg){let pos=`[${o.line}, ${o.col}]`;fp=fp?" : "+fp:"";this._error(`Config 'extends' error at ${pos} : ${o.msg}${fp}`);return null}return o.obj}_preprocessRawJson(txt,fp){var json=this._cfgInst.processIncludes(txt,fp);if(this._cfgInst.isOk()){json=this._cfgInst.processTokens(json);if(this._cfgInst.isOk()){}}return this._cfgInst.isOk()?json:null}_mergeStack(){if(!this._fixupPaths()){return null}for(let i=this._stack.length-1;i>0;i--){if(!this._mergePair(this._stack[i-1],this._stack[i])){return null}}if(this._isMergeProp("files")){if(this._stack[0].cfg.hasOwnProperty("files")){this._stack[0].cfg.files=_removeDupes(this._stack[0].cfg.files)}}if(this._isMergeProp("exclude")){if(this._stack[0].cfg.hasOwnProperty("exclude")){this._stack[0].cfg.exclude=_removeDupes(this._stack[0].cfg.exclude)}}if(this._stack[0].cfg.extends){delete this._stack[0].cfg.extends}return this._stack[0].cfg}_mergePair(parSE,chSE){var props,parent,child,merger,ret=true;parent=parSE.cfg;child=chSE.cfg;this._extendOpts=parSE.cfg.extendOptions||{};props=Object.keys(child);props.forEach(prop=>{if(prop.startsWith("_")||prop==="base"||prop==="extends"||prop==="tokens"||this._extendOpts[prop]===EXOPT_IGNORE){return}if(prop==="title"&&chSE.profile){return}if(!parent.hasOwnProperty(prop)){parent[prop]=child[prop];return}if(!this._isMergeProp(prop)){return}if(merger=this._mergeHandlers[prop]){if(!merger(parSE,chSE)){ret=false}}});if(!ret){return ret}if(!parSE.profile&&parSE.cfg.ruleNames){if(!this._checkRuleNamesProfileConflicts(parSE)){return false}}let type,what;if(chSE.profile){type="profile";what=chSE.profile}else{type="config";what=chSE.path}this._msgCtx.info(`[Info]: Inheriting ${type} '${what}'`,"I",true);return true}_checkMergePropTypes(){var cfg,se,prop,prop2,val;for(let i=0;i<this._stack.length;i++){se=this._stack[i];cfg=se.cfg;if(!this._cfgLib.checkPropNames(cfg,se.path)){this._isError=true}if(cfg.extendOptions){if(this._utils.isObject(cfg.extendOptions)){this._extendOpts=cfg.extendOptions;for(prop in this._extendOpts){val=this._extendOpts[prop];if(val===EXOPT_MERGE&&!MERGEABLE_BY_OPTION[prop]){this._emitErrorMsg(MSG.EXT_OPT,prop,se.path);return}else if(val!==EXOPT_MERGE&&val!==EXOPT_IGNORE){this._emitErrorMsg(MSG.EXT_OPT_VAL,prop,se.path);return}}}else{this._emitErrorMsg(MSG.OBJ,"extendOptions",se.path);return}}else{this._extendOpts={}}for(prop in cfg){if(!this._isMergeProp(prop)){continue}val=cfg[prop];if(prop==="components"||prop==="componentUrls"){if(typeof val!=="string"&&!Array.isArray(val)||!this._utils.isArrayContentsType(val,"string")){this._emitErrorMsg(MSG.STR_OR_AR_STR,prop,se.path)}}else if(prop==="files"){if(!Array.isArray(val)){this._emitErrorMsg(prop,prop,se.path)}if(!this._utils.isArrayContentsType(val,["string","object"])){this._emitErrorMsg(MSG.AR_STR_OBJ,prop,se.path)}}else if(prop==="exclude"){if(!Array.isArray(val)||!this._utils.isArrayContentsType(val,"string")){this._emitErrorMsg(MSG.STR_OR_AR_STR,prop,se.path)}}else if(prop==="groups"){if(!Array.isArray(val)){this._emitErrorMsg(MSG.STR,prop,se.path)}}else if(prop==="messages"){if(!this._utils.isObject(val)){this._emitErrorMsg(MSG.OBJ,prop,se.path)}if(se.messages.reject){if(!Array.isArray(se.messages.reject)){this._emitErrorMsg(MSG.OBJ,"messages.reject",se.path)}}if(se.messages.accept){if(!Array.isArray(se.messages.accept)){this._emitErrorMsg(MSG.OBJ,"messages.accept",se.path)}}}else if(prop==="nameSpaces"){if(!Array.isArray(val)){this._emitErrorMsg(MSG.AR_STR,prop,se.path)}}else if(prop==="options"){if(!this._utils.isObject(val)){this._emitErrorMsg(MSG.OBJ,prop,se.path)}}else if(prop==="ruleMods"){if(!this._utils.isObject(val)){this._emitErrorMsg(MSG.OBJ,prop,se.path);continue}for(prop2 in val){if(prop2==="enable"||prop2==="disable"){if(!Array.isArray(val[prop2])){this._emitErrorMsg(MSG.AR_OBJ,prop2==="enable"?"ruleMods.enable":"ruleMods.disable",se.path)}}else{if(!this._utils.isObject(val[prop2])){this._emitErrorMsg(MSG.AR_OBJ,prop+"."+prop2,se.path)}}}}else if(prop==="ruleNames"){if(!Array.isArray(val)||!this._utils.isArrayContentsType(val,"string")){this._emitErrorMsg(MSG.AR_STR,prop,se.path)}}else if(prop==="rulePacks"){if(!Array.isArray(val)||!this._utils.isArrayContentsType(val,"object")){this._emitErrorMsg(MSG.AR_OBJ,prop,se.path)}}else if(prop==="sevMap"){if(!this._utils.isObject(val)){this._emitErrorMsg(MSG.OBJ,prop,se.path)}if(val.sevMsg&&!this._utils.isObject(val.sevMsg)){this._emitErrorMsg(MSG.OBJ,prop+".sevMsg",se.path)}if(val.sevSet&&!this._utils.isObject(val.sevSet)){this._emitErrorMsg(MSG.OBJ,prop+".sevSet",se.path)}}else if(prop==="tokens"){if(!this._utils.isObject(val)){this._emitErrorMsg(MSG.OBJ,prop,se.path)}}else if(prop==="typescript"){if(!this._utils.isObject(val)){this._emitErrorMsg(MSG.OBJ,prop,se.path)}for(prop2 in val){if(prop2==="tsconfig"&&typeof val[prop2]!=="string"){this._emitErrorMsg(MSG.STR,"typescript.tsconfig",se.path)}if(prop2==="compile"&&typeof val[prop2]!=="boolean"){this._emitErrorMsg(MSG.BOOL,"typescript.compile",se.path)}}}else{this._error(`JAF ERROR: unhandled 'extends' property '${prop}' - ${se.path}`);this._isError=true}}}}_checkStackEnableDisableConflicts(){var config,i,b=true;for(i=this._stack.length-1;i>=0;i--){config=this._stack[i];if(!this._cfgLib.processRuleMods(config.cfg,config.profile?`profile '${config.profile}'`:config.path)){b=false}}if(!b){this._isError=true}return b}_checkRuleNamesProfileConflicts(parSE){var enable,rules,rule,i,profiles,isSet,b=true;if(!(this._profResult&&this._profResult.enable)){return true}rules=parSE.cfg.ruleNames;enable=this._profResult.enable;isSet=this._profResult.profiles.length>1;profiles=(isSet?"set [":"'")+this._profResult.profiles.join(", ")+(isSet?"]":"'");for(i=0;i<enable.length;i++){rule=enable[i];if(!rules.includes(rule)){this._msgCtx.error(`Config 'ruleNames' cannot disable rule '${rule}' enabled in profile ${profiles} - ${parSE.path}`);b=false}}if(!b){this._isError=true}return b}_checkUnsupportedProfileProps(){var se,config,i,b=true;var _self=this;function _emitUnsupProfileError(prof,prop){_self._msgCtx.error(`Property '${prop}' is not supported in profile ('${prof}')`);_self._isError=true;b=false}for(i=this._stack.length-1;i>=0;i--){se=this._stack[i];if(se.profile){config=se.cfg;if(config.ruleNames){_emitUnsupProfileError(se.profile,"ruleNames")}if(config.groups){_emitUnsupProfileError(se.profile,"groups")}}}return b}_checkProfileExtend(){var i;var stk=this._stack;for(i=0;i<stk.length;i++){if(!stk[i].profile){continue}for(i=i+1;i<stk.length;i++){if(!stk[i].profile){this._msgCtx.error(`Profile '${stk[i-1].profile}' cannot extend from a non-profile config - ${stk[i].path}`);return false}}break}return true}_checkExtendOptionsProfile(){if(this._profResult){let stk=this._stack;let opts;for(let i=0;i<stk.length;i++){if(opts=stk[i].cfg.extendOptions){if(opts.ruleMods==="ignore"){let isSet=this._profResult.profiles.length>1;let profiles=(isSet?"set [":"'")+this._profResult.profiles.join(", ")+(isSet?"]":"'");this._msgCtx.error(`Config cannot use 'extendsOptions.ruleMods' to ignore inherited 'ruleMods' from profile ${profiles} - ${stk[i].path}`);return false}}}}return true}_resolveProfilePath(o){var prof,ret;if(!(prof=o.profile)){this._error(`JAF ERROR: 'extends' declared as an object but property 'profile' is missing.`);this._isError=true;return null}ret={profile:o.profile};if(!this._isAMD){ret.path=this._nd.path.join(__dirname,"../"+PROFILE_DIR,prof)+".json"};return ret}_fixupPaths(){var se,ret=true;for(let i=this._stack.length-1;i>=0;i--){se=this._stack[i];if(!(this._cleanBase(se)&&this._fixupConfig(se))){ret=false;break}}return ret}_cleanBase(se){if(this._isAMD){return true}var src,ft;var nd=this._nd;src=se.cfg.base;if(src==="$jafcwd"){src=this._cwd}else{if(!src){src=this._nd.path.dirname(se.path)}src=nd.path.normalize(src);if(!nd.path.isAbsolute(src)){src=nd.path.join(nd.path.dirname(se.path),src)}ft=this._fsUtils.getFileType(src);if(ft!=="d"){this._msgCtx.error(`Config file 'base' is not a directory - '${src}' in ${se.path}`);return false}}se.cfg.base=src;this._info(`[Info]: Using config base '${src}' in ${se.path}`,"I");return true}_fixupConfig(se){var nd,cfg,src,dir,ft,i;nd=this._nd;cfg=se.cfg;if(cfg.files){if(!this._cfgLib.validateFileList(cfg.files)){this._bErrors=true;return}if(src=se.cfg.files){for(i=0;i<src.length;i++){if(!src[i].startsWith("http")){src[i]=nd.path.normalize(src[i]);src[i]=nd.path.resolve(cfg.base,src[i])}}}}if(cfg.exclude){if(!this._cfgLib.validateFileList(cfg.exclude)){this._bErrors=true;return}if(src=cfg.exclude){for(i=0;i<src.length;i++){src[i]=nd.path.normalize(src[i]);src[i]=nd.path.resolve(cfg.base,src[i])}}}src=cfg.components;if(src){for(i=0;i<src.length;i++){dir=nd.path.normalize(src[i]);dir=nd.path.resolve(cfg.base,dir);cfg.components[i]=dir}}src=cfg.outPath;if(src&&src!=="$noout"){src=nd.path.normalize(src);src=nd.path.resolve(cfg.base,src);cfg.outPath=src}src=cfg.rulePacks;if(src){for(i=0;i<src.length;i++){dir=src[i].path;dir=nd.path.normalize(dir);src[i].path=nd.path.resolve(cfg.base,dir);if(src[i].path.endsWith(".zip")){continue}ft=this._fsUtils.getFileType(src[i].path);if(ft!=="d"){this._error("'rulePacks (entry "+(i+1)+"): path' is not a directory - \""+src[i].path+"\"");this._bErrors=true}}}if(cfg.typescript&&cfg.typescript.tsconfig){src=cfg.typescript.tsconfig;if(src&&typeof src==="string"){if(!nd.path.isAbsolute(src)){dir=nd.path.normalize(src);dir=nd.path.resolve(cfg.base,dir)}else{dir=src}if(!dir.endsWith(TSCONFIG)){dir=nd.path.join(dir,TSCONFIG)}cfg.typescript.tsconfig=dir}}if(this._bErrors){this._error(`Errors found in inherited config '${se.path}'`)}return!this._bErrors}_getAbsolutePath(fp){if(this._nd.path.isAbsolute(fp)){return fp}let prevFp,prevBase,p;prevFp=this._stack[this._stack.length-1].path;prevFp=this._nd.path.dirname(prevFp);prevBase=this._stack[this._stack.length-1].cfg.base;if(prevBase){if(!this._nd.path.isAbsolute(prevBase)){p=this._nd.path.join(prevFp,prevBase,fp)}else{p=this._nd.path.join(prevBase,fp)}}else{p=this._nd.path.join(prevFp,fp)}if(!this._nd.path.isAbsolute(p)){p=this._nd.path.join(this._dir,p)}return p}_isCircular(fp){var ret;for(let i=0;i<this._stack.length;i++){if(this._stack[i].path===fp){ret=true;break}}return ret}_isMergeProp(p){return MERGEABLE_BY_DEFAULT[p]||this._extendOpts[p]===EXOPT_MERGE}_mergePropFiles(parSE,chSE){return this._mergePropFilesExclude(parSE,chSE,"files")}_mergePropExclude(parSE,chSE){return this._mergePropFilesExclude(parSE,chSE,"exclude")}_mergePropFilesExclude(parSE,chSE,prop){var parent,child,ch,i;var parent=parSE.cfg[prop];var child=chSE.cfg[prop];for(i=0;i<child.length;i++){ch=child[i];if(!parent.includes(ch)){parent.push(ch)}}return true}_mergePropOptions(parSE,chSE){return this._mergeObjects(parSE,chSE,"options")}_mergePropGroups(parSE,chSE){return this._mergeArrays(parSE,chSE,"groups")}_mergePropTokens(parSE,chSE){return this._mergeObjects(parSE,chSE,"tokens")}_mergePropNameSpaces(parSE,chSE){return this._mergeArrays(parSE,chSE,"nameSpaces")}_mergePropRuleMods(parSE,chSE){var pname,pack,parPack,rule,rval;var parent=parSE.cfg.ruleMods;var child=chSE.cfg.ruleMods;if(!this._mergeRuleModsEnableDisable(parSE,chSE)){return false}for(pname in child){if(pname==="enable"||pname==="disable"){continue}pack=child[pname];if(!parent[pname]){parent[pname]=pack;continue}this._mergeRuleModsPackObjects(parent[pname],pack)}parPack=parent[pname];for(rule in rval){if(!parPack[rule]){parPack[rule]=rval[rule]}}return true}_mergeRuleModsEnableDisable(parSE,chSE){var parent,child,val,x;var parEnable,parDisable,chEnable,chDisable;var parent=parSE.cfg.ruleMods;var child=chSE.cfg.ruleMods;parEnable=parent.enable;parDisable=parent.disable;chEnable=child.enable;chDisable=child.disable;var self=this;function _profVetoEnable(val){var ret=false;if(self._profResult&&self._profResult.disable){ret=self._profResult.disable.includes(val)}return ret}function _profVetoDisable(val){var ret=false;if(self._profResult&&self._profResult.enable){ret=self._profResult.enable.includes(val)}return ret}if(parEnable&&chDisable){for(val of parEnable){if(!(parSE.profile&&chSE.profile)){if(_profVetoEnable(val)){this._emitProfileVetoError(val,parSE.path,false);return false}}if((x=chDisable.indexOf(val))>=0){chDisable.splice(x,1)}}}if(parDisable&&chEnable){for(val of parDisable){if(!(parSE.profile&&chSE.profile)){if(_profVetoDisable(val)){this._emitProfileVetoError(val,parSE.path,true);return false}}if((x=chEnable.indexOf(val))>=0){chEnable.splice(x,1)}}}if(chEnable){if(!parEnable){parent.enable=parEnable=[]}for(val of chEnable){if(!parEnable.includes(val)){parEnable.push(val)}}}if(chDisable){if(!parDisable){parent.disable=parDisable=[]}for(val of chDisable){if(!parDisable.includes(val)){parDisable.push(val)}}}if(parSE.profile&&chSE.profile){if(!this._profResult){this._profResult={}}this._profResult.enable=parEnable;this._profResult.disable=parDisable;if(this._isDebug){console.log(`Profile merge: ${parSE.profile} <- ${chSE.profile}`)}}else{if(this._isDebug){console.log(`Merge: '${parSE.path}' <- '${chSE.profile?chSE.profile:chSE.path}'`)}}if(this._isDebug){console.log(`${parSE.path} <- ${chSE.path}`);console.log(`Enable = ${parEnable.join(",\n ")}`);console.log(`Disable = ${parDisable.join(",\n ")}\n`)}return true}_emitProfileVetoError(rule,cfgPath,disable){var profiles,temp,op1,op2;temp=[...this._profResult.profiles];temp.forEach((rule,i)=>{temp[i]="'"+rule+"'"});temp=temp.join(", ");if(disable){op1="disable";op2="enabled"}else{op1="enable";op2="disabled"}profiles="profile"+`${this._profResult.profiles.length>1?" set [":""} ${temp}${this._profResult.profiles.length>1?"]":""}`;cfgPath=cfgPath?`in ${cfgPath} `:"";this._error(`Config 'ruleMods' conflict: cannot ${op1} rule '${rule}' ${cfgPath}- ${op2} by ${profiles}`)}_mergePropRuleNames(parSE,chSE){return this._mergeArrays(parSE,chSE,"ruleNames")}_mergePropRulePacks(parSE,chSE){var parent=parSE.cfg.rulePacks;var child=chSE.cfg.rulePacks;for(let i=0;i<child.length;i++){let ch=child[i];let b=false;for(let j=0;j<parent.length;j++){let par=parent[j];if(ch.path===par.path){b=true;break}}if(!b){parent.push(ch)}}return true}_mergePropMessages(parSE,chSE){var parent=parSE.cfg.messages;var child=chSE.cfg.messages;var parReject=parent.reject;var chReject=child.reject;if(!parReject&&chReject){parent.reject=chReject}else if(parReject&&chReject){parent.reject=_removeDupes(parReject.concat(chReject))}var parAccept=parent.accept;var chAccept=child.accept;if(!parAccept&&chAccept){parent.accept=chAccept}else if(parAccept&&chAccept){parent.accept=_removeDupes(parAccept.concat(chAccept))}return true}_mergePropComponents(parSE,chSE){return this._mergeArrays(parSE,chSE,"components")}_mergePropCompUrls(parSE,chSE){return this._mergeArrays(parSE,chSE,"componentUrls")}_mergePropTypescript(parSE,chSE){return this._mergeObjects(parSE,chSE,"typescript")}_mergePropSevMap(parSE,chSE){var parent=parSE.cfg.sevMap;var child=chSE.cfg.sevMap;var parSevMsg,chSevMsg;var parSevSet,chSevSet;if(parent){parSevMsg=parent.sevMsg;parSevSet=parent.sevSet}if(child){chSevMsg=child.sevMsg;chSevSet=child.sevSet}if(parSevMsg&&chSevMsg){this._mergeObjects(parSE,chSE,"sevMap")}else if(!parSevMsg&&chSevMsg){parent.sevMsg=chSevMsg}if(parSevSet&&chSevSet){this._mergeObjects(parSE,chSE,"sevSet")}else if(!parSevSet&&chSevSet){parent.sevSet=chSevSet}if(parent.sevSet&&parent.sevMsg){let sev,msg,oldsev,val;for(val in parent.sevSet){sev=parent.sevSet[val];for(msg in parent.sevMsg){oldsev=parent.sevMsg[msg];if(val===oldsev){parent.sevMsg[msg]=sev}}}}return true}_mergeObjects(parSE,chSE,prop){var parent,child;parent=parSE.cfg[prop];child=chSE.cfg[prop];for(let prop in child){if(!parent.hasOwnProperty(prop)){parent[prop]=child[prop]}}return true}_mergeRuleModsPackObjects(to,from){var rule;for(rule in from){if(!to[rule]){to[rule]=from[rule]}}}_mergeArrays(parSE,chSE,prop){var parent,child,isPS,isCS,isPA,isCA,val;parent=parSE.cfg[prop];child=chSE.cfg[prop];isPS=typeof parent==="string";isCS=typeof child==="string";if(isPS&&isCS&&parent===child){return}isPA=Array.isArray(parent);isCA=Array.isArray(child);parent=isPA?parent:[parent];child=isCA?child:[child];for(let i=0;i<child.length;i++){val=child[i];if(!parent.includes(val)){parent.push(val)}}return true}_emitErrorMsg(s,prop,path){var s=s||MSG.UNKNOWN;if(prop){s=s.replace(REPL_PROP,prop)}this._error(s.replace(REPL_PATH,path));this._isError=true}_parseError(msg){this._parseError=msg}_dumpStack(){var type,msg;this._msgCtx.info("[Info]: -- Config 'extends' stack --","I",true);for(let i=0;i<this._stack.length;i++){type=this._stack[i].profile;type=type?type:"config ";msg=!this._isAMD?`${type} ${this._stack[i].path}`:`${type}`;this._msgCtx.info(`[Info]: ${msg}`,"I",true)}}}function _removeDupes(ar){return Array.isArray(ar)?ar.filter((val,x)=>ar.indexOf(val)===x):ar};module.exports=Extends;
|
package/lib/grouplist.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
|
|
6
|
+
function showBuiltinGroups(nd,arg,appCtx){var packs;if(packs=nd.builtinpacks.getPackMetadata(nd,appCtx)){let prefixes=nd.builtinpacks.getPrefixes();for(let pack of prefixes){if(!arg||arg===pack){_display(packs[pack],true,appCtx.colors)}}}};function showExternalGroups(packs,arg,nd,appCtx){var pack,isExternal;if(arg){arg=arg.toLowerCase()}for(pack of packs){if(!pack.builtin){if(!arg||arg===pack.prefix.toLowerCase()){_display(pack,appCtx.colors);isExternal=true}}}if(!isExternal){console.log(appCtx.colors.BRIGHTRED(" No external rule packs declared!"))}};function _display(pack,isBuiltin,clr){var rules,rule,opts,summary={},oos=[],dis=[],groups,group,msg;if(isBuiltin){_title(pack,clr);rules=pack.rules;for(rule in rules){opts=rules[rule];if(!(groups=opts.group)){continue};if(typeof groups==="string"){groups=[groups]}for(group of groups){if(!summary[group]){summary[group]=[]}summary[group].push(rule)}if(opts.hasOwnProperty("inservice")&&!opts.inservice){oos.push(rule)}else{if(opts.hasOwnProperty("enabled")&&!opts.enabled){dis.push(rule)}}}groups=Object.keys(summary);groups=groups.sort()}else{_title(pack,clr);if(pack.groupMap){summary=pack.groupMap;groups=Object.keys(pack.groupMap);groups=groups.sort()}}if(!groups){console.log(clr.BRIGHTYELLOW(`● No groups`));return}for(group of groups){console.log(clr.BRIGHTYELLOW(`● ${group}:`));rules=summary[group];for(rule of rules){msg=` ${rule}`;if(oos.includes(rule)){msg+=clr.RED(" (out of service)")}else if(dis.includes(rule)){msg+=clr.RED(" (disabled by default)")}console.log(msg)}}};function _title(pack,clr){console.log(`\n\n${clr.BRIGHTRED("\u25CF")} ${clr.CYAN("Pack")} ${clr.BRIGHTRED(`${pack.prefix}`)} ${clr.CYAN(" - Group Rule Membership")}`)};module.exports.showBuiltinGroups=showBuiltinGroups;module.exports.showExternalGroups=showExternalGroups;
|
package/lib/groups.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const _GROUPS={all:true,'jet-html':true,'jet-css':true,'jet-js':true,'jet-ts':true,'jet-tsx':true,'jet-json':true,'jet-md':true,'jet-aria':true,'jet-deprecated':true,'jet-deleted':true,'jet-override':true,'jet-cca':true,'jet-spoc':true,'jet-csp':true,'jet-demo':true,'jet-bp':true,'jet-perf':true,html5:true};module.exports.isGroup=g=>{return _GROUPS[g]};
|
|
6
|
+
const _GROUPS={all:true,'jet-html':true,'jet-css':true,'jet-js':true,'jet-ts':true,'jet-tsx':true,'jet-json':true,'jet-md':true,'jet-aria':true,'jet-deprecated':true,'jet-deleted':true,'jet-override':true,'jet-cca':true,'jet-spoc':true,'jet-csp':true,'jet-demo':true,'jet-bp':true,'jet-redwood-bp':true,'jet-perf':true,html5:true};module.exports.isGroup=g=>{return _GROUPS[g]};
|