@oracle/oraclejet-audit 17.0.6 → 17.1.1
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 +1 -1
- package/lib/Components.js +1 -1
- package/lib/ConfigEx.js +1 -1
- package/lib/HtmlUtils.js +1 -1
- package/lib/Registry.js +1 -1
- package/lib/RuleSet.js +1 -1
- package/lib/Rules.js +1 -1
- package/lib/TsxUtils.js +1 -1
- package/lib/checkage.js +1 -1
- package/lib/defaults.js +1 -1
- package/lib/manual.js +1 -1
- package/lib/migrator.js +1 -1
- package/lib/sublib/precomp/Precompiler.js +1 -1
- package/libext/expparser.js +1 -1
- package/meta/17.0.0/jetauditmeta.js +2 -2
- package/meta/17.1.0/jetauditmeta.js +9 -0
- package/meta/metaverlist.json +1 -1
- package/package.json +2 -2
- package/rules/jaf/jaf-sys-rule-disable.js +6 -0
- package/rules/jaf/jaf-sys-rule-opt.js +1 -1
- package/rules/jaf/jaf-sys-rule-pack-disable.js +6 -0
- package/rules/jaf/jaf-ts-loader.js +6 -0
- package/rules/jaf/msgid.json +1 -1
- package/rules/jaf/rules.json +1 -1
- package/rules/jet/helpers/vartrack.js +1 -1
- package/rules/jet/oj-acc-aria-prop.js +1 -1
- package/rules/jet/oj-acc-input-aria-label.js +1 -1
- package/rules/jet/oj-css-style-override.js +1 -1
- package/rules/jet/rules.json +1 -1
- package/schema/component-schema.json +1 -1
- package/src/JafCore.js +1 -1
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 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._warn=appCtx.warn;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._configLib=appCtx.configLib;this._plugin=appCtx.plugin;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;this._debugMode=appCtx.debugMode;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,warn:this._warn,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}if(typeObj=this._registry.getRegisteredCallbacks(ruleCtx.type)){let tsxType=ruleCtx.type;if(tsxType==="TsxWebComponent"||tsxType==="TsxElem"||tsxType.startsWith("Tsx<")||tsxType==="TsxJetComponent"||tsxType==="TsxStyle"||tsxType==="TsxEvent"){if(tsxType.includes("|")||tsxType.includes("=")||tsxType==="TsxEvent"||tsxType==="TsxStyle"){ruleCtx.type=arg1.type="TsxProperty"}else{ruleCtx.type=arg1.type="TsxComponent"}}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.getTsxRuleSynopsis=function(){return this._registry.getTsxRuleSynopsis()};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;if(this._debugMode){this._debug(`Firing rule '${ruleName}' ...`)}rule=this._getRuleByName(ruleName,ruleCtx._rsi);if(!rule){if(this._debugMode){this._debug(`'${ruleName}' rsi=${ruleCtx._rsi} instance could not be loaded`)}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.configLib=this._configLib;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;ruleCtx.utils.pluginLib=this._plugin.getPluginLib();this._curCtx=ruleCtx;try{if(callback){ruleCtx.rulePack._setCBCtx(ruleCtx);if((ctxType==="attr"||ctxType==="attrexpr"||ctxType==="attrexpr-$props"||ctxType==="event"||ctxType.indexOf("|")>0||ctxType==="class"||ctxType==="style"||ctxType==="stylemember"||ctxType.startsWith("<")&&ctxType.includes("="))&&typeof value!=="string"){if(ctxType==="style"||ctxType==="stylemember"){if(this._debugMode){this._debugRuleCall(ctxType,name,_extractStyles(value.val),value.rawval)}if(ctxType==="style"){callback(ruleCtx,name,_extractStyles(value.val),value.rawval)}else{callback(ruleCtx,name,value.val,value.rawval)}}else{if(this._debugMode){this._debugRuleCall(ctxType,name,value.val,value.rawVal)}callback(ruleCtx,name,value.val,value.rawval)}}else if(ctxType.startsWith("compjson")||ctxType==="comment"){if(this._debugMode){this._debugRuleCall(ctxType,value)}callback(ruleCtx,value)}else if(ruleCtx.type==="json"){if(this._debugMode){this._debugRuleCall(ctxType,value.ast)}callback(ruleCtx,value.ast)}else if(ctxType==="MemberExpression"||ctxType==="CallExpression"){if(this._debugMode){this._debugRuleCall(ctxType,name)}callback(ruleCtx,name)}else{if(this._debugMode){this._debugRuleCall(ctxType,name,value)}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._debugRuleCall=function(ctxType){let s="";for(let i=1;i<arguments.length;i++){s+=`${i>1?",":""} arg${i}=${arguments[i]}`}this._debug(` -> ${ctxType} ${s}`)};Rules.prototype.makeRuleContext=function(){return new RuleContext};Rules.prototype.isTypeRegistered=function(regType){return this._registry.isRegisteredCallback(regType)};Rules.prototype.isAnyTsxCompAttrRegistered=function(){return this._registry.isRegisteredAnyTsxCompAttr()};Rules.prototype.isAnyTsxAttrRegistered=function(){return this._registry.isRegisteredAnyTsxAttr()};Rules.prototype.isAnyTsxTypeRegistered=function(){return this._registry.isAnyTsxTypeRegistered()};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;if(!(typeObj=this._registry.getRegisteredCallbacks(ruleCtx.type))){return}ruleCtx.userDefs=this._config.userDefs;ruleCtx.utils.configLib=this._configLib;ruleCtx.utils.fsUtils=this._fsUtils;ruleCtx.utils.metaLib=this._metaLib;ruleCtx.utils.msgLib=this._message;ruleCtx.utils.semVerUtils=this._semVer;ruleCtx.utils.OjetLib=this._ojetLib;ruleCtx.utils.utils=this._utils;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];if(this._debugMode){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;
|
|
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._warn=appCtx.warn;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._configLib=appCtx.configLib;this._plugin=appCtx.plugin;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._curRuleName=null;this._Stats=appCtx.Stats;this._isUnitTest=appCtx.isUnitTest;this._debugMode=appCtx.debugMode;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,warn:this._warn,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}if(typeObj=this._registry.getRegisteredCallbacks(ruleCtx.type)){let tsxType=ruleCtx.type;if(tsxType==="TsxWebComponent"||tsxType==="TsxElem"||tsxType.startsWith("Tsx<")||tsxType==="TsxJetComponent"||tsxType==="TsxStyle"||tsxType==="TsxEvent"){if(tsxType.includes("|")||tsxType.includes("=")||tsxType==="TsxEvent"||tsxType==="TsxStyle"){ruleCtx.type=arg1.type="TsxProperty"}else{ruleCtx.type=arg1.type="TsxComponent"}}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.getTsxRuleSynopsis=function(){return this._registry.getTsxRuleSynopsis()};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;if(this._debugMode){this._debug(`Prepping rule '${ruleName}' ...`)}rule=this._getRuleByName(ruleName,ruleCtx._rsi);if(!rule){if(this._debugMode){this._debug(`'${ruleName}' rsi=${ruleCtx._rsi} instance could not be loaded`)}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.configLib=this._configLib;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;ruleCtx.utils.pluginLib=this._plugin.getPluginLib();this._curCtx=ruleCtx;try{if(callback){if(this._debugMode){this._debug(`Firing rule '${ruleName}' ...`)}this._curRuleName=ruleName;ruleCtx.rulePack._setCBCtx(ruleCtx);if((ctxType==="attr"||ctxType==="attrexpr"||ctxType==="attrexpr-$props"||ctxType==="event"||ctxType.indexOf("|")>0||ctxType==="class"||ctxType==="style"||ctxType==="stylemember"||ctxType.startsWith("<")&&ctxType.includes("="))&&typeof value!=="string"){if(ctxType==="style"||ctxType==="stylemember"){if(this._debugMode){this._debugRuleCall(ctxType,name,_extractStyles(value.val),value.rawval)}if(ctxType==="style"){callback(ruleCtx,name,_extractStyles(value.val),value.rawval)}else{callback(ruleCtx,name,value.val,value.rawval)}}else{if(this._debugMode){this._debugRuleCall(ctxType,name,value.val,value.rawVal)}callback(ruleCtx,name,value.val,value.rawval)}}else if(ctxType.startsWith("compjson")||ctxType==="comment"){if(this._debugMode){this._debugRuleCall(ctxType,value)}callback(ruleCtx,value)}else if(ruleCtx.type==="json"){if(this._debugMode){this._debugRuleCall(ctxType,value.ast)}callback(ruleCtx,value.ast)}else if(ctxType==="MemberExpression"||ctxType==="CallExpression"){if(this._debugMode){this._debugRuleCall(ctxType,name)}callback(ruleCtx,name)}else{if(this._debugMode){this._debugRuleCall(ctxType,name,value)}callback(ruleCtx,name,value)}if(this._debugMode){this._debug(`JAF <- '${ruleName}'`)}this._curRuleName=null;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){this._curRuleName=null;if(!e||!e.message){msg=`Unknown error - ${this._getFileSuffix(ruleCtx.filepath)} syntax issue?`}this._error("** running rule "+ruleName+(msg?` [${msg}] \n`:"")+` - file -> ${ruleCtx.filepath}`);if(e){this._error(`Stack trace:\n${e.stack}`)}}};Rules.prototype._debugRuleCall=function(ctxType){let s="";for(let i=1;i<arguments.length;i++){s+=`${i>1?",":""} arg${i}=${arguments[i]}`}this._debug(` -> '${ctxType}' ${s}`)};Rules.prototype.makeRuleContext=function(){return new RuleContext};Rules.prototype.isTypeRegistered=function(regType){return this._registry.isRegisteredCallback(regType)};Rules.prototype.isAnyTsxCompAttrRegistered=function(){return this._registry.isRegisteredAnyTsxCompAttr()};Rules.prototype.isAnyTsxAttrRegistered=function(){return this._registry.isRegisteredAnyTsxAttr()};Rules.prototype.isAnyTsxTypeRegistered=function(){return this._registry.isAnyTsxTypeRegistered()};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;if(!(typeObj=this._registry.getRegisteredCallbacks(ruleCtx.type))){return}ruleCtx.userDefs=this._config.userDefs;ruleCtx.utils.configLib=this._configLib;ruleCtx.utils.fsUtils=this._fsUtils;ruleCtx.utils.metaLib=this._metaLib;ruleCtx.utils.msgLib=this._message;ruleCtx.utils.semVerUtils=this._semVer;ruleCtx.utils.OjetLib=this._ojetLib;ruleCtx.utils.utils=this._utils;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];if(this._debugMode){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.getFiredRuleName=function(){return this._curRuleName};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/TsxUtils.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 TSX2_UTILS=require("./TsxUtils2");const HTML_UTILS=require("./HtmlUtils");const CB_END="end";const CB_NEXT_COMP="next-comp";const TSX_COMPONENT="TsxComponent";const TSX_PROPERTY="TsxProperty";const TEMPLATE="template";const OJ_DEFER="oj-defer";const OJ_BIND="oj-bind";const BODY="body";var TsxUtils=function(assert){this._fnAssert=assert;this._metaLib=null};TsxUtils.prototype.extractTsxProperties=function(ruleCtx,tsxRC,cb){this._onTsxRC(ruleCtx,tsxRC,cb)};TsxUtils.prototype.getProperty=function(tsxObj,propName){return this._extractProp(tsxObj,propName)};TsxUtils.prototype._extractProp=function(tsxObj,propName){var ret,ot;if(tsxObj&&(ot=tsxObj.type)){if(ot===TSX_PROPERTY){return tsxObj}if(ot===TSX_COMPONENT&&propName){let props,prop,i;if(props=tsxObj.properties){for(i=0;i<props.length;i++){prop=props[i];if(prop.name===propName){ret=prop;break}}}}}return ret};TsxUtils.prototype.getPropertyRawValue=function(tsxComp,name,stripDelims){var prop,ret;if(prop=this.getProperty(tsxComp,name)){ret=prop.valueRaw;if(stripDelims&&ret.charAt(0)==="\""){ret=ret.charAt(1)==="\""?ret="":ret.substring(1,ret.length-1)}}return typeof ret==="string"?ret:null};TsxUtils.prototype.getPropertyValue=function(tsxComp,propName){var tsxProp,ret,obj,i;var a=propName.split(".");var major=a[0];if(tsxProp=this.getProperty(tsxComp,major)){if(a.length===1){return tsxProp.node.value}if(!this.isPropertyPreactExpr(tsxProp)){return undefined}obj=tsxProp.node.value;for(i=1;i<a.length;i++){major=a.shift();if(!_isObject(obj)){break}if((obj=obj[major])&&_isObject(obj)){continue}break}}return ret};TsxUtils.prototype.getPropertyStringValue=function(tsxObj,propName){var tsxProp,value,ret;if(tsxProp=this._extractProp(tsxObj,propName)){value=tsxProp.node.value;if(value!==null){ret=value.type==="Literal"&&typeof value.value==="string"?value.value:null}}else{ret=null}return ret};TsxUtils.prototype.isPropertyPreactExpr=function(tsxObj,propName){var tsxProp,ret=false;if(tsxProp=this._extractProp(tsxObj,propName)){ret=tsxProp.node.value.type==="JSXExpressionContainer"}return ret};TsxUtils.prototype.isPropertyObjectExpr=function(tsxObj,propName){var tsxProp,ret=false;if(tsxProp=this._extractProp(tsxObj,propName)){if(tsxProp.node.value.type==="JSXExpressionContainer"){let expr=tsxProp.node.value.expression;ret=expr&&expr.type==="ObjectExpression"}}return ret};TsxUtils.prototype.isPropertyString=function(tsxObj,propName){var tsxProp,ret=false;if(tsxProp=this._extractProp(tsxObj,propName)){ret=tsxProp.node.value.type==="Literal"&&typeof tsxProp.node.value.value==="string"}return ret};TsxUtils.prototype.getAncestor=function(tsxComp,name){var o,ret;name=name||tsxComp.name;while(o=tsxComp.parent){if(o.name===name){ret=o;break}tsxComp=o}return ret||null};TsxUtils.prototype.getChildren=function(tsxComp){return tsxComp.children};TsxUtils.prototype.getDescendant=function(tsxComp,name){var childs,child,ret,i;while(childs=tsxComp.children){for(i=0;i<childs.length;i++){child=childs[i];if(child.name===name){ret=child;break}if(ret=this.getDescendant(child,name)){break}}break}return ret||null};TsxUtils.prototype.getDirectDescendant=function(tsxComp,name){var childs,child,ret,i;if(childs=tsxComp.children){for(i=0;i<childs.length;i++){child=childs[i];if(child.name===name){ret=child;break}}}return ret||null};TsxUtils.prototype.isExpressionObject=function(tsxObj,propName){var tsxProp,ret;if(tsxProp=this._extractProp(tsxObj,propName)){if(tsxProp.node.value.type==="JSXExpressionContainer"){let expr=tsxProp.node.value.expression;ret=expr.type==="ObjectExpression"}}return!!ret};TsxUtils.prototype.getExpressionObject=function(tsxObj,propName){var tsxProp,obj;if(tsxProp=this._extractProp(tsxObj,propName)){if(!tsxProp.node.value){return null}if(tsxProp.node.value.type!=="JSXExpressionContainer"){return null}let expr=tsxProp.node.value.expression;if(expr.type==="ObjectExpression"){let props,stack;props=expr.properties;obj={};stack=[];props.forEach(prop=>{_doProp(prop,obj,stack,this._fnAssert)})}}return obj||null};TsxUtils.prototype.toCamelCase=function(str){return TSX2_UTILS.toCamelCase(str)};TsxUtils.prototype.toKebabCase=function(str){return TSX2_UTILS.toKebabCase(str)};function _doProp(prop,obj,stack,fnAssert){let key,elems,propx;if(prop.type==="Property"&&(prop.key.type==="Identifier"||prop.key.type==="Literal")){if(prop.key.type==="Identifier"){key=prop.key.name}else{key=prop.key.value}
|
|
6
|
+
const TSX2_UTILS=require("./TsxUtils2");const HTML_UTILS=require("./HtmlUtils");const CB_END="end";const CB_NEXT_COMP="next-comp";const TSX_COMPONENT="TsxComponent";const TSX_PROPERTY="TsxProperty";const TEMPLATE="template";const OJ_DEFER="oj-defer";const OJ_BIND="oj-bind";const BODY="body";var TsxUtils=function(assert){this._fnAssert=assert;this._metaLib=null};TsxUtils.prototype.extractTsxProperties=function(ruleCtx,tsxRC,cb){this._onTsxRC(ruleCtx,tsxRC,cb)};TsxUtils.prototype.getProperty=function(tsxObj,propName){return this._extractProp(tsxObj,propName)};TsxUtils.prototype._extractProp=function(tsxObj,propName){var ret,ot;if(tsxObj&&(ot=tsxObj.type)){if(ot===TSX_PROPERTY){return tsxObj}if(ot===TSX_COMPONENT&&propName){let props,prop,i;if(props=tsxObj.properties){for(i=0;i<props.length;i++){prop=props[i];if(prop.name===propName){ret=prop;break}}}}}return ret};TsxUtils.prototype.getPropertyRawValue=function(tsxComp,name,stripDelims){var prop,ret;if(prop=this.getProperty(tsxComp,name)){ret=prop.valueRaw;if(stripDelims&&ret.charAt(0)==="\""){ret=ret.charAt(1)==="\""?ret="":ret.substring(1,ret.length-1)}}return typeof ret==="string"?ret:null};TsxUtils.prototype.getPropertyValue=function(tsxComp,propName){var tsxProp,ret,obj,i;var a=propName.split(".");var major=a[0];if(tsxProp=this.getProperty(tsxComp,major)){if(a.length===1){return tsxProp.node.value}if(!this.isPropertyPreactExpr(tsxProp)){return undefined}obj=tsxProp.node.value;for(i=1;i<a.length;i++){major=a.shift();if(!_isObject(obj)){break}if((obj=obj[major])&&_isObject(obj)){continue}break}}return ret};TsxUtils.prototype.getPropertyStringValue=function(tsxObj,propName){var tsxProp,value,ret;if(tsxProp=this._extractProp(tsxObj,propName)){value=tsxProp.node.value;if(value!==null){ret=value.type==="Literal"&&typeof value.value==="string"?value.value:null}}else{ret=null}return ret};TsxUtils.prototype.isPropertyPreactExpr=function(tsxObj,propName){var tsxProp,ret=false;if(tsxProp=this._extractProp(tsxObj,propName)){ret=tsxProp.node.value.type==="JSXExpressionContainer"}return ret};TsxUtils.prototype.isPropertyObjectExpr=function(tsxObj,propName){var tsxProp,ret=false;if(tsxProp=this._extractProp(tsxObj,propName)){if(tsxProp.node.value.type==="JSXExpressionContainer"){let expr=tsxProp.node.value.expression;ret=expr&&expr.type==="ObjectExpression"}}return ret};TsxUtils.prototype.isPropertyString=function(tsxObj,propName){var tsxProp,ret=false;if(tsxProp=this._extractProp(tsxObj,propName)){ret=tsxProp.node.value.type==="Literal"&&typeof tsxProp.node.value.value==="string"}return ret};TsxUtils.prototype.getAncestor=function(tsxComp,name){var o,ret;name=name||tsxComp.name;while(o=tsxComp.parent){if(o.name===name){ret=o;break}tsxComp=o}return ret||null};TsxUtils.prototype.getChildren=function(tsxComp){return tsxComp.children};TsxUtils.prototype.getDescendant=function(tsxComp,name){var childs,child,ret,i;while(childs=tsxComp.children){for(i=0;i<childs.length;i++){child=childs[i];if(child.name===name){ret=child;break}if(ret=this.getDescendant(child,name)){break}}break}return ret||null};TsxUtils.prototype.getDirectDescendant=function(tsxComp,name){var childs,child,ret,i;if(childs=tsxComp.children){for(i=0;i<childs.length;i++){child=childs[i];if(child.name===name){ret=child;break}}}return ret||null};TsxUtils.prototype.isExpressionObject=function(tsxObj,propName){var tsxProp,ret;if(tsxProp=this._extractProp(tsxObj,propName)){if(tsxProp.node.value.type==="JSXExpressionContainer"){let expr=tsxProp.node.value.expression;ret=expr.type==="ObjectExpression"}}return!!ret};TsxUtils.prototype.getExpressionObject=function(tsxObj,propName){var tsxProp,obj;if(tsxProp=this._extractProp(tsxObj,propName)){if(!tsxProp.node.value){return null}if(tsxProp.node.value.type!=="JSXExpressionContainer"){return null}let expr=tsxProp.node.value.expression;if(expr.type==="ObjectExpression"){let props,stack;props=expr.properties;obj={};stack=[];props.forEach(prop=>{_doProp(prop,obj,stack,this._fnAssert)})}}return obj||null};TsxUtils.prototype.toCamelCase=function(str){return TSX2_UTILS.toCamelCase(str)};TsxUtils.prototype.toKebabCase=function(str){return TSX2_UTILS.toKebabCase(str)};function _doProp(prop,obj,stack,fnAssert){let key,elems,propx,pvType;if(prop.type==="Property"&&(prop.key.type==="Identifier"||prop.key.type==="Literal")){if(prop.key.type==="Identifier"){key=prop.key.name}else{key=prop.key.value}pvType=prop.value.type;if(pvType==="Literal"){obj[key]=prop.value.value}else if(pvType==="Identifier"){obj[key]=prop.value.name}else if(pvType==="ArrayExpression"){obj[key]=[];elems=prop.value.elements;elems.forEach(elem=>{if(elem.type==="Literal"){obj[key].push(elem.value)}else if(elem.type==="ObjectExpression"){elem.properties.forEach(prop=>{stack.push(obj);obj={};propx=_doProp(prop,obj,stack,fnAssert);obj=stack.pop();obj[key].push(propx)})}})}else if(prop.value.type==="FunctionExpression"){obj[key]=prop.value.body.body}else if(pvType==="ObjectExpression"){let o,p,i,objProps=prop.value.properties;stack.push(obj);obj[key]=o={};obj=o;for(i=0;i<objProps.length;i++){p=objProps[i];if(p.key.type==="Identifier"){if(p.value.type==="Literal"){o[p.key.name]=p.value.value}else if(p.value.type==="ObjectExpression"){_doProp(p,obj,stack,fnAssert);obj=stack.pop()}else if(p.value.type==="Identifier"){o[p.key.name]=p.value.name}else if(p.value.type==="ArrowFunctionExpression"){o[p.key.name]=p.value}else{fnAssert(`TsxUtils._doProp file line=${prop?.loc.start.line} ${p.value.type}`)}}}}else if(pvType==="MemberExpression"){obj[key]=prop.value}else if(pvType==="TemplateLiteral"){obj[key]=null}else if(pvType==="LogicalExpression"){obj[key]=prop.value}else if(pvType==="CallExpression"){obj[key]=prop.value}else if(pvType==="AssignmentPattern"){fnAssert(`TsxUtils._doProp2 unhandled prop key '${key}' value type '${pvType}', file line=${prop?.loc.start.line}`);obj[key]="?"}else{fnAssert(`TsxUtils._doProp3 unhandled prop key '${key}' value type '${pvType}', file line=${prop?.loc.start.line}`);obj[key]="?"}}return obj};TsxUtils.prototype.setIssuePosition=function(issue,obj){if(obj.type===TSX_COMPONENT||obj.type===TSX_PROPERTY){let loc=obj.loc;issue.setPosition(loc.start.line,loc.start.column,obj.range[0],obj.range[1])}else{issue.setPosition(0,0,0,0)}};TsxUtils.prototype.setIssuePropValuePosition=function(issue,tsxProp){if(tsxProp.type==="TsxProperty"){let loc=tsxProp.node.value.loc;issue.setPosition(loc.start.line,loc.start.column,tsxProp.node.value.range[0],tsxProp.node.value.range[1])}else{issue.setPosition(0,0,0,0)}};TsxUtils.prototype.getRawtext=function(ruleCtx,tsxRC){return ruleCtx&&tsxRC&&tsxRC.range?ruleCtx.data.substring(tsxRC.range[0],tsxRC.range[1]):""};TsxUtils.prototype._onTsxRC=function(ruleCtx,tsxRC,cb){var comps,tsxComp,ret,i;if(!(comps=tsxRC.components)){return}for(i=0;i<comps.length;i++){tsxComp=comps[i];ret=this._checkComp(ruleCtx,tsxComp,cb);if(ret===CB_END){break}};cb(ruleCtx,null)};TsxUtils.prototype._checkComp=function(ruleCtx,tsxComp,cb){var props;if(props=tsxComp.properties){let prop,ret,i;for(i=0;i<props.length;i++){prop=props[i];ret=cb(ruleCtx,prop);if(ret===CB_END||ret===CB_NEXT_COMP){return ret}};}if(tsxComp.children){tsxComp.children.forEach(child=>{this._checkComp(ruleCtx,child,cb)})}};TsxUtils.prototype.getSlotParent=function(ruleCtx,tsxProp,slotName){var parent,isOjDefer=false,ret=null;parent=tsxProp.parent;if(!(parent=parent.parent)){return}isOjDefer=parent.name==="oj-defer";if(parent&&parent.name){if(parent.name!==BODY){if(ruleCtx.utils.metaLib.isTagSlotName(parent.name,slotName)){ret=parent}if(!ret){if(isOjDefer&&parent.name===TEMPLATE||parent.name==="oj-switcher"){ret=parent}else if(parent.name===TEMPLATE||parent.name.startsWith(OJ_BIND)||parent.name===OJ_DEFER){ret=_continueUpwards(ruleCtx,parent,slotName)}}}}return ret};TsxUtils.prototype.isChildOfElem=function(elemName,tsxComp){var ret=null;while(tsxComp.parent){if(tsxComp.parent.name===elemName){ret=tsxComp.parent;break}tsxComp=tsxComp.parent}return ret};function _continueUpwards(ruleCtx,tsxComp,slotName){var ret=null,parent,tagName;while(parent=tsxComp.parent){tagName=parent.name;if(tagName===TEMPLATE||tagName.startsWith(OJ_BIND)||tagName===OJ_DEFER){tsxComp=parent;continue}if(parent.name!==BODY){if(ruleCtx.utils.metaLib.isTagSlotName(tagName,slotName)){ret=parent}}break}return ret};function _isObject(value){return typeof value==="object"&&!Array.isArray(value)};TsxUtils.prototype.setMetaLib=function(metaLib){this._metaLib=metaLib};TsxUtils.prototype.isCommonElem=function(elem){return HTML_UTILS.isCommonElem(elem)};TsxUtils.prototype.isCommonAttr=function(attrName){return TSX2_UTILS.isCommonProp(attrName)||this.isAriaAttr(attrName)};TsxUtils.prototype.isCommonEventAttr=function(attrName){return TSX2_UTILS.isCommonEventProp(attrName)};TsxUtils.prototype.isHtml5ObsoleteElem=function(tag){return HTML_UTILS.isHtml5ObsoleteElem(tag)};TsxUtils.prototype.isAriaAttr=function(attr){return HTML_UTILS.isAriaAttr(attr)};TsxUtils.prototype.isSelfClosingTag=function(tag){return HTML_UTILS.isSelfClosingTag(tag)};TsxUtils.prototype.isSvgElem=function(elem){return HTML_UTILS.isSvgElem(elem)};module.exports=TsxUtils;
|
package/lib/checkage.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 BUILT="2024-11-
|
|
6
|
+
const BUILT="2024-11-22T16:22:29.207Z";const MAJOR_RELS=2;function CheckAge(burnedInJetVer,msgCtx){this._jetRels=-1;this._msgCtx=msgCtx;this._burnedInMajor=parseInt(burnedInJetVer.split(".")[0])};CheckAge.prototype.checkAge=function(){var curDate;var buildDate;var buildMonth;var monthsToNow;curDate=new Date;buildDate=BUILT==="@BUILT@"?curDate:new Date(BUILT);buildMonth=buildDate.getMonth()+1;monthsToNow=_getElapsedMonths(buildDate,curDate);if(!monthsToNow){this._jetRels=0}else{this._jetRels=_getReleases(buildMonth,monthsToNow);if(this._jetRels>MAJOR_RELS){this._emitMsg(monthsToNow)}}return this._jetRels};CheckAge.prototype.getJafReleaseCount=function(){return this._jetRels};CheckAge.prototype.getMajorReleaseCount=function(major){if(typeof major==="string"){let a=major.split(".");major=parseInt(a[0])}if(isNaN(major)){return this._jetRels}let estimatedMajor=this._burnedInMajor+this._jetRels;return estimatedMajor-major};CheckAge.prototype._emitMsg=function(old){var INDENT=" ".repeat(12);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} month${old===1?"":"s"} 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,"JAF-9100",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/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:"17.
|
|
6
|
+
const defaults={JETVER:"17.1.1".replace(/(\d*\.\d*)(\.\d*)+$/g,"$1")+".0",THEME:"Alta",ECMAVER:14};module.exports=defaults;
|
package/lib/manual.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 PREFIX;var RP_PREFIX;const RULES_JSON="rules.json";const MSGID_JSON="msgid.json";const JS=".js";const RE_WS=/^\s*$/;const RE_MARKUP=/<[^>]*>/g;const RE_MULTI_BLANKS=/\s{2,}/g;const EMPTY="";const LINELEN=100;const LIST_INDENT=2;var _path;var _rDir;var _rpDir;var _isMsgId;var _prefix;var _msgNum;var _rawArg;var _sev;var _multiIDs=[];function showBuiltinMsgHelp(nd,arg,wantManPage,appCtx){var rc;_init(nd,appCtx);rc=_initArg(arg,wantManPage,appCtx);return rc>0?_processBuiltin(nd,appCtx):rc===0};function showExternalMsgHelp(rules,manCheckL,manCheckS,nd,appCtx){var check,temp,isShort,o,x,ret=false;_init(nd,appCtx);check=manCheckL||manCheckS;if(check){temp=check.toLowerCase();x=temp.indexOf("-");check=x>=0?temp.substring(0,x):"";check=check.toUpperCase()+temp.substring(x);isShort=!!manCheckS;if(rules.getRSIByRuleName(temp)>=0){o=rules.getRuleDescriptionEx(null,temp,isShort)}else{o=rules.getRuleDescriptionEx(check,null,isShort)}if(o&&o.descrip){_display(o,appCtx.colors)}else{appCtx.error(`Unable to locate '${temp}' via the configuration file.`)}ret=true}return ret};function _processBuiltin(nd,appCtx){var meta;_rDir=_path.join(__dirname,"../rules");_rpDir=_path.join(__dirname,"../rulepacks");if(!(meta=_loadRuleMetadata(nd,appCtx))){return true}return _isMsgId?_processMsgId(meta,nd,appCtx):_processRuleName(meta,nd,appCtx)};function _processMsgId(meta,nd,appCtx){var mjson=meta.mjson;var rname,r,x;for(r in mjson){if(_msgNum===mjson[r]){rname=r;break}}if(!rname){appCtx.error(`No rule found for message ID ${_prefix}-${_msgNum}.`);return true}x=rname.indexOf("_");if(x>=0){rname=rname.substring(0,x)}return _displayIt(rname,_prefix,meta,nd,appCtx)};function _processRuleName(meta,nd,appCtx){var rname,rjson,r;rname=_rawArg.toLowerCase();rjson=meta.rjson.rules;for(r in rjson){if(r===rname){return _displayIt(rname,_prefix,meta,nd,appCtx)}}appCtx.error(`Rule ${rname} is not a known rule.`);return!rname.startsWith("oj-")};function _displayIt(rname,prefix,meta,nd,appCtx){var rule,r,mjson,rjson,prefix;mjson=meta.mjson;for(r in mjson){if(r.startsWith(rname)){_multiIDs.push(mjson[r])}}rjson=meta.rjson;for(r in rjson.rules){if(r===rname){_sev=rjson.rules[r].severity;break}}_sev=_sev||"unknown";if(rule=_loadRule(rname,meta,nd,appCtx)){let o={descrip:rule.getDescription(),rule:rname,prefix:prefix,sev:_sev,idList:_multiIDs};_display(o,appCtx.colors);return true}return false};function _loadRule(rname,meta,nd,appCtx){var rule,ruleJS,fp;try{fp=nd.path.join(meta.rdir,rname+JS);ruleJS=nd.ruleLoader(fp);if(ruleJS.prototype||!ruleJS.getName){try{rule=new ruleJS}catch(e){appCtx.error(`Failed to instantiate rule ${rname}`)}}else{rule=ruleJS}return rule}catch(e){appCtx.error(`Failed to load rule ${rname}`)}};function _loadRuleMetadata(nd,appCtx){var meta,fp;fp=RP_PREFIX.includes(_prefix)?nd.path.join(_rpDir,_prefix):nd.path.join(_rDir,_prefix);meta=_loadRulesJson(fp,nd,appCtx);return meta};function _loadRulesJson(dir,nd,appCtx){var rjson,mjson,fp;fp=nd.path.join(dir,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 false}fp=nd.path.join(dir,MSGID_JSON);if(appCtx.fsUtils.fileExists(fp)){mjson=nd.jsonLoader.load(fp,nd,m=>{appCtx.error(m)},true,appCtx.utils)}else{if(!RP_PREFIX.includes(_prefix)){appCtx.error(`Internal error: rule message ID manifest for ${_prefix} not found`);return false}}if(rjson){return{rjson:rjson,mjson:mjson,rdir:dir}}};function _init(nd){_path=nd.path;PREFIX=nd.builtinpacks.getPrefixes();RP_PREFIX=nd.builtinpacks.getRulepackFolderPrefixes()};function _initArg(arg,wantManPage,appCtx){var x,mp;_rawArg=arg;arg=arg.toLowerCase();if(mp=_isManPage(arg)){_displayManPage(mp.full,mp.short,appCtx.colors);return 0}if(wantManPage){appCtx.error(`manPage for command ${arg} not found`);return 0}x=arg.indexOf("-");if(x<0){if(!isNaN(parseInt(arg))){arg="jet-"+arg;x=3}else{appCtx.error("Expected a message ID or rulename or manpage to follow --help");return 0}}_prefix=arg.substring(0,x);_msgNum=arg.substring(x+1);x=parseInt(_msgNum);_isMsgId=!isNaN(x);if(_isMsgId){if(_msgNum.length<4){_msgNum="0".repeat(4-_msgNum.length)+_msgNum}}else{_msgNum=null;if(arg.startsWith("oj-")){_prefix="jet"}}if(PREFIX.includes(_prefix)){return 1}return-1};function _isManPage(manPage){var syn;switch(manPage){case"amdlist":case"amd":manPage="amdlist";syn="amd";break;case"base":case"b":manPage="base";syn="b";break;case"betalist":case"bl":manPage="betalist";syn="bl";break;case"config":case"c":manPage="config";syn="c";break;case"dac":syn="dac";break;case"debug":case"d":manPage="debug";syn="d";break;case"deflist":case"def":manPage="deflist";syn="def";break;case"dislist":case"dl":manPage="dislist";syn="dl";break;case"deplist":case"dpl":manPage="deplist";syn="dpl";break;case"dryrun":case"dr":manPage="dryrun";syn="dr";break;case"extra":case"e":manPage="extra";syn="e";break;case"followlinks":case"fl":manPage="followlinks";syn="fl";break;case"format":case"t":manPage="format";syn="t";break;case"groups":case"g":manPage="groups";syn="g";break;case"grouplist":case"gl":manPage="grouplist";syn="gl";break;case"help":case"h":manPage="help";syn="h";break;case"init":case"i":manPage="init";syn="i";break;case"initrule":case"ir":manPage="initrule";syn="ir";break;case"jetlist":case"jl":manPage="jetlist";syn="jl";break;case"jetver":case"jv":manPage="jetver";syn="jv";break;case"loadorder":case"rlo":manPage="loadorder";syn="rlo";break;case"maintenence":case"mnt":manPage="maintenance";syn="mnt";break;case"metahist":case"mh":manPage="metahist";syn="mh";break;case"migrator":case"mig":manPage="migrator";syn="mig";break;case"msgid":case"id":manPage="msgid";syn="id";break;case"nslist":case"nsl":manPage="nslist";syn="nsl";break;case"nocolor":case"nc":manPage="nocolor";syn="nc";break;case"nodebug":case"nd":manPage="nodebug";syn="nd";break;case"noextra":case"ne":manPage="noextra";syn="ne";break;case"nofollowlinks":case"nfl":manPage="nofollowlinks";syn="nfl";break;case"noout":case"no":manPage="noout";syn="no";break;case"noverbose":case"nv":manPage="noverbose";syn="nv";break;case"outpath":case"o":manPage="outPath";syn="o";break;case"profiles":case"prof":manPage="profiles";syn="prof";break;case"reg":syn="reg";break;case"retcode":case"rc":manPage="retcode";syn="rc";break;case"rules":case"r":manPage="rules";syn="r";break;case"rulesjson":case"rj":manPage="rulesjson";syn="rj";break;case"rulessonar":case"rs":manPage="rulessonar";syn="rs";break;case"severity":case"s":manPage="severity";syn="s";break;case"version":case"v":manPage="version";syn="v";break;case"xgrouplist":case"xgl":manPage="xgrouplist";syn="xgl";break}return syn?{full:manPage,short:syn}:syn};var first;function _display(o,clr){var lines,line,s,s1,s2,s3;var liEnd,x;var list,temp,indent;var idList=o.idList.filter((c,index)=>{return o.idList.indexOf(c)===index});var multiSev=idList.length>1;s=clr.BRIGHTGREEN("Rule: ");s1=clr.BRIGHTGREEN("Severity: ");s2=clr.BRIGHTGREEN("Message ID");s3=clr.BRIGHTYELLOW("\xB9");line="\n"+s+clr.BRIGHTYELLOW(o.rule)+" "+s1+clr.BRIGHTYELLOW(o.sev)+(multiSev?s3:EMPTY)+" "+s2+(multiSev?"'s":EMPTY)+": "+o.prefix+"-"+idList.join(", ");console.log(line);s=_removeMarkup(o.descrip,clr);s=_removeColorMarkup(s,clr);indent=0;lines=s.split("\n");for(let i=0;i<lines.length;i++){line=lines[i];if((x=line.indexOf("-"))>=3&&!isNaN(parseInt(line.charAt(x+1)))){line=clr.BRIGHTYELLOW(line)}if(line.charAt(0)==="\x12"){list=true;temp=line.indexOf("/",1);indent=parseInt(line.substring(1,temp));line=line.substring(temp+1).trim();first=true}liEnd=false;if(list&&(x=line.indexOf("\x13"))>=0){line=line.substring(0,x);liEnd=true}_displayLine(line,list,indent,clr);if(liEnd){list=false;indent=0}}if(multiSev){s="\n"+s3+clr.BRIGHTYELLOW(" Possibility of more than 1 severity since there are "+idList.length+" message ID's");console.log(s)}console.log("")};function _displayLine(s,list,indent,clr){var line,c,x;var start=0;var end=LINELEN;while(end<s.length){x=_NL(s,start,end);if(x>=0){line=s.substring(start,x).trim();if(list){if(line.indexOf("\x13")>=0){indent=0}}line=_fixup(line);console.log((list?" ".repeat((first?0:indent)+LIST_INDENT):"")+clr.CYAN(line));first=false;start=x+1;end=start+LINELEN;continue}c=s.charAt(end);if(RE_WS.test(c)){line=s.substring(start,end).trim();line=_fixup(line);console.log((list?" ".repeat((first?0:indent)+LIST_INDENT):"")+clr.CYAN(line));first=false;start=end;end+=LINELEN;continue}else{end--}}if(start<end){line=s.substring(start,end).trim();line=_fixup(line);console.log((list?" ".repeat((first?0:indent)+LIST_INDENT):"")+clr.CYAN(line));first=false}};function _removeMarkup(s,clr){s=s.replace(/<oj\-/g,"@@01").replace(/<\/oj\-/g,"@@02").replace(/<link>/g,"@@20").replace(/<script>/g,"@@21").replace(/<html>/g,"@@22").replace(/<\/link>/g,"@@30").replace(/<\/script>/g,"@@31").replace(/<\/html>/g,"@@32").replace(/<br>/g,"@@03").replace(/<p>/g,"@@03@@03").replace(/<b>/g,"@@04").replace(/<em>/g,"@@04").replace(/<i>/g,"@@05").replace(/<\/b>/g,"@@06").replace(/<\/em>/g,"@@06").replace(/<\/i>/g,"@@06").replace(/<div/g,"@@7").replace(/<\/div>/g,"@@8").replace(/<template>/g,"@@9").replace(/<\/template>/g,"@@10").replace(/<ol/g,"@@11").replace(/<\/ol>/g,"@@12").replace(/<ul/g,"@@13").replace(/<\/ul>/g,"@@14").replace(/<li/g,"@@15").replace(/<\/li>/g,"@@16").replace(/ /g,"\x11").replace(RE_MARKUP,EMPTY).replace(RE_MULTI_BLANKS," ").trimRight().replace(/@@01/g,"<oj-").replace(/@@02/g,"</oj-").replace(/@@03/g,"\n").replace(/</g,"<").replace(/>/g,">").replace(/@@9/g,"<template>").replace(/@@10/g,"</template>").replace(/@@7/g,"<div").replace(/@@8/g,"</div>").replace(/@@11/g,"<ol").replace(/@@12/g,"</ol>").replace(/@@13/g,"<ul").replace(/@@14/g,"</ul>").replace(/@@15/g,"<li").replace(/@@16/g,"</li>").replace(/@@20/g,"<link>").replace(/@@21/g,"<script>").replace(/@@22/g,"<html>").replace(/@@30/g,"</link>").replace(/@@31/g,"</script>").replace(/@@32/g,"</html>");if(!clr.isColor()){s=s.replace(/@@4/g,EMPTY).replace(/@@5/g,EMPTY).replace(/@@6/g,EMPTY)}return _handleLists(s)};function _removeColorMarkup(s,clr){if(clr.isColor()){s=s.replace(/@@04/g,EMPTY).replace(/@@05/g,EMPTY).replace(/@@06/g,EMPTY)}return s.trim()};function _handleLists(s){var start,end,ordered,rep,x;x=0;while(true){ordered=false;if((start=s.indexOf("<ol>",x))>=0){ordered=true}else{start=s.indexOf("<ul>",x)}if(start>=0){end=ordered?s.indexOf("</ol>",start):s.indexOf("</ul>",start);if(end>=start){rep=_handleList(s,start,end,ordered);s=s.substring(0,start)+rep;x=s.length;s+=s.substring(end+4)}else{x=start+4}}else{break}}return s};function _handleList(s,start,end,ordered){var list,itemStart,itemEnd,count=0,sCount,rep="";list=s.substring(start+4,end).trim();itemEnd=0;while(true){if((itemStart=list.indexOf("<li>",itemEnd))>=0){itemEnd=list.indexOf("</li>",itemStart);sCount=(ordered?""+ ++count+")":"*")+" ";rep+="\n\n"+"\x12"+sCount.length+"/"+sCount+list.substring(itemStart+4,itemEnd).trimRight()+"\x13"}else{break}}return rep}function _displayManPage(manPage,syn,clr){let lib=require("./manpage");return lib.show(manPage,syn,clr)};function _fixup(s){return s.replace(/\x11/g," ")};function _NL(s,start,end){var ret=-1,x;if(start<end){if((x=s.indexOf("\n",start))>=0){if(x<end){ret=x}}}return ret};module.exports={showBuiltinMsgHelp,showExternalMsgHelp};
|
|
6
|
+
var PREFIX;var RP_PREFIX;const RULES_JSON="rules.json";const MSGID_JSON="msgid.json";const JS=".js";const RE_WS=/^\s*$/;const RE_MARKUP=/<[^>]*>/g;const RE_MULTI_BLANKS=/\s{2,}/g;const EMPTY="";const LINELEN=100;const LIST_INDENT=2;var _path;var _rDir;var _rpDir;var _isMsgId;var _prefix;var _msgNum;var _rawArg;var _sev;var _multiIDs=[];function showBuiltinMsgHelp(nd,arg,wantManPage,appCtx){var rc;_init(nd,appCtx);rc=_initArg(arg,wantManPage,appCtx);return rc>0?_processBuiltin(nd,appCtx):rc===0};function showExternalMsgHelp(rules,manCheckL,manCheckS,nd,appCtx){var check,temp,isShort,o,x,ret=false;_init(nd,appCtx);check=manCheckL||manCheckS;if(check){temp=check.toLowerCase();x=temp.indexOf("-");check=x>=0?temp.substring(0,x):"";check=check.toUpperCase()+temp.substring(x);isShort=!!manCheckS;if(rules.getRSIByRuleName(temp)>=0){o=rules.getRuleDescriptionEx(null,temp,isShort)}else{o=rules.getRuleDescriptionEx(check,null,isShort)}if(o&&o.descrip){_display(o,appCtx.colors)}else{appCtx.error(`Unable to locate '${temp}' via the configuration file.`)}ret=true}return ret};function _processBuiltin(nd,appCtx){var meta;_rDir=_path.join(__dirname,"../rules");_rpDir=_path.join(__dirname,"../rulepacks");if(!(meta=_loadRuleMetadata(nd,appCtx))){return true}return _isMsgId?_processMsgId(meta,nd,appCtx):_processRuleName(meta,nd,appCtx)};function _processMsgId(meta,nd,appCtx){var mjson=meta.mjson;var rname,r,x;for(r in mjson){if(_msgNum===mjson[r]){rname=r;break}}if(!rname){appCtx.error(`No rule found for message ID ${_prefix}-${_msgNum}.`);return true}x=rname.indexOf("_");if(x>=0){rname=rname.substring(0,x)}return _displayIt(rname,_prefix,meta,nd,appCtx)};function _processRuleName(meta,nd,appCtx){var rname,rjson,r;rname=_rawArg.toLowerCase();rjson=meta.rjson.rules;for(r in rjson){if(r===rname){return _displayIt(rname,_prefix,meta,nd,appCtx)}}appCtx.error(`Rule ${rname} is not a known rule.`);return!rname.startsWith("oj-")};function _displayIt(rname,prefix,meta,nd,appCtx){var rule,r,mjson,rjson,prefix;mjson=meta.mjson;for(r in mjson){if(r.startsWith(rname)){_multiIDs.push(mjson[r])}}rjson=meta.rjson;for(r in rjson.rules){if(r===rname){_sev=rjson.rules[r].severity;break}}_sev=_sev||"unknown";if(rule=_loadRule(rname,meta,nd,appCtx)){let o={descrip:rule.getDescription(),rule:rname,prefix:prefix,sev:_sev,idList:_multiIDs};_display(o,appCtx.colors);return true}return false};function _loadRule(rname,meta,nd,appCtx){var rule,ruleJS,fp;try{fp=nd.path.join(meta.rdir,rname+JS);ruleJS=nd.ruleLoader(fp);if(ruleJS.prototype||!ruleJS.getName){try{rule=new ruleJS}catch(e){appCtx.error(`Failed to instantiate rule ${rname}`)}}else{rule=ruleJS}return rule}catch(e){appCtx.error(`Failed to load rule ${rname}`)}};function _loadRuleMetadata(nd,appCtx){var meta,fp;fp=RP_PREFIX.includes(_prefix)?nd.path.join(_rpDir,_prefix):nd.path.join(_rDir,_prefix);meta=_loadRulesJson(fp,nd,appCtx);return meta};function _loadRulesJson(dir,nd,appCtx){var rjson,mjson,fp;fp=nd.path.join(dir,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 false}fp=nd.path.join(dir,MSGID_JSON);if(appCtx.fsUtils.fileExists(fp)){mjson=nd.jsonLoader.load(fp,nd,m=>{appCtx.error(m)},true,appCtx.utils)}else{if(!RP_PREFIX.includes(_prefix)){appCtx.error(`Internal error: rule message ID manifest for ${_prefix} not found`);return false}}if(rjson){return{rjson:rjson,mjson:mjson,rdir:dir}}};function _init(nd){_path=nd.path;PREFIX=nd.builtinpacks.getPrefixes();RP_PREFIX=nd.builtinpacks.getRulepackFolderPrefixes()};function _initArg(arg,wantManPage,appCtx){var x,mp;_rawArg=arg;arg=arg.toLowerCase();if(mp=_isManPage(arg)){_displayManPage(mp.full,mp.short,appCtx.colors);return 0}if(wantManPage){appCtx.error(`manPage for command ${arg} not found`);return 0}x=arg.indexOf("-");if(x<0){if(!isNaN(parseInt(arg))){arg="jet-"+arg;x=3}else{appCtx.error("Expected a message ID or rulename or manpage to follow --help");return 0}}_prefix=arg.substring(0,x);_msgNum=arg.substring(x+1);x=parseInt(_msgNum);_isMsgId=!isNaN(x);if(_isMsgId){if(_msgNum.length<4){_msgNum="0".repeat(4-_msgNum.length)+_msgNum}}else{_msgNum=null;if(arg.startsWith("oj-")){_prefix="jet"}}if(PREFIX.includes(_prefix)){return 1}return-1};function _isManPage(manPage){var syn;switch(manPage){case"amdlist":case"amd":manPage="amdlist";syn="amd";break;case"base":case"b":manPage="base";syn="b";break;case"betalist":case"bl":manPage="betalist";syn="bl";break;case"config":case"c":manPage="config";syn="c";break;case"dac":syn="dac";break;case"debug":case"d":manPage="debug";syn="d";break;case"deflist":case"def":manPage="deflist";syn="def";break;case"dislist":case"dl":manPage="dislist";syn="dl";break;case"deplist":case"dpl":manPage="deplist";syn="dpl";break;case"dryrun":case"dr":manPage="dryrun";syn="dr";break;case"extra":case"e":manPage="extra";syn="e";break;case"followlinks":case"fl":manPage="followlinks";syn="fl";break;case"format":case"t":manPage="format";syn="t";break;case"groups":case"g":manPage="groups";syn="g";break;case"grouplist":case"gl":manPage="grouplist";syn="gl";break;case"help":case"h":manPage="help";syn="h";break;case"init":case"i":manPage="init";syn="i";break;case"initrule":case"ir":manPage="initrule";syn="ir";break;case"jetlist":case"jl":manPage="jetlist";syn="jl";break;case"jetver":case"jv":manPage="jetver";syn="jv";break;case"loadorder":case"rlo":manPage="loadorder";syn="rlo";break;case"maintenence":case"mnt":manPage="maintenance";syn="mnt";break;case"metahist":case"mh":manPage="metahist";syn="mh";break;case"migrator":case"mig":manPage="migrator";syn="mig";break;case"msgid":case"id":manPage="msgid";syn="id";break;case"nslist":case"nsl":manPage="nslist";syn="nsl";break;case"nocolor":case"nc":manPage="nocolor";syn="nc";break;case"nodebug":case"nd":manPage="nodebug";syn="nd";break;case"noextra":case"ne":manPage="noextra";syn="ne";break;case"nofollowlinks":case"nfl":manPage="nofollowlinks";syn="nfl";break;case"noout":case"no":manPage="noout";syn="no";break;case"noverbose":case"nv":manPage="noverbose";syn="nv";break;case"outpath":case"o":manPage="outPath";syn="o";break;case"profiles":case"prof":manPage="profiles";syn="prof";break;case"reg":syn="reg";break;case"retcode":case"rc":manPage="retcode";syn="rc";break;case"rules":case"r":manPage="rules";syn="r";break;case"rulesjson":case"rj":manPage="rulesjson";syn="rj";break;case"rulessonar":case"rs":manPage="rulessonar";syn="rs";break;case"severity":case"s":manPage="severity";syn="s";break;case"version":case"v":manPage="version";syn="v";break;case"xgrouplist":case"xgl":manPage="xgrouplist";syn="xgl";break}return syn?{full:manPage,short:syn}:syn};var first;function _display(o,clr){var lines,line,s,s1,s2,s3;var liEnd,x;var list,temp,indent;var idList=o.idList.filter((c,index)=>{return o.idList.indexOf(c)===index});var multiSev=idList.length>1;s=clr.BRIGHTGREEN("Rule: ");s1=clr.BRIGHTGREEN("Severity: ");s2=clr.BRIGHTGREEN("Message ID");s3=clr.BRIGHTYELLOW("\xB9");line="\n"+s+clr.BRIGHTYELLOW(o.rule)+" "+s1+clr.BRIGHTYELLOW(o.sev)+(multiSev?s3:EMPTY)+" "+s2+(multiSev?"'s":EMPTY)+": "+o.prefix+"-"+idList.join(", ");console.log(line);s=_removeMarkup(o.descrip,clr);s=_removeColorMarkup(s,clr);indent=0;lines=s.split("\n");for(let i=0;i<lines.length;i++){line=lines[i];if((x=line.indexOf("-"))>=3&&!isNaN(parseInt(line.charAt(x+1)))){line=clr.BRIGHTYELLOW(line)}if((x=line.indexOf("JAF#"))>=0&&!isNaN(parseInt(line.charAt(x+4)))){line=line.substring(0,x+3)+"-"+line.substring(x+4)}if(line.charAt(0)==="\x12"){list=true;temp=line.indexOf("/",1);indent=parseInt(line.substring(1,temp));line=line.substring(temp+1).trim();first=true}liEnd=false;if(list&&(x=line.indexOf("\x13"))>=0){line=line.substring(0,x);liEnd=true}_displayLine(line,list,indent,clr);if(liEnd){list=false;indent=0}}if(multiSev){s="\n"+s3+clr.BRIGHTYELLOW(" Possibility of more than 1 severity since there are "+idList.length+" message ID's");console.log(s)}console.log("")};function _displayLine(s,list,indent,clr){var line,c,x;var start=0;var end=LINELEN;while(end<s.length){x=_NL(s,start,end);if(x>=0){line=s.substring(start,x).trim();if(list){if(line.indexOf("\x13")>=0){indent=0}}line=_fixup(line);console.log((list?" ".repeat((first?0:indent)+LIST_INDENT):"")+clr.CYAN(line));first=false;start=x+1;end=start+LINELEN;continue}c=s.charAt(end);if(RE_WS.test(c)){line=s.substring(start,end).trim();line=_fixup(line);console.log((list?" ".repeat((first?0:indent)+LIST_INDENT):"")+clr.CYAN(line));first=false;start=end;end+=LINELEN;continue}else{end--}}if(start<end){line=s.substring(start,end).trim();line=_fixup(line);console.log((list?" ".repeat((first?0:indent)+LIST_INDENT):"")+clr.CYAN(line));first=false}};function _removeMarkup(s,clr){s=s.replace(/<oj\-/g,"@@01").replace(/<\/oj\-/g,"@@02").replace(/<link>/g,"@@20").replace(/<script>/g,"@@21").replace(/<html>/g,"@@22").replace(/<\/link>/g,"@@30").replace(/<\/script>/g,"@@31").replace(/<\/html>/g,"@@32").replace(/<br>/g,"@@03").replace(/<p>/g,"@@03@@03").replace(/<b>/g,"@@04").replace(/<em>/g,"@@04").replace(/<i>/g,"@@05").replace(/<\/b>/g,"@@06").replace(/<\/em>/g,"@@06").replace(/<\/i>/g,"@@06").replace(/<div/g,"@@7").replace(/<\/div>/g,"@@8").replace(/<template>/g,"@@9").replace(/<\/template>/g,"@@10").replace(/<ol/g,"@@11").replace(/<\/ol>/g,"@@12").replace(/<ul/g,"@@13").replace(/<\/ul>/g,"@@14").replace(/<li/g,"@@15").replace(/<\/li>/g,"@@16").replace(/ /g,"\x11").replace(RE_MARKUP,EMPTY).replace(RE_MULTI_BLANKS," ").trimRight().replace(/@@01/g,"<oj-").replace(/@@02/g,"</oj-").replace(/@@03/g,"\n").replace(/</g,"<").replace(/>/g,">").replace(/@@9/g,"<template>").replace(/@@10/g,"</template>").replace(/@@7/g,"<div").replace(/@@8/g,"</div>").replace(/@@11/g,"<ol").replace(/@@12/g,"</ol>").replace(/@@13/g,"<ul").replace(/@@14/g,"</ul>").replace(/@@15/g,"<li").replace(/@@16/g,"</li>").replace(/@@20/g,"<link>").replace(/@@21/g,"<script>").replace(/@@22/g,"<html>").replace(/@@30/g,"</link>").replace(/@@31/g,"</script>").replace(/@@32/g,"</html>");if(!clr.isColor()){s=s.replace(/@@4/g,EMPTY).replace(/@@5/g,EMPTY).replace(/@@6/g,EMPTY)}return _handleLists(s)};function _removeColorMarkup(s,clr){if(clr.isColor()){s=s.replace(/@@04/g,EMPTY).replace(/@@05/g,EMPTY).replace(/@@06/g,EMPTY)}return s.trim()};function _handleLists(s){var start,end,ordered,rep,x;x=0;while(true){ordered=false;if((start=s.indexOf("<ol>",x))>=0){ordered=true}else{start=s.indexOf("<ul>",x)}if(start>=0){end=ordered?s.indexOf("</ol>",start):s.indexOf("</ul>",start);if(end>=start){rep=_handleList(s,start,end,ordered);s=s.substring(0,start)+rep;x=s.length;s+=s.substring(end+4)}else{x=start+4}}else{break}}return s};function _handleList(s,start,end,ordered){var list,itemStart,itemEnd,count=0,sCount,rep="";list=s.substring(start+4,end).trim();itemEnd=0;while(true){if((itemStart=list.indexOf("<li>",itemEnd))>=0){itemEnd=list.indexOf("</li>",itemStart);sCount=(ordered?""+ ++count+")":"*")+" ";rep+="\n\n"+"\x12"+sCount.length+"/"+sCount+list.substring(itemStart+4,itemEnd).trimRight()+"\x13"}else{break}}return rep}function _displayManPage(manPage,syn,clr){let lib=require("./manpage");return lib.show(manPage,syn,clr)};function _fixup(s){return s.replace(/\x11/g," ")};function _NL(s,start,end){var ret=-1,x;if(start<end){if((x=s.indexOf("\n",start))>=0){if(x<end){ret=x}}}return ret};module.exports={showBuiltinMsgHelp,showExternalMsgHelp};
|
package/lib/migrator.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
|
-
function run(cwd,rtf,appCtx,fnOpenWriter,JafVersion,fnShowVersion){var mig,isVerboseDebug=rtf.verboseMode||rtf.debugMode;var ctx;appCtx.debug("Loading migrator entry-point...");try{if(rtf.outPath){if(!fnOpenWriter(rtf.outPath)){return}}ctx=_makeContext(rtf,appCtx,JafVersion,cwd);mig=new(require("../corePackMigrator/cli"))(ctx)}catch(e){let s="[JAF-
|
|
6
|
+
function run(cwd,rtf,appCtx,fnOpenWriter,JafVersion,fnShowVersion){var mig,isVerboseDebug=rtf.verboseMode||rtf.debugMode;var ctx;appCtx.debug("Loading migrator entry-point...");try{if(rtf.outPath){if(!fnOpenWriter(rtf.outPath)){return}}ctx=_makeContext(rtf,appCtx,JafVersion,cwd);mig=new(require("../corePackMigrator/cli"))(ctx)}catch(e){let s="[JAF-9104]: Error loading Migrator support.";if(isVerboseDebug){s+=`\n{e.message}`}appCtx.msg(appCtx.colors.RED(s))}if(!mig){return}appCtx.debug("Checking entry-points...");let isError;if(!mig.run){_missingEntry("run",appCtx);isError=true}if(rtf.unitTest&&!mig.test){_missingEntry("test",appCtx);isError=true}if(!mig.getVersion){}if(isError){return}_displayOptions(ctx,appCtx);if(rtf.help){let migVer;if(mig.getVersion){migVer=mig.getVersion()}migVer?appCtx.console(migVer,"I"):fnShowVersion();return}appCtx.debug("Invoking migrator...");try{return mig.run()}catch(e){let s,x,i;s=e.stack;if((x=s.indexOf("migrator.js"))>=0){for(i=x;;i--){if(s.charAt(i)==="\n"){s=s.substring(0,i);break}}}appCtx.error(appCtx.colors.RED(`[JAF-9102]: Migrator run failure.\n${s}`))}return 0};function _makeContext(rtf,appCtx,JafVersion,cwd){return{jafVersion:JafVersion,jetVersion:rtf.jetverSet?rtf.jetverSet:appCtx.defaultJetVer,configPath:rtf.configPath||null,cwd:cwd,logPath:rtf.outPath,log:{error:appCtx.error,warn:appCtx.warn,info:appCtx.info,msg:appCtx.msg,console:appCtx.console,debug:appCtx.debug},options:{verboseMode:rtf.verboseMode,debugMode:rtf.debugMode,dryRunMode:rtf.dryRunSet,colorMode:appCtx.colors.isColor(),unitTest:!!rtf.unitTest},runMode:appCtx.runMode,platform:appCtx.platform,utils:{utils:appCtx.utils,fsUtils:appCtx.fsUtils,color:appCtx.colors}}};function _displayOptions(ctx,appCtx){if(ctx.options.debugMode){appCtx.debug("Migrator options:");appCtx.debug(` jafVersion: ${ctx.jafVersion}`);appCtx.debug(` jetVersion: ${ctx.jetVersion}`);appCtx.debug(` configPath: ${ctx.configPath}`);appCtx.debug(` runMode: ${ctx.options.runMode}`);appCtx.debug(` debugMode: ${ctx.options.debugMode}`);appCtx.debug(` verboseMode: ${ctx.options.verboseMode}`);appCtx.debug(` dryRunMode: ${ctx.options.dryRunMode}`);appCtx.debug(` colorMode: ${ctx.options.colorMode}`);appCtx.debug(` logPath: ${ctx.logPath}`);appCtx.debug(` unitTest: ${ctx.options.unitTest}`)}else{appCtx.info(`Migrator log -> ${ctx.logPath}\n`)}};function _missingEntry(method,appCtx){appCtx.error(appCtx.colors.RED(`[JAF-9102]: Internal error - Migrator support method ${method}() not exported.`))};module.exports={run};
|
|
@@ -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 JAF_TEMP="jaf";const WORKING_ROOT_FOLDER="ts-temp";const TSCONFIG_JSON="tsconfig.json";var path;const PreCompiler=function(utils,jafUtils,fsUtils,msgCtx,semVer,nd){this._utils=utils;this._jafUtils=jafUtils;this._fsUtils=fsUtils;this._semVer=semVer;this._error=msgCtx.error;this._info=msgCtx.info;this._msg=msgCtx.msg;this._debug=msgCtx.debug;this._jafMsg=msgCtx.jafMsg;this._isDebug=msgCtx.isDebug;this._isVerbose=msgCtx.isVerbose;this._isVerboseOrDebug=this._isVerbose||this._isDebug;path=nd.path;this._workingRootFolder=this._utils.toJAFPath(path.join(nd.os.tmpdir(),JAF_TEMP,WORKING_ROOT_FOLDER));this._runOnce=false;this._vfiles=null};PreCompiler.prototype.getPrecompileCache=function(auditBase,tsSource,componentRootFolder){if(!this.runOnce){this._runOnce=true;this._precompileCache=this._transformVComponents(path.join(auditBase,TSCONFIG_JSON),auditBase,tsSource,componentRootFolder)}return this._precompileCache};PreCompiler.prototype.getVFiles=function(){return this._vfiles};PreCompiler.prototype._transformVComponents=function(tsConfigPath,auditBase,sourceBase,componentBase){const normalizedTsConfigPath=this._fsUtils.toJAFPath(tsConfigPath);if(!this._fsUtils.fileExistsSync(normalizedTsConfigPath)){if(this._isVerboseOrDebug){this._info(`Typescript configuration file '${tsConfigPath}' not found, pre-compilation will be skipped`)}return}const outputFolder=this._fsUtils.getUniqueFileNameSync("_XXXXXX");const compiledOutputFolder=this._utils.toJAFPath(`${this._workingRootFolder}/js${outputFolder}`);const compiledJSONFolder=this._utils.toJAFPath(`${this._workingRootFolder}/json${outputFolder}`);const allTsConfig=this._fsUtils.readJsonSync(tsConfigPath,true,error=>this._error(`Typescript configuration file ${tsConfigPath} cannot be read, unable to process VComponents.\nError: ${error}`));if(!allTsConfig){return}if(this._isVerboseOrDebug){this._msg(
|
|
6
|
+
const JAF_TEMP="jaf";const WORKING_ROOT_FOLDER="ts-temp";const TSCONFIG_JSON="tsconfig.json";const VCOMP_MSG_PREFIX="VComponent Processing:";var path;const PreCompiler=function(utils,jafUtils,fsUtils,msgCtx,semVer,nd){this._utils=utils;this._jafUtils=jafUtils;this._fsUtils=fsUtils;this._semVer=semVer;this._error=msgCtx.error;this._info=msgCtx.info;this._msg=msgCtx.msg;this._debug=msgCtx.debug;this._jafMsg=msgCtx.jafMsg;this._isDebug=msgCtx.isDebug;this._isVerbose=msgCtx.isVerbose;this._isVerboseOrDebug=this._isVerbose||this._isDebug;path=nd.path;this._workingRootFolder=this._utils.toJAFPath(path.join(nd.os.tmpdir(),JAF_TEMP,WORKING_ROOT_FOLDER));this._runOnce=false;this._vfiles=null};PreCompiler.prototype.getPrecompileCache=function(auditBase,tsSource,componentRootFolder){if(!this.runOnce){this._runOnce=true;this._precompileCache=this._transformVComponents(path.join(auditBase,TSCONFIG_JSON),auditBase,tsSource,componentRootFolder)}return this._precompileCache};PreCompiler.prototype.getVFiles=function(){return this._vfiles};PreCompiler.prototype._transformVComponents=function(tsConfigPath,auditBase,sourceBase,componentBase){const normalizedTsConfigPath=this._fsUtils.toJAFPath(tsConfigPath);if(!this._fsUtils.fileExistsSync(normalizedTsConfigPath)){if(this._isVerboseOrDebug){this._info(`Typescript configuration file '${tsConfigPath}' not found, pre-compilation will be skipped`)}return}const outputFolder=this._fsUtils.getUniqueFileNameSync("_XXXXXX");const compiledOutputFolder=this._utils.toJAFPath(`${this._workingRootFolder}/js${outputFolder}`);const compiledJSONFolder=this._utils.toJAFPath(`${this._workingRootFolder}/json${outputFolder}`);const allTsConfig=this._fsUtils.readJsonSync(tsConfigPath,true,error=>this._error(`Typescript configuration file ${tsConfigPath} cannot be read, unable to process VComponents.\nError: ${error}`));if(!allTsConfig){return}if(this._isDebug){this._debug(`TypeScript Config ->\n${JSON.stringify(allTsConfig,null,3)}`)}if(this._isVerboseOrDebug){this._msg(`${VCOMP_MSG_PREFIX} Compiling project...`)}if(this._isDebug){this._debug("...transforming to full paths")}allTsConfig.compilerOptions.paths[`${componentBase}/*`]=[`${auditBase}/${sourceBase}/${componentBase}/*`];const sourceBaseRoot=sourceBase.includes("/")?sourceBase.split("/")[0]:sourceBase;Object.entries(allTsConfig.compilerOptions.paths).forEach(([pathKey,pathValues])=>{if(this._isDebug){this._debug(`pathKey -> ${pathKey} pathValues -> ${pathValues}`)};const remapped=pathValues.map(mappedPath=>{return this._remapPath(mappedPath,sourceBaseRoot,auditBase)});allTsConfig.compilerOptions.paths[pathKey]=remapped});if(allTsConfig.compilerOptions.hasOwnProperty("typeRoots")){allTsConfig.compilerOptions.typeRoots=allTsConfig.compilerOptions.typeRoots.map(typeroot=>this._remapPath(typeroot,sourceBaseRoot,auditBase))}if(allTsConfig.compilerOptions.hasOwnProperty("types")){allTsConfig.compilerOptions.types=allTsConfig.compilerOptions.types.map(type=>this._remapPath(type,sourceBaseRoot,auditBase))}allTsConfig.compilerOptions.rootDir=auditBase;allTsConfig.compilerOptions.outDir=compiledOutputFolder;if(!this._fsUtils.pathExistsSync(this._workingRootFolder)){this._fsUtils.createFolderSync(this._workingRootFolder)}else{this._fsUtils.deleteFolderSync(this._workingRootFolder,false)}if(this._isVerboseOrDebug){this._msg(`${VCOMP_MSG_PREFIX} Typescript will be compiled into '${this._workingRootFolder}'`)}let nodeJetRoot=path.join(auditBase,"node_modules","@oracle","oraclejet");if(!this._fsUtils.pathExistsSync(nodeJetRoot)){nodeJetRoot=path.normalize(path.join(auditBase,"..","..","node_modules","@oracle","oraclejet"))}let nodeJetPackage=path.join(nodeJetRoot,"package.json");let customTsc=this._utils.toJAFPath(path.join(nodeJetRoot,"dist","custom-tsc"));if(!this._fsUtils.pathExistsSync(customTsc)||!this._fsUtils.pathExistsSync(nodeJetPackage)){this._error("Unable to run VComponent pre-compilation -the required packages are not available. Run \"ojet restore\" or \"npm install\" to correct this.");return}let jetVerString;const packageJson=this._fsUtils.readJsonSync(nodeJetPackage);if(packageJson){jetVerString=packageJson.version}if(this._isVerboseOrDebug){this._msg(`${VCOMP_MSG_PREFIX} oraclejet package version -> ${jetVerString?jetVerString:"not found"}`)}let CustomTypeScriptCompiler;if(this._isVerboseOrDebug){this._msg(`${VCOMP_MSG_PREFIX} loading TypeScript compiler...`)}try{CustomTypeScriptCompiler=require(customTsc)}catch(e){this._jafMsg("jaf-ts-loader",`${VCOMP_MSG_PREFIX} failure loading TypeScript <- '${customTsc}'`)}if(!CustomTypeScriptCompiler){return}const readFrom=path.join(auditBase,sourceBase);let files=this._discoverCompilableFiles(readFrom,readFrom);if(!files||!files.length){return}files.forEach((file,x)=>{files[x]=this._utils.toJAFPath(file)});if(this._isDebug){this._displayCompilableList(files)}const buildOptions={debug:false,dtDir:compiledJSONFolder,version:"",jetVersion:"",templatePath:path.join(customTsc,"templates"),tsBuiltDir:compiledOutputFolder,typesDir:compiledOutputFolder};const compileOptionsPre12={files,compilerOptions:allTsConfig.compilerOptions,buildOptions:buildOptions};const compileOptions1201={tsconfigJson:{compilerOptions:allTsConfig.compilerOptions,files},buildOptions:buildOptions};let compileOptions;if(jetVerString){if(this._semVer.gt(jetVerString,"12.0.0")){compileOptions=compileOptions1201}else{compileOptions=compileOptionsPre12}if(this._semVer.lt(jetVerString,"16.0.0")){compileOptions.mainEntryFile="loader.d.ts"}}if(compileOptions){if(this._isDebug){this._debug(`Using TypeScript compile options ->\n${JSON.stringify(compileOptions,null,3)}\n`)}try{if(this._isVerboseOrDebug){this._msg(`${VCOMP_MSG_PREFIX} compiling ${files.length} file${files.length>1?"s":""}...`)}const{errors}=CustomTypeScriptCompiler.compile(compileOptions);if(errors.length){this._error(`${errors.length} Error${errors.length>1?"s":""} found during TypeScript pre-compilation of VComponents`);errors.forEach(error=>{if(error.hasOwnProperty("message")){this._error(error.message);this._error(error.stack)}else{this._jafMsg("jaf-ts-precompile",JSON.stringify(error))}})}else{this._msg(`${VCOMP_MSG_PREFIX} Typescript compilation of ${files.length} file${files.length!==1?"s":""} successful ...`)}if(!errors.length){this._vfiles=files}return compiledJSONFolder}catch(uncaughtFromCompile){this._error("Uncaught error during TypeScript pre-compilation of VComponents");this._error(uncaughtFromCompile.stack)}}else{this._error("Unable to run VComponent pre-compilation, cannot detect JET custom compiler version")}};PreCompiler.prototype._discoverCompilableFiles=function(root,pathPrefix){const allSources=this._fsUtils.readDirSync(root);return allSources?this._extractCompilables(allSources,"").map(sourceFile=>`${pathPrefix}/${sourceFile}`):null};PreCompiler.prototype._extractCompilables=function(sources,folder){return sources.reduce((compilables,candidate)=>{if(candidate.isFile&&(candidate.name.endsWith(".ts")||candidate.name.endsWith(".tsx"))){compilables.push(`${folder}/${candidate.name}`)}else if(candidate.files){compilables=compilables.concat(this._extractCompilables(candidate.files,`${folder}/${candidate.name}`))}return compilables},new Array)};PreCompiler.prototype._remapPath=function(definedPath,sourceFolder,auditBase){let newPath=definedPath;const segs=definedPath.split("/");if(segs[0]==="."){segs.shift()}switch(segs[0]){case"node_modules":case"jet_components":case"exchange_components":case sourceFolder:newPath=`${auditBase}${segs.join("/")}`;break}return newPath};PreCompiler.prototype._displayCompilableList=function(files){let count=0;let flist;if(files&&files.length){count=files.length;flist="\n "+files.join("\n ")}this._debug(`VComponents: discovered ${count} compilable files:${flist}`)};module.exports=PreCompiler;
|
package/libext/expparser.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 ExpParser=function(){this.parse=function(expr){var context={index:0,expr:expr};var nodes=_gobbleExpressions(context);if(nodes.length===1){return nodes[0]}return{type:COMPOUND,body:nodes}};function _gobbleExpressions(context,untilICode){const expr=context.expr;const length=expr.length;const nodes=[];while(context.index<length){_gobbleSpaces(context);const ch_i=expr.charCodeAt(context.index);if(ch_i===untilICode){break}else if(ch_i===SEMCOL_CODE||ch_i===COMMA_CODE){context.index++}else{const node=_gobbleExpression(context);if(node){nodes.push(node)}else if(context.index<length){_throwError("Unexpected \""+expr.charAt(context.index)+"\"",context.index)}}}return nodes}function _gobbleSpaces(context){var expr=context.expr;var ch=expr.charCodeAt(context.index);while(ch===32||ch===9||ch===10||ch===13){ch=expr.charCodeAt(++context.index)}}function _gobbleExpression(context){var expr=context.expr;var test=_gobbleBinaryExpression(context),consequent,alternate;_gobbleSpaces(context);if(expr.charCodeAt(context.index)===QUMARK_CODE){context.index++;consequent=_gobbleExpression(context);if(!consequent){_throwError("Expected expression",context.index)}_gobbleSpaces(context);if(expr.charCodeAt(context.index)===COLON_CODE){context.index++;alternate=_gobbleExpression(context);if(!alternate){_throwError("Expected expression",context.index)}return{type:CONDITIONAL_EXP,test:test,consequent:consequent,alternate:alternate}}_throwError("Expected :",context.index)}else{return test}}function _gobbleBinaryOp(context){var expr=context.expr;_gobbleSpaces(context);var to_check=expr.substr(context.index,_max_binop_len),tc_len=to_check.length;while(tc_len>0){if(_binary_ops[to_check]&&(!_isIdentifierStart(expr.charCodeAt(context.index))||context.index+to_check.length<expr.length&&!_isIdentifierPart(expr.charCodeAt(context.index+to_check.length)))){context.index+=tc_len;return to_check}to_check=to_check.substr(0,--tc_len)}return false}function _gobbleBinaryExpression(context){var node,biop,prec,stack,biop_info,left,right,i,cur_biop,cur_prec;left=_gobbleToken(context);biop=_gobbleBinaryOp(context);if(!biop){return left}biop_info={value:biop,prec:_binaryPrecedence(biop)};right=_gobbleToken(context);if(!right){_throwError("Expected expression after "+biop,context.index)}stack=[left,biop_info,right];cur_biop=biop;cur_prec=biop_info.prec;while(biop=_gobbleBinaryOp(context)){prec=_binaryPrecedence(biop,cur_biop,cur_prec);if(prec===0){break}biop_info={value:biop,prec:prec};cur_biop=biop;cur_prec=prec;while(stack.length>2&&prec<=stack[stack.length-2].prec){right=stack.pop();biop=stack.pop().value;left=stack.pop();node=_createBinaryExpression(biop,left,right,context);stack.push(node)}node=_gobbleToken(context);if(!node){_throwError("Expected expression after "+cur_biop,context.index)}stack.push(biop_info,node)}i=stack.length-1;node=stack[i];while(i>1){node=_createBinaryExpression(stack[i-1].value,stack[i-2],node,context);i-=2}return node}function _gobbleToken(context){var expr=context.expr;var ch,to_check,tc_len;_gobbleSpaces(context);ch=expr.charCodeAt(context.index);if(_isDecimalDigit(ch)||ch===PERIOD_CODE){return _gobbleNumericLiteral(context)}else if(ch===SQUOTE_CODE||ch===DQUOTE_CODE||ch===OBRACK_CODE){return _gobbleVariable(context)}else if(ch===OBRACE_CODE){return _gobbleObjectLiteral(context)}else if(ch===BTICK_CODE){return _gobbleTemplateLiteral(context)}to_check=expr.substr(context.index,_max_unop_len);tc_len=to_check.length;while(tc_len>0){if(to_check in _unary_ops&&(!_isIdentifierStart(expr.charCodeAt(context.index))||context.index+to_check.length<expr.length&&!_isIdentifierPart(expr.charCodeAt(context.index+to_check.length)))){context.index+=tc_len;return{type:UNARY_EXP,operator:to_check,argument:_gobbleToken(context),prefix:true}}to_check=to_check.substr(0,--tc_len)}var start=context.index;var funcEnd=context.index+8;if(expr.substring(start,funcEnd)==="function"&&!_isIdentifierPart(expr.charCodeAt(funcEnd))){context.index=funcEnd;return _gobbleFunction(context)}if(_isIdentifierStart(ch)||ch===OPAREN_CODE){return _gobbleVariable(context)}return false}function _gobbleNumericLiteral(context){var expr=context.expr;var number="",ch,chCode;while(_isDecimalDigit(expr.charCodeAt(context.index))){number+=expr.charAt(context.index++)}if(expr.charCodeAt(context.index)===PERIOD_CODE){number+=expr.charAt(context.index++);while(_isDecimalDigit(expr.charCodeAt(context.index))){number+=expr.charAt(context.index++)}}ch=expr.charAt(context.index);if(ch==="e"||ch==="E"){number+=expr.charAt(context.index++);ch=expr.charAt(context.index);if(ch==="+"||ch==="-"){number+=expr.charAt(context.index++)}while(_isDecimalDigit(expr.charCodeAt(context.index))){number+=expr.charAt(context.index++)}if(!_isDecimalDigit(expr.charCodeAt(context.index-1))){_throwError("Expected exponent ("+number+expr.charAt(context.index)+")",context.index)}}chCode=expr.charCodeAt(context.index);if(_isIdentifierStart(chCode)){_throwError("Variable names cannot start with a number ("+number+expr.charAt(context.index)+")",context.index)}else if(chCode===PERIOD_CODE){_throwError("Unexpected period",context.index)}return{type:LITERAL,value:parseFloat(number),raw:number}}function _gobbleStringLiteral(context){var expr=context.expr;var str="",quote=expr.charAt(context.index++),closed=false,ch;var length=expr.length;while(context.index<length){ch=expr.charAt(context.index++);if(ch===quote){closed=true;break}else if(ch==="\\"){ch=expr.charAt(context.index++);switch(ch){case"n":str+="\n";break;case"r":str+="\r";break;case"t":str+="\t";break;case"b":str+="\b";break;case"f":str+="\f";break;case"v":str+="\x0B";break;default:str+=ch}}else{str+=ch}}if(!closed){_throwError("Unclosed quote after \""+str+"\"",context.index)}return{type:LITERAL,value:str,raw:quote+str+quote}}function _gobbleIdentifier(context,bMemberExpr){var expr=context.expr;var ch=expr.charCodeAt(context.index),start=context.index,identifier;if(_isIdentifierStart(ch)){context.index++}else{_throwError("Unexpected "+expr.charAt(context.index),context.index)}var length=expr.length;while(context.index<length){ch=expr.charCodeAt(context.index);if(_isIdentifierPart(ch)){context.index++}else{break}}identifier=expr.slice(start,context.index);if(identifier==="new"&&!bMemberExpr){_gobbleSpaces(context);var constructorNode=_gobbleVariable(context,CALL_EXP);if(constructorNode.type!==CALL_EXP){_throwError("Expression of type: "+constructorNode.type+" not supported for constructor expression")}return{type:NEW_EXP,callee:constructorNode.callee,arguments:constructorNode.arguments}}if(_literals.has(identifier)){return{type:LITERAL,value:_literals.get(identifier),raw:identifier}}return{type:IDENTIFIER,name:identifier}}function _gobbleArguments(context,termination,identifiersOnly){var expr=context.expr;var length=expr.length;var ch_i,args=[],node,closed=false;var separator_count=0;while(context.index<length){_gobbleSpaces(context);ch_i=expr.charCodeAt(context.index);if(ch_i===termination){closed=true;context.index++;if(termination===CPAREN_CODE&&separator_count&&separator_count>=args.length){_throwError("Unexpected token "+String.fromCharCode(termination),context.index)}break}else if(ch_i===COMMA_CODE){context.index++;separator_count++;if(separator_count!==args.length){if(termination===CPAREN_CODE){_throwError("Unexpected token ,",context.index)}else if(termination===CBRACK_CODE){for(var arg=args.length;arg<separator_count;arg++){args.push(null)}}}}else{if(identifiersOnly){node=_gobbleIdentifier(context)}else{node=_gobbleExpression(context)}if(!node||args.length>separator_count){_throwError("Expected comma",context.index)}args.push(node)}}if(!closed){_throwError("Expected "+String.fromCharCode(termination),context.index)}return args}function _gobbleVariable(context,stopAtType){var expr=context.expr;var ch_i,node;ch_i=expr.charCodeAt(context.index);if(ch_i===OPAREN_CODE){node=_gobbleGroup(context)}else if(ch_i===SQUOTE_CODE||ch_i===DQUOTE_CODE){node=_gobbleStringLiteral(context)}else if(ch_i===OBRACK_CODE){node=_gobbleArray(context)}else{node=_gobbleIdentifier(context)}_gobbleSpaces(context);ch_i=expr.charCodeAt(context.index);while(ch_i===PERIOD_CODE||ch_i===OBRACK_CODE||ch_i===OPAREN_CODE||_isOptionalChaining(context)){context.index++;if(ch_i===PERIOD_CODE){_gobbleSpaces(context);node={type:MEMBER_EXP,computed:false,object:node,property:_gobbleIdentifier(context,true)}}else if(ch_i===QUMARK_CODE){context.index++;_gobbleSpaces(context);node={type:MEMBER_EXP,computed:false,optional:true,object:node,property:_gobbleIdentifier(context,true)}}else if(ch_i===OBRACK_CODE){node={type:MEMBER_EXP,computed:true,object:node,property:_gobbleExpression(context)};_gobbleSpaces(context);ch_i=expr.charCodeAt(context.index);if(ch_i!==CBRACK_CODE){_throwError("Unclosed [",context.index)}context.index++}else if(ch_i===OPAREN_CODE){node={type:CALL_EXP,arguments:_gobbleArguments(context,CPAREN_CODE),callee:node}}if(stopAtType===node.type){return node}_gobbleSpaces(context);ch_i=expr.charCodeAt(context.index)}return node}function _gobbleGroup(context){context.index++;var node=_gobbleExpression(context);_gobbleSpaces(context);if(context.expr.charCodeAt(context.index)===CPAREN_CODE){context.index++;return node}_throwError("Unclosed (",context.index)}function _gobbleArray(context){context.index++;return{type:ARRAY_EXP,elements:_gobbleArguments(context,CBRACK_CODE)}}function _gobbleFunction(context){var expr=context.expr;_gobbleSpaces(context);var ch_i=expr.charCodeAt(context.index);if(ch_i!==OPAREN_CODE){_throwError("Expected (,",context.index)}context.index++;var args=_gobbleArguments(context,CPAREN_CODE,true);_gobbleSpaces(context);ch_i=expr.charCodeAt(context.index);if(ch_i!==OBRACE_CODE){_throwError("Expected {,",context.index)}context.index++;_gobbleSpaces(context);var startDef=context.index;var hasReturn;var start=context.index;if(expr.substring(start,start+6)==="return"){hasReturn=true;context.index+=6}_gobbleSpaces(context);var body=_gobbleExpression(context);_gobbleSpaces(context);ch_i=expr.charCodeAt(context.index);if(ch_i===SEMCOL_CODE){context.index++;_gobbleSpaces(context)}ch_i=expr.charCodeAt(context.index);if(ch_i!==CBRACE_CODE){_throwError("Expected },",context.index)}context.index++;return{type:FUNCTION_EXP,arguments:args,body:body,expr:expr.substring(startDef,context.index-1),return:hasReturn}}function _gobbleObjectLiteral(context){var expr=context.expr;context.index++;var props=[];var closed;var separator_count=0;var length=expr.length;while(context.index<length&&!closed){_gobbleSpaces(context);var ch_i=expr.charCodeAt(context.index);if(ch_i===CBRACE_CODE){closed=true;context.index++}else if(ch_i===COMMA_CODE){context.index++;separator_count++;if(separator_count!==props.length){_throwError("Unexpected token ,",context.index)}}else{var key=ch_i===SQUOTE_CODE||ch_i===DQUOTE_CODE?_gobbleStringLiteral(context):_gobbleIdentifier(context);_gobbleSpaces(context);ch_i=expr.charCodeAt(context.index);if(key.type===IDENTIFIER&&(ch_i===COMMA_CODE||ch_i===CBRACE_CODE)){props.push({type:PROPERTY,key:key,value:key,shorthand:true})}else if(ch_i===COLON_CODE){context.index++;var writer=context.writer;var keyValue=getKeyValue(key);if(keyValue==="_ko_property_writers"){context.writer=1}try{props.push({type:PROPERTY,key:key,value:_gobbleExpression(context),shorthand:false})}finally{context.writer=writer}}else{_throwError("Expected ':'. Found "+String.fromCharCode(ch_i),context.index)}}}if(!closed){_throwError("Expected "+String.fromCharCode(CBRACE_CODE),context.index)}return{type:OBJECT_EXP,properties:props}}function _gobbleTemplateLiteral(context){const expr=context.expr;let ch_i=expr.charCodeAt(context.index);if(ch_i===BTICK_CODE){const node={type:TEMPLATE_LITERAL,quasis:[],expressions:[]};let cooked="";let raw="";let closed=false;const length=expr.length;const pushQuasi=()=>node.quasis.push({type:TEMPLATE_ELEMENT,value:{raw,cooked},tail:closed});while(context.index<length){let ch=expr.charAt(++context.index);if(ch==="`"){context.index+=1;closed=true;pushQuasi();return node}else if(ch==="$"&&expr.charAt(context.index+1)==="{"){context.index+=2;pushQuasi();raw="";cooked="";try{node.expressions.push(..._gobbleExpressions(context,CBRACE_CODE))}finally{ch_i=expr.charCodeAt(context.index);if(ch_i!==CBRACE_CODE){_throwError("Unclosed ${ in template literal",expr)}}}else if(ch==="\\"){raw+=ch;ch=expr.charAt(++context.index);raw+=ch;switch(ch){case"n":cooked+="\n";break;case"r":cooked+="\r";break;case"t":cooked+="\t";break;case"b":cooked+="\b";break;case"f":cooked+="\f";break;case"v":cooked+="\x0B";break;default:cooked+=ch}}else{cooked+=ch;raw+=ch}}if(context.index===length){_throwError("Unclosed backtick ` in template literal",expr)}}return false}var PERIOD_CODE=46,COMMA_CODE=44,SQUOTE_CODE=39,DQUOTE_CODE=34,OPAREN_CODE=40,CPAREN_CODE=41,OBRACK_CODE=91,CBRACK_CODE=93,QUMARK_CODE=63,SEMCOL_CODE=59,COLON_CODE=58,BTICK_CODE=96,OBRACE_CODE=123,CBRACE_CODE=125;function _getMaxKeyLen(obj){return Object.keys(obj).reduce(function(curr,key){return Math.max(curr,key.length)},0)}var t=true,_unary_ops={"-":t,"!":t,"~":t,"+":t,typeof:t},_binary_ops={"=":1,"||":2,"??":2,"&&":3,"|":4,"^":5,"&":6,"==":7,"!=":7,"===":7,"!==":7,"<":8,">":8,"<=":8,">=":8,instanceof:8,"<<":9,">>":9,">>>":9,"+":10,"-":10,"*":11,"/":11,"%":11,"**":12},_max_unop_len=_getMaxKeyLen(_unary_ops),_max_binop_len=_getMaxKeyLen(_binary_ops);var _literals=new Map;_literals.set("true",true);_literals.set("false",false);_literals.set("null",null);_literals.set("undefined",undefined);function _binaryPrecedence(op_val,prev_op_val,prev_op_prec){const basePrec=_binary_ops[op_val]||0;if(basePrec!==12||prev_op_val===undefined||op_val!==prev_op_val){return basePrec}return(prev_op_prec+13)*0.5}function _createBinaryExpression(operator,left,right,context){if(operator==="="&&!context.writer){_throwError("Unexpected operator '='",context.index)}var type=operator==="||"||operator==="&&"||operator==="??"?LOGICAL_EXP:BINARY_EXP;return{type:type,operator:operator,left:left,right:right}}function _isOptionalChaining(context){var expr=context.expr;if(expr.charCodeAt(context.index)===QUMARK_CODE&&expr.charCodeAt(context.index+1)===PERIOD_CODE&&!_isDecimalDigit(expr.charCodeAt(context.index+2))){return true}return false}function _isDecimalDigit(ch){return ch>=48&&ch<=57}function _isIdentifierStart(ch){return ch===36||ch===95||ch>=65&&ch<=90||ch>=97&&ch<=122||ch>=128&&!_binary_ops[String.fromCharCode(ch)]}function _isIdentifierPart(ch){return ch===36||ch===95||ch>=65&&ch<=90||ch>=97&&ch<=122||ch>=48&&ch<=57||ch>=128&&!_binary_ops[String.fromCharCode(ch)]}function _throwError(message,index){var error=new Error(message+" at character "+index);error.index=index;error.description=message;throw error}};const getKeyValue=function(keyObj){return keyObj.type===IDENTIFIER?keyObj.name:keyObj.value};module.exports=ExpParser;const COMPOUND="Compound";const IDENTIFIER="Identifier";const MEMBER_EXP="MemberExpression";const LITERAL="Literal";const CALL_EXP="CallExpression";const UNARY_EXP="UnaryExpression";const BINARY_EXP="BinaryExpression";const LOGICAL_EXP="LogicalExpression";const CONDITIONAL_EXP="ConditionalExpression";const ARRAY_EXP="ArrayExpression";const OBJECT_EXP="ObjectExpression";const FUNCTION_EXP="FunctionExpression";const NEW_EXP="NewExpression";const PROPERTY="Property";const TEMPLATE_LITERAL="TemplateLiteral";const TEMPLATE_ELEMENT="TemplateElement";
|
|
6
|
+
const ExpParser=function(){this.parse=function(expr){var context={index:0,expr:expr};var nodes=_gobbleExpressions(context);if(nodes.length===1){return nodes[0]}return{type:COMPOUND,body:nodes}};function _gobbleExpressions(context,untilICode){const expr=context.expr;const length=expr.length;const nodes=[];while(context.index<length){_gobbleSpaces(context);const ch_i=expr.charCodeAt(context.index);if(ch_i===SEMCOL_CODE||ch_i===COMMA_CODE){context.index++}else{const node=_gobbleExpression(context);if(node){nodes.push(node)}else if(context.index<length){if(ch_i===untilICode){break}_throwError("Unexpected \""+expr.charAt(context.index)+"\"",context.index)}}}return nodes}function _gobbleSpaces(context){var expr=context.expr;var ch=expr.charCodeAt(context.index);while(ch===32||ch===9||ch===10||ch===13){ch=expr.charCodeAt(++context.index)}}function _gobbleExpression(context){const expr=context.expr;let test=_gobbleArrowFunctionExpression(context)||_gobbleBinaryExpression(context),consequent,alternate;_gobbleSpaces(context);if(expr.charCodeAt(context.index)===QUMARK_CODE){context.index++;consequent=_gobbleExpression(context);if(!consequent){_throwError("Expected expression",context.index)}_gobbleSpaces(context);if(expr.charCodeAt(context.index)===COLON_CODE){context.index++;alternate=_gobbleExpression(context);if(!alternate){_throwError("Expected expression",context.index)}test={type:CONDITIONAL_EXP,test:test,consequent:consequent,alternate:alternate}}else{_throwError("Expected :",context.index)}}_updateBinariesToArrows(test);return test}function _gobbleBinaryOp(context){var expr=context.expr;_gobbleSpaces(context);var to_check=expr.substr(context.index,_max_binop_len),tc_len=to_check.length;while(tc_len>0){if(_binary_ops[to_check]&&(!_isIdentifierStart(expr.charCodeAt(context.index))||context.index+to_check.length<expr.length&&!_isIdentifierPart(expr.charCodeAt(context.index+to_check.length)))){context.index+=tc_len;return to_check}to_check=to_check.substr(0,--tc_len)}return false}function _gobbleBinaryExpression(context){var node,biop,prec,stack,biop_info,left,right,i,cur_biop,cur_prec;left=_gobbleToken(context);biop=_gobbleBinaryOp(context);if(!biop){return left}biop_info={value:biop,prec:_binaryPrecedence(biop)};right=biop==="=>"?_gobbleArrowFunctionBody(context):_gobbleToken(context);if(!right){_throwError("Expected expression after "+biop,context.index)}stack=[left,biop_info,right];cur_biop=biop;cur_prec=biop_info.prec;while(biop=_gobbleBinaryOp(context)){prec=_binaryPrecedence(biop,cur_biop,cur_prec);if(prec===0){break}biop_info={value:biop,prec:prec};cur_biop=biop;cur_prec=prec;while(stack.length>2&&prec<=stack[stack.length-2].prec){right=stack.pop();biop=stack.pop().value;left=stack.pop();node=_createBinaryExpression(biop,left,right,context);stack.push(node)}node=_gobbleToken(context);if(!node){_throwError("Expected expression after "+cur_biop,context.index)}stack.push(biop_info,node)}i=stack.length-1;node=stack[i];while(i>1){node=_createBinaryExpression(stack[i-1].value,stack[i-2],node,context);i-=2}return node}function _gobbleToken(context){var expr=context.expr;var ch,to_check,tc_len;_gobbleSpaces(context);ch=expr.charCodeAt(context.index);if(_isDecimalDigit(ch)||ch===PERIOD_CODE){return _gobbleNumericLiteral(context)}else if(ch===SQUOTE_CODE||ch===DQUOTE_CODE||ch===OBRACK_CODE){return _gobbleVariable(context)}else if(ch===OBRACE_CODE){return _gobbleObjectLiteral(context)}else if(ch===BTICK_CODE){return _gobbleTemplateLiteral(context)}to_check=expr.substr(context.index,_max_unop_len);tc_len=to_check.length;while(tc_len>0){if(to_check in _unary_ops&&(!_isIdentifierStart(expr.charCodeAt(context.index))||context.index+to_check.length<expr.length&&!_isIdentifierPart(expr.charCodeAt(context.index+to_check.length)))){context.index+=tc_len;return{type:UNARY_EXP,operator:to_check,argument:_gobbleToken(context),prefix:true}}to_check=to_check.substr(0,--tc_len)}var start=context.index;var funcEnd=context.index+8;if(expr.substring(start,funcEnd)==="function"&&!_isIdentifierPart(expr.charCodeAt(funcEnd))){context.index=funcEnd;return _gobbleFunction(context)}if(_isIdentifierStart(ch)||ch===OPAREN_CODE){return _gobbleVariable(context)}return false}function _gobbleNumericLiteral(context){var expr=context.expr;var number="",ch,chCode;while(_isDecimalDigit(expr.charCodeAt(context.index))){number+=expr.charAt(context.index++)}if(expr.charCodeAt(context.index)===PERIOD_CODE){number+=expr.charAt(context.index++);while(_isDecimalDigit(expr.charCodeAt(context.index))){number+=expr.charAt(context.index++)}}ch=expr.charAt(context.index);if(ch==="e"||ch==="E"){number+=expr.charAt(context.index++);ch=expr.charAt(context.index);if(ch==="+"||ch==="-"){number+=expr.charAt(context.index++)}while(_isDecimalDigit(expr.charCodeAt(context.index))){number+=expr.charAt(context.index++)}if(!_isDecimalDigit(expr.charCodeAt(context.index-1))){_throwError("Expected exponent ("+number+expr.charAt(context.index)+")",context.index)}}chCode=expr.charCodeAt(context.index);if(_isIdentifierStart(chCode)){_throwError("Variable names cannot start with a number ("+number+expr.charAt(context.index)+")",context.index)}else if(chCode===PERIOD_CODE){_throwError("Unexpected period",context.index)}return{type:LITERAL,value:parseFloat(number),raw:number}}function _gobbleStringLiteral(context){var expr=context.expr;var str="",quote=expr.charAt(context.index++),closed=false,ch;var length=expr.length;while(context.index<length){ch=expr.charAt(context.index++);if(ch===quote){closed=true;break}else if(ch==="\\"){ch=expr.charAt(context.index++);switch(ch){case"n":str+="\n";break;case"r":str+="\r";break;case"t":str+="\t";break;case"b":str+="\b";break;case"f":str+="\f";break;case"v":str+="\x0B";break;default:str+=ch}}else{str+=ch}}if(!closed){_throwError("Unclosed quote after \""+str+"\"",context.index)}return{type:LITERAL,value:str,raw:quote+str+quote}}function _gobbleIdentifier(context,bMemberExpr){var expr=context.expr;var ch=expr.charCodeAt(context.index),start=context.index,identifier;if(_isIdentifierStart(ch)){context.index++}else{_throwError("Unexpected "+expr.charAt(context.index),context.index)}var length=expr.length;while(context.index<length){ch=expr.charCodeAt(context.index);if(_isIdentifierPart(ch)){context.index++}else{break}}identifier=expr.slice(start,context.index);if(identifier==="new"&&!bMemberExpr){_gobbleSpaces(context);var constructorNode=_gobbleVariable(context,CALL_EXP);if(constructorNode.type!==CALL_EXP){_throwError("Expression of type: "+constructorNode.type+" not supported for constructor expression")}return{type:NEW_EXP,callee:constructorNode.callee,arguments:constructorNode.arguments}}if(_literals.has(identifier)){return{type:LITERAL,value:_literals.get(identifier),raw:identifier}}return{type:IDENTIFIER,name:identifier}}function _gobbleArguments(context,termination,identifiersOnly){var expr=context.expr;var length=expr.length;var ch_i,args=[],node,closed=false;var separator_count=0;while(context.index<length){_gobbleSpaces(context);ch_i=expr.charCodeAt(context.index);if(ch_i===termination){closed=true;context.index++;if(termination===CPAREN_CODE&&separator_count&&separator_count>=args.length){_throwError("Unexpected token "+String.fromCharCode(termination),context.index)}break}else if(ch_i===COMMA_CODE){context.index++;separator_count++;if(separator_count!==args.length){if(termination===CPAREN_CODE){_throwError("Unexpected token ,",context.index)}else if(termination===CBRACK_CODE){for(var arg=args.length;arg<separator_count;arg++){args.push(null)}}}}else{if(identifiersOnly){node=_gobbleIdentifier(context)}else{node=_gobbleExpression(context)}if(!node||args.length>separator_count){_throwError("Expected comma",context.index)}args.push(node)}}if(!closed){_throwError("Expected "+String.fromCharCode(termination),context.index)}return args}function _gobbleVariable(context,stopAtType){var expr=context.expr;var ch_i,node;ch_i=expr.charCodeAt(context.index);if(ch_i===OPAREN_CODE){node=_gobbleGroup(context)}else if(ch_i===SQUOTE_CODE||ch_i===DQUOTE_CODE){node=_gobbleStringLiteral(context)}else if(ch_i===OBRACK_CODE){node=_gobbleArray(context)}else{node=_gobbleIdentifier(context)}_gobbleSpaces(context);ch_i=expr.charCodeAt(context.index);while(ch_i===PERIOD_CODE||ch_i===OBRACK_CODE||ch_i===OPAREN_CODE||_isOptionalChaining(context)){context.index++;if(ch_i===PERIOD_CODE){_gobbleSpaces(context);node={type:MEMBER_EXP,computed:false,object:node,property:_gobbleIdentifier(context,true)}}else if(ch_i===QUMARK_CODE){context.index++;_gobbleSpaces(context);node={type:MEMBER_EXP,computed:false,optional:true,object:node,property:_gobbleIdentifier(context,true)}}else if(ch_i===OBRACK_CODE){node={type:MEMBER_EXP,computed:true,object:node,property:_gobbleExpression(context)};_gobbleSpaces(context);ch_i=expr.charCodeAt(context.index);if(ch_i!==CBRACK_CODE){_throwError("Unclosed [",context.index)}context.index++}else if(ch_i===OPAREN_CODE){node={type:CALL_EXP,arguments:_gobbleArguments(context,CPAREN_CODE),callee:node}}if(stopAtType===node.type){return node}_gobbleSpaces(context);ch_i=expr.charCodeAt(context.index)}return node}function _gobbleGroup(context){context.index++;let nodes=_gobbleExpressions(context,CPAREN_CODE);if(context.expr.charCodeAt(context.index)===CPAREN_CODE){context.index++;if(nodes.length===1){return nodes[0]}else if(!nodes.length){return false}return{type:SEQUENCE_EXP,expressions:nodes}}_throwError("Unclosed (",context.index)}function _gobbleArray(context){context.index++;return{type:ARRAY_EXP,elements:_gobbleArguments(context,CBRACK_CODE)}}function _gobbleFunctionBody(context){_gobbleSpaces(context);const expr=context.expr;let ch_i=expr.charCodeAt(context.index);context.index++;_gobbleSpaces(context);let hasReturn=false;const start=context.index;if(expr.substring(start,start+6)==="return"){hasReturn=true;context.index+=6}_gobbleSpaces(context);const funcBody=_gobbleExpression(context);_gobbleSpaces(context);ch_i=expr.charCodeAt(context.index);if(ch_i===SEMCOL_CODE){context.index++;_gobbleSpaces(context)}ch_i=expr.charCodeAt(context.index);if(ch_i!==CBRACE_CODE){_throwError("Expected },",context.index)}context.index++;return{type:BLOCK_STATEMENT,expr:expr.substring(start,context.index-1),body:hasReturn?{type:RETURN_STATEMENT,argument:funcBody}:funcBody}}function _gobbleFunction(context){var expr=context.expr;_gobbleSpaces(context);var ch_i=expr.charCodeAt(context.index);if(ch_i!==OPAREN_CODE){_throwError("Expected (,",context.index)}context.index++;var args=_gobbleArguments(context,CPAREN_CODE,true);_gobbleSpaces(context);ch_i=expr.charCodeAt(context.index);if(ch_i!==OBRACE_CODE){_throwError("Expected {,",context.index)}return{type:FUNCTION_EXP,params:args,body:_gobbleFunctionBody(context)}}function _gobbleObjectLiteral(context){var expr=context.expr;context.index++;var props=[];var closed;var separator_count=0;var length=expr.length;while(context.index<length&&!closed){_gobbleSpaces(context);var ch_i=expr.charCodeAt(context.index);if(ch_i===CBRACE_CODE){closed=true;context.index++}else if(ch_i===COMMA_CODE){context.index++;separator_count++;if(separator_count!==props.length){_throwError("Unexpected token ,",context.index)}}else{var key=ch_i===SQUOTE_CODE||ch_i===DQUOTE_CODE?_gobbleStringLiteral(context):_gobbleIdentifier(context);_gobbleSpaces(context);ch_i=expr.charCodeAt(context.index);if(key.type===IDENTIFIER&&(ch_i===COMMA_CODE||ch_i===CBRACE_CODE)){props.push({type:PROPERTY,key:key,value:key,shorthand:true})}else if(ch_i===COLON_CODE){context.index++;var writer=context.writer;var keyValue=getKeyValue(key);if(keyValue==="_ko_property_writers"){context.writer=1}try{props.push({type:PROPERTY,key:key,value:_gobbleExpression(context),shorthand:false})}finally{context.writer=writer}}else{_throwError("Expected ':'. Found "+String.fromCharCode(ch_i),context.index)}}}if(!closed){_throwError("Expected "+String.fromCharCode(CBRACE_CODE),context.index)}return{type:OBJECT_EXP,properties:props}}function _gobbleTemplateLiteral(context){const expr=context.expr;let ch_i=expr.charCodeAt(context.index);if(ch_i===BTICK_CODE){const node={type:TEMPLATE_LITERAL,quasis:[],expressions:[]};let cooked="";let raw="";let closed=false;const length=expr.length;const pushQuasi=()=>node.quasis.push({type:TEMPLATE_ELEMENT,value:{raw,cooked},tail:closed});while(context.index<length){let ch=expr.charAt(++context.index);if(ch==="`"){context.index+=1;closed=true;pushQuasi();return node}else if(ch==="$"&&expr.charAt(context.index+1)==="{"){context.index+=2;pushQuasi();raw="";cooked="";try{node.expressions.push(..._gobbleExpressions(context,CBRACE_CODE))}finally{ch_i=expr.charCodeAt(context.index);if(ch_i!==CBRACE_CODE){_throwError("Unclosed ${ in template literal",expr)}}}else if(ch==="\\"){raw+=ch;ch=expr.charAt(++context.index);raw+=ch;switch(ch){case"n":cooked+="\n";break;case"r":cooked+="\r";break;case"t":cooked+="\t";break;case"b":cooked+="\b";break;case"f":cooked+="\f";break;case"v":cooked+="\x0B";break;default:cooked+=ch}}else{cooked+=ch;raw+=ch}}if(context.index===length){_throwError("Unclosed backtick ` in template literal",expr)}}return false}function _gobbleArrowFunctionExpression(context){const expr=context.expr;let ch=expr.charCodeAt(context.index);let node;if(ch===OPAREN_CODE){const backupIndex=context.index;context.index++;_gobbleSpaces(context);ch=expr.charCodeAt(context.index);if(ch===CPAREN_CODE){context.index++;const biop=_gobbleBinaryOp(context);if(biop==="=>"){const body=_gobbleArrowFunctionBody(context);if(!body){_throwError("Expected expression after "+biop)}node={type:ARROW_EXP,params:[],body}}}if(!node){context.index=backupIndex}}return node}function _gobbleArrowFunctionBody(context){const expr=context.expr;_gobbleSpaces(context);let returnNode;if(expr.charCodeAt(context.index)===OBRACE_CODE){returnNode=_gobbleFunctionBody(context)}else{const startDef=context.index;_gobbleSpaces(context);const funcBody=_gobbleExpression(context);_gobbleSpaces(context);context.index++;returnNode={type:BLOCK_STATEMENT,expr:expr.substring(startDef,context.index-1),body:{type:RETURN_STATEMENT,argument:funcBody}}}return returnNode}function _updateBinariesToArrows(node){if(node){Object.values(node).forEach(val=>{if(val&&typeof val==="object"){_updateBinariesToArrows(val)}});if(node.operator==="=>"){node.type=ARROW_EXP;node.params=node.left?[node.left]:null;node.body=node.right;if(node.params&&node.params[0].type===SEQUENCE_EXP){node.params=node.params[0].expressions}delete node.left;delete node.right;delete node.operator}}}var PERIOD_CODE=46,COMMA_CODE=44,SQUOTE_CODE=39,DQUOTE_CODE=34,OPAREN_CODE=40,CPAREN_CODE=41,OBRACK_CODE=91,CBRACK_CODE=93,QUMARK_CODE=63,SEMCOL_CODE=59,COLON_CODE=58,BTICK_CODE=96,OBRACE_CODE=123,CBRACE_CODE=125;function _getMaxKeyLen(obj){return Object.keys(obj).reduce(function(curr,key){return Math.max(curr,key.length)},0)}var t=true,_unary_ops={"-":t,"!":t,"~":t,"+":t,typeof:t},_binary_ops={"=":1,"||":2,"??":2,"&&":3,"|":4,"^":5,"&":6,"==":7,"!=":7,"===":7,"!==":7,"<":8,">":8,"<=":8,">=":8,instanceof:8,"<<":9,">>":9,">>>":9,"+":10,"-":10,"*":11,"/":11,"%":11,"**":12,"=>":0.1},_max_unop_len=_getMaxKeyLen(_unary_ops),_max_binop_len=_getMaxKeyLen(_binary_ops);var _literals=new Map;_literals.set("true",true);_literals.set("false",false);_literals.set("null",null);_literals.set("undefined",undefined);function _binaryPrecedence(op_val,prev_op_val,prev_op_prec){const basePrec=_binary_ops[op_val]||0;if(basePrec!==12||prev_op_val===undefined||op_val!==prev_op_val){return basePrec}return(prev_op_prec+13)*0.5}function _createBinaryExpression(operator,left,right,context){if(operator==="="&&!context.writer){_throwError("Unexpected operator '='",context.index)}var type=operator==="||"||operator==="&&"||operator==="??"?LOGICAL_EXP:BINARY_EXP;return{type:type,operator:operator,left:left,right:right}}function _isOptionalChaining(context){var expr=context.expr;if(expr.charCodeAt(context.index)===QUMARK_CODE&&expr.charCodeAt(context.index+1)===PERIOD_CODE&&!_isDecimalDigit(expr.charCodeAt(context.index+2))){return true}return false}function _isDecimalDigit(ch){return ch>=48&&ch<=57}function _isIdentifierStart(ch){return ch===36||ch===95||ch>=65&&ch<=90||ch>=97&&ch<=122||ch>=128&&!_binary_ops[String.fromCharCode(ch)]}function _isIdentifierPart(ch){return ch===36||ch===95||ch>=65&&ch<=90||ch>=97&&ch<=122||ch>=48&&ch<=57||ch>=128&&!_binary_ops[String.fromCharCode(ch)]}function _throwError(message,index){var error=new Error(message+" at character "+index);error.index=index;error.description=message;throw error}};const getKeyValue=function(keyObj){return keyObj.type===IDENTIFIER?keyObj.name:keyObj.value};module.exports=ExpParser;const COMPOUND="Compound";const IDENTIFIER="Identifier";const MEMBER_EXP="MemberExpression";const LITERAL="Literal";const CALL_EXP="CallExpression";const UNARY_EXP="UnaryExpression";const BINARY_EXP="BinaryExpression";const LOGICAL_EXP="LogicalExpression";const CONDITIONAL_EXP="ConditionalExpression";const ARRAY_EXP="ArrayExpression";const OBJECT_EXP="ObjectExpression";const FUNCTION_EXP="FunctionExpression";const NEW_EXP="NewExpression";const PROPERTY="Property";const TEMPLATE_LITERAL="TemplateLiteral";const TEMPLATE_ELEMENT="TemplateElement";const SEQUENCE_EXP="SequenceExpression";const ARROW_EXP="ArrowFunctionExpression";const RETURN_STATEMENT="ReturnStatement";const BLOCK_STATEMENT="BlockStatement";
|