@oracle/oraclejet-audit 12.0.0 → 13.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/jaf-amd.js +2 -20
- package/jaf.js +1 -1
- package/jafapi.js +1 -1
- package/lib/AST_Ts.js +1 -1
- package/lib/AstJson.js +1 -1
- package/lib/AstMd.js +1 -1
- package/lib/AstNodeTypes.js +1 -1
- package/lib/Cli.js +6 -0
- package/lib/Color.js +6 -0
- package/lib/Comments.js +1 -1
- package/lib/ComponentSvcs.js +1 -1
- package/lib/Components.js +1 -1
- package/lib/Config.js +1 -1
- package/lib/ConfigLib.js +1 -1
- package/lib/CssUtils.js +1 -1
- package/lib/DomUtils.js +1 -1
- package/lib/FileSet.js +1 -1
- package/lib/FsUtils.js +1 -1
- package/lib/Issue.js +1 -1
- package/lib/JafEvents.js +1 -1
- package/lib/JafLib.js +1 -1
- package/lib/Json.js +1 -1
- package/lib/JsonLoader.js +1 -1
- package/lib/Md.js +1 -1
- package/lib/MetaLib.js +1 -1
- package/lib/OjCPack.js +6 -0
- package/lib/OjetLib.js +6 -0
- package/lib/Registry.js +1 -1
- package/lib/RuleSet.js +1 -1
- package/lib/Rules.js +1 -1
- package/lib/Scope.js +1 -1
- package/lib/Utils.js +1 -1
- package/lib/ZipUtils.js +1 -1
- package/lib/amdlist.js +6 -0
- package/lib/api.js +1 -1
- package/lib/betalist.js +6 -0
- package/lib/builtinpacks.js +1 -1
- package/lib/checkage.js +6 -0
- package/lib/cliStats.js +1 -1
- package/lib/cmdline.js +1 -1
- package/lib/defaults.js +1 -1
- package/lib/deflist.js +1 -1
- package/lib/dislist.js +1 -1
- package/lib/exportRules.js +1 -1
- package/lib/extends.js +1 -1
- package/lib/grouplist.js +1 -1
- package/lib/groups.js +1 -1
- package/lib/help.js +1 -1
- package/lib/jetver.js +1 -1
- package/lib/manpage.js +6 -0
- package/lib/manual.js +1 -1
- package/lib/metaLoader.js +1 -1
- package/lib/metahist.js +1 -1
- package/lib/msgidLoader.js +1 -1
- package/lib/ns.js +1 -1
- package/lib/outfile.js +1 -1
- package/lib/proflist.js +6 -0
- package/lib/rlolist.js +6 -0
- package/lib/scaffold.js +1 -1
- package/lib/scaffoldRule.js +1 -1
- package/lib/schema.js +1 -1
- package/lib/scopewalker.js +1 -1
- package/meta/12.1.0/jetauditmeta.js +9 -0
- package/meta/13.0.0/jetauditmeta.js +9 -0
- package/meta/metaverlist.json +1 -1
- package/package.json +6 -4
- package/profiles/best-practice.json +146 -0
- package/profiles/redwood-strict.json +31 -0
- package/rulepacks/jetwc/jetwc-bootstrap.js +1 -1
- package/rulepacks/jetwc/jetwc-css-oj-complete.js +1 -1
- package/rulepacks/jetwc/jetwc-pack-children.js +1 -1
- package/rulepacks/jetwc/jetwc-schema.js +1 -1
- package/rulepacks/jetwc/jetwc-supproperty-propagation.js +6 -0
- package/rulepacks/jetwc/msgid.json +1 -1
- package/rulepacks/jetwc/rules.json +1 -1
- package/rulepacks/jetwc-lib/jetwcutils-componentFinder.js +1 -1
- package/rulepacks/jetwc-lib/jetwcutils-preCompiler.js +1 -1
- package/rulepacks/jetwco/jetwco-bootstrap.js +1 -1
- package/rulepacks/jetwco/jetwco-component-api-controlled-changes.js +1 -1
- package/rulepacks/jetwco/rules.json +1 -1
- package/rules/jaf/jaf-sys-age.js +6 -0
- package/rules/jaf/jaf-ts-walk.js +6 -0
- package/rules/jaf/msgid.json +1 -1
- package/rules/jaf/rules.json +1 -1
- package/rules/jet/helpers/extractStylesFromClass.js +1 -1
- package/rules/jet/msgid.json +1 -1
- package/rules/jet/oj-acc-aria-ojselector-labelledby.js +6 -0
- package/rules/jet/oj-acc-aria-prop.js +1 -1
- package/rules/jet/oj-c-acc-avatar-aria-role.js +6 -0
- package/rules/jet/oj-cca-compjson-bp-jetver.js +1 -1
- package/rules/jet/oj-css-style-override.js +1 -1
- package/rules/jet/oj-css-var-override.js +1 -1
- package/rules/jet/oj-html-alta-deprecated.js +1 -1
- package/rules/jet/oj-html-attr-2def.js +1 -1
- package/rules/jet/oj-html-attr-req.js +1 -1
- package/rules/jet/oj-html-cca-tagname.js +1 -1
- package/rules/jet/oj-html-cdn.js +1 -1
- package/rules/jet/oj-html-combo-converter.js +1 -1
- package/rules/jet/oj-html-file-pick-accept.js +1 -1
- package/rules/jet/oj-html-notag-style.js +1 -1
- package/rules/jet/oj-html-ojattr-deprecated.js +1 -1
- package/rules/jet/oj-html-ojattr-enum-deprecated.js +1 -1
- package/rules/jet/oj-html-ojattr-evt-syntax.js +1 -1
- package/rules/jet/oj-html-ojattr-value.js +1 -1
- package/rules/jet/oj-html-ojattr.js +1 -1
- package/rules/jet/oj-html-ojtag-deprecated.js +1 -1
- package/rules/jet/oj-html-pageopts-type.js +6 -0
- package/rules/jet/oj-html-rating-gauge-size.js +6 -0
- package/rules/jet/oj-html-redwood-bp-endslot.js +6 -0
- package/rules/jet/oj-html-slot-deprecated.js +6 -0
- package/rules/jet/oj-html-slot-pref-content.js +1 -1
- package/rules/jet/oj-html-wctag-maintenance.js +6 -0
- package/rules/jet/rules.json +1 -1
- package/schema/component-schema.json +1 -1482
- package/src/JafCore.js +1 -1
- package/types/index.d.ts +38 -9
- package/lib/colors.js +0 -6
package/jaf.js
CHANGED
|
@@ -4,4 +4,4 @@
|
|
|
4
4
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
5
5
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
6
6
|
*/
|
|
7
|
-
(function(){const ac=require("./src/JafCore");var nd={fs:require("fs"),path:require("path"),glob:require("glob"),process:process,os:require("os"),decomment:require("strip-json-comments"),decache:require("decache"),Config:require("./lib/Config"),metaLoader:require("./lib/metaLoader"),ruleLoader:require("./lib/ruleLoader"),msgidLoader:require("./lib/msgidLoader"),jsonLoader:require("./lib/JsonLoader"),Components:require("./lib/Components"),ComponentSvcs:require("./lib/ComponentSvcs"),schema:require("./lib/schema"),builtinpacks:require("./lib/builtinpacks"),extends:require("./lib/extends"),tsparse:require("@typescript-eslint/typescript-estree"),scaffold:require("./lib/scaffold.js"),scaffoldRule:require("./lib/scaffoldRule.js"),fsUtils:require("./lib/FsUtils"),zipUtils:require("./lib/ZipUtils"),
|
|
7
|
+
(function(){const ac=require("./src/JafCore");var nd={fs:require("fs"),path:require("path"),glob:require("glob"),process:process,os:require("os"),decomment:require("strip-json-comments"),decache:require("decache"),Config:require("./lib/Config"),metaLoader:require("./lib/metaLoader"),ruleLoader:require("./lib/ruleLoader"),msgidLoader:require("./lib/msgidLoader"),jsonLoader:require("./lib/JsonLoader"),Components:require("./lib/Components"),ComponentSvcs:require("./lib/ComponentSvcs"),schema:require("./lib/schema"),builtinpacks:require("./lib/builtinpacks"),extends:require("./lib/extends"),tsparse:require("@typescript-eslint/typescript-estree"),scaffold:require("./lib/scaffold.js"),scaffoldRule:require("./lib/scaffoldRule.js"),fsUtils:require("./lib/FsUtils"),zipUtils:require("./lib/ZipUtils"),ojetUtils:require("./lib/OjetLib"),Watch:require("./lib/Watch"),colors:require("./lib/Color"),Cli:require("./lib/Cli"),jetver:require("./lib/jetver"),exportRules:require("./lib/exportRules"),spinner:require("./lib/spinnernoop")};let rc=new ac(nd).start();if(rc!==99){process.exit(rc)}})();
|
package/jafapi.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 Jaf=function(){this._audit=require("./src/JafCore");this._api=require("./lib/api");this.
|
|
6
|
+
var Jaf=function(){this._audit=require("./src/JafCore");this._api=require("./lib/api");this._nd={fs:require("fs"),path:require("path"),glob:require("glob"),process:process,os:require("os"),decomment:require("strip-json-comments"),decache:require("decache"),Config:require("./lib/Config"),metaLoader:require("./lib/metaLoader"),ruleLoader:require("./lib/ruleLoader"),msgidLoader:require("./lib/msgidLoader"),jsonLoader:require("./lib/JsonLoader"),Components:require("./lib/Components"),ComponentSvcs:require("./lib/ComponentSvcs"),schema:require("./lib/schema"),builtinpacks:null,extends:require("./lib/extends"),tsparse:require("@typescript-eslint/typescript-estree"),fsUtils:require("./lib/FsUtils"),zipUtils:require("./lib/ZipUtils"),jetver:require("./lib/jetver"),exportRules:require("./lib/exportRules"),spinner:require("./lib/spinnernoop")};this._audit=new this._audit(this._nd,"api");this._api=new this._api(this._nd,this._audit);this._error=1};Jaf.prototype.initSync=function(config,cbIssue,cbMsg,cbSummary){this._error=this._api.startSync({config:config,cbIssue:cbIssue,cbMsg:cbMsg,cbSummary:cbSummary});return this._error};Jaf.prototype.init=function(config){var _self=this;return new Promise((resolve,reject)=>{_self._api.start(()=>{config:config}).then(result=>{_self._error=result;resolve(result)}).catch(error=>{reject(error)})})};Jaf.prototype.auditSync=function(filespec){var i,rc=this._error;if(!this._error){if(this._audit._regListenerTypesSet){return rc}if(Array.isArray(filespec)&&filespec.length){for(i=0;i<filespec.length;i++){rc=this._api.auditSync(filespec[i])}}else{rc=this._api.auditSync(filespec)}}return rc};Jaf.prototype.audit=function(filespec){var _self;_self=this;return new Promise(function(resolve,reject){if(_self._error){reject(_self._error)}else{_self._api.audit(filespec).then(resultObj=>{resolve(resultObj)}).catch(err=>{throw err})}})};Jaf.prototype.on=function(evName,fn,extra){this._api.on(evName,fn,extra);return this};Jaf.prototype.removeAllListeners=function(evName){this._api.removeAllListeners(evName);return this};Jaf.prototype.removeListener=function(evName,fn){this._api.removeListener(evName,fn);return this};Jaf.prototype.getDescription=function(issue,short){return this._api.getDescription(issue,short)};Jaf.prototype.getActiveRulesetInfo=function(fmt){fmt=fmt!=="json"&&fmt!=="prose"&&fmt!=="sonar"?"json":fmt;return this._api.getRulesetInfo(fmt,true)};Jaf.prototype.setCallbacks=function(fnIssue,fnMsg,fnSummary){this._audit.setApiCallbacks(fnIssue,fnMsg,fnSummary)};Jaf.prototype.enableMsgId=function(msgid,state){return this._api.enableMsgId(msgid,state)};Jaf.prototype.getConfig=function(){return this._api.getConfig()};Jaf.prototype.getSevLib=function(){return this._api.getSevLib()};Jaf.prototype.enableRule=function(ruleName,state){return this._api.enableRule(ruleName,state)};Jaf.prototype.getInfo=function(){return this._api.getInfo()};Jaf.prototype.getMarker=function(){return this._api.getMarker()};Jaf.prototype.setMarker=function(mark){return this._api.setMarker(mark)};Jaf.prototype.setVsCodeExtHint=function(isVsCodeExt){isVsCodeExt=isVsCodeExt!==undefined?!!isVsCodeExt:true;return this._api.setVsCodeExtHint(isVsCodeExt)};module.exports=Jaf;
|
package/lib/AST_Ts.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 NT=require("./AstNodeTypes");const Scope=require("./Scope");const COMMON_DOC_METHODS={"getElementsByClassName":true,"getElementsByTagName":true,"getElementsByTagNameNS":true,"getElementById":true,"getElementsByName":true,"querySelector":true,"querySelectorAll":true,"createElement":true,"createElementNS":true};const LOC="loc";const RANGE="range";const PARENT="parent";var AST=function(data,file,fileType,nd,ecmaVer,comments,msgCtx,config){var opts={ecmaVersion:ecmaVer,comment:comments};if(fileType==="tsx"){opts.jsx=true}opts.loc=true;opts.range=true;opts.errorOnUnknownASTType=true;opts.project="D:/vsprojects/JetAuditDev/tsconfig/tsconfig.json";this._ast=nd.tsparse.parse(data,opts);this._data=data;this._file=file;this._scope=null;this._utils=null;this._program=null;this._isComments=comments;this._msgCtx=msgCtx;this._config=config;this._nd=nd};AST.prototype.walk=function(callback){try{this._walkAddParent(callback)}catch(e){console.log(`JAF internal TS WALK ERROR: ${e}`)}};AST.prototype.getAst=function(){return this._ast};AST.prototype.getFilePath=function(){return this._file};AST.prototype.getRawComments=function(){return this._ast.comments};AST.prototype.getNodeFromIndex=function(index){return _getNodeFromIndex2(this._ast,index)};function _getNodeFromIndex2(node,index){var body,n,i,ret=null;if(!node){return null}if(index===node.range[0]){return node}if(index<node.range[0]||index>node.range[1]){return null}if(node.body){body=node.body;if(Array.isArray(body)){for(i=0;i<body.length;i++){n=body[i];if(index<n.range[0]){ret=n}else{ret=_getNodeFromIndex2(n,index)}if(ret){if(ret===-1){ret=null}break}}}else{ret=_getNodeFromIndex2(body,index);if(ret){if(ret===-1){ret=null}}}}else{if(node.type==="IfStatement"){ret=_getNodeFromIndex2(node.consequent,index)}else{ret=node}}return ret};AST.prototype.getUtils=function(){if(!this._utils){this._utils={getBlock:this.getBlock.bind(this),getBody:this.getBody.bind(this),getProgram:this.getProgram.bind(this),getContainingFunctionName:this.getContainingFunctionName.bind(this),isFuncArg:this.isFuncArg.bind(this),getScopes:this._createVarScopes.bind(this),getNodeTypes:_getNodeTypes,isCommonDocApi:this.isCommonDocApi,parseDefine:this.parseDefine.bind(this),parseImport:this.parseImport.bind(this)}}return this._utils};function _getNodeTypes(){return NT};AST.prototype.getBlock=function(node){var block;if(!node){if(!this._program){node=this._ast;if(node.type!==NT.PROGRAM){node=null}this._program=node}else{node=this._program}block=node}else{while(node){if(node.type){if(node.type===NT.BLOCK_STMT||node.type===NT.PROGRAM){block=node;break}}node=node.parent}}return block};AST.prototype.getBody=function(node){var block=this.getBlock(node);return block?block.body:block};AST.prototype.getFunctionBody=function(node){var block;if(!node){if(!this._program){node=this._ast;if(node.type!==NT.PROGRAM){node=null}this._program=node}else{node=this._program}block=node}else{while(node){if(node.type){if(node.type===NT.FUNC_DECLARATION||node.type===NT.PROGRAM){block=node;break}}node=node.parent}}return block};AST.prototype.getProgram=function(){return this._ast.type===NT.PROGRAM?this._ast:null};AST.prototype.getContainingFunctionName=function(node){var body=this.getFunctionBody(node);return body&&body.id?body.id.name:undefined};AST.prototype._createVarScopes=function(){if(!this._scope){this._scope=new Scope(this._msgCtx,this._config,this._nd);this._scopeStacks=this._scope.build(this._ast);this._accessor=this._scope.getAccessor()}return this._accessor};AST.prototype.getData=function(){return this._data};AST.prototype.isFuncArg=function(node,varName){var args,arg,n,j,ret=false;var n=node;while(n.type&&n.type!==NT.FUNC_DECLARATION){n=n.parent;if(!n||!n.type){n=null;break}}if(n){args=n.params;for(j=0;j<args.length;j++){arg=args[j];if(arg.type===NT.IDENTIFIER){if(arg.name===varName){ret=true;break}}}}return ret};AST.prototype.isCommonDocApi=function(method){return COMMON_DOC_METHODS[method]};AST.prototype.parseDefine=function(node,obj){var modules,names,len,i;if(!node.arguments||node.arguments.length<2){return null}modules=node.arguments[0].elements;names=node.arguments[1].params;obj=obj||null;if(modules&&names&&modules.length){len=Math.min(modules.length,names.length);obj=obj?obj:{};for(i=0;i<len;i++){obj[names[i].name]=modules[i].value}}return obj};AST.prototype.parseImport=function(node,obj){var source,specifiers,spec,name,i;obj=obj||{};source=node.source&&node.source.value;if(node.specifiers){specifiers=node.specifiers;for(var i=0;i<specifiers.length;i++){spec=specifiers[i];if((spec.type===NT.IMPORT_DEF_SPECIFIER||spec.type===NT.IMPORT_SPECIFIER)&&spec.local){name=spec.local.name;obj[name]=source}}}return obj};AST.prototype._walkAddParent=function(fn){var stack=[this._ast],i,j,key,len,node,child,subchild;for(i=0;i<stack.length;i+=1){node=stack[i];if(node.type==="Line"||node.type==="EmptyStatement"){continue}fn(node);for(key in node){if(key!==PARENT){if(key===RANGE||key===LOC){continue}child=node[key];if(child instanceof Array){for(j=0,len=child.length;j<len;j+=1){subchild=child[j];if(subchild){subchild.parent=node;stack.push(subchild)}}}else if(child!=void 0&&typeof child.type==="string"){child.parent=node;stack.push(child)}}}}};module.exports=AST;
|
|
6
|
+
const NT=require("./AstNodeTypes");const Scope=require("./Scope");const COMMON_DOC_METHODS={"getElementsByClassName":true,"getElementsByTagName":true,"getElementsByTagNameNS":true,"getElementById":true,"getElementsByName":true,"querySelector":true,"querySelectorAll":true,"createElement":true,"createElementNS":true};const LOC="loc";const RANGE="range";const PARENT="parent";var AST=function(data,file,fileType,nd,ecmaVer,comments,msgCtx,config){var opts={ecmaVersion:ecmaVer,comment:comments};if(fileType==="tsx"){opts.jsx=true}opts.loc=true;opts.range=true;opts.errorOnUnknownASTType=true;opts.project="D:/vsprojects/JetAuditDev/tsconfig/tsconfig.json";this._ast=nd.tsparse.parse(data,opts);this._data=data;this._file=file;this._scope=null;this._utils=null;this._program=null;this._isComments=comments;this._msgCtx=msgCtx;this._config=config;this._nd=nd};AST.prototype.walk=function(callback){try{this._walkAddParent(callback)}catch(e){console.log(`JAF internal TS/TSX WALK ERROR: ${e}`)}};AST.prototype.getAst=function(){return this._ast};AST.prototype.getFilePath=function(){return this._file};AST.prototype.getRawComments=function(){return this._ast.comments};AST.prototype.getNodeFromIndex=function(index){return _getNodeFromIndex2(this._ast,index)};function _getNodeFromIndex2(node,index){var body,n,i,ret=null;if(!node){return null}if(index===node.range[0]){return node}if(index<node.range[0]||index>node.range[1]){return null}if(node.body){body=node.body;if(Array.isArray(body)){for(i=0;i<body.length;i++){n=body[i];if(index<n.range[0]){ret=n}else{ret=_getNodeFromIndex2(n,index)}if(ret){if(ret===-1){ret=null}break}}}else{ret=_getNodeFromIndex2(body,index);if(ret){if(ret===-1){ret=null}}}}else{if(node.type==="IfStatement"){ret=_getNodeFromIndex2(node.consequent,index)}else{ret=node}}return ret};AST.prototype.getUtils=function(){if(!this._utils){this._utils={getBlock:this.getBlock.bind(this),getBody:this.getBody.bind(this),getProgram:this.getProgram.bind(this),getContainingFunctionName:this.getContainingFunctionName.bind(this),isFuncArg:this.isFuncArg.bind(this),getScopes:this._createVarScopes.bind(this),getNodeTypes:_getNodeTypes,isCommonDocApi:this.isCommonDocApi,parseDefine:this.parseDefine.bind(this),parseImport:this.parseImport.bind(this)}}return this._utils};function _getNodeTypes(){return NT};AST.prototype.getBlock=function(node){var block;if(!node){if(!this._program){node=this._ast;if(node.type!==NT.PROGRAM){node=null}this._program=node}else{node=this._program}block=node}else{while(node){if(node.type){if(node.type===NT.BLOCK_STMT||node.type===NT.PROGRAM){block=node;break}}node=node.parent}}return block};AST.prototype.getBody=function(node){var block=this.getBlock(node);return block?block.body:block};AST.prototype.getFunctionBody=function(node){var block;if(!node){if(!this._program){node=this._ast;if(node.type!==NT.PROGRAM){node=null}this._program=node}else{node=this._program}block=node}else{while(node){if(node.type){if(node.type===NT.FUNC_DECLARATION||node.type===NT.PROGRAM){block=node;break}}node=node.parent}}return block};AST.prototype.getProgram=function(){return this._ast.type===NT.PROGRAM?this._ast:null};AST.prototype.getContainingFunctionName=function(node){var body=this.getFunctionBody(node);return body&&body.id?body.id.name:undefined};AST.prototype._createVarScopes=function(){if(!this._scope){this._scope=new Scope(this._msgCtx,this._config,this._file,this._nd);this._scopeStacks=this._scope.build(this._ast);this._accessor=this._scope.getAccessor()}return this._accessor};AST.prototype.getData=function(){return this._data};AST.prototype.isFuncArg=function(node,varName){var args,arg,n,j,ret=false;var n=node;while(n.type&&n.type!==NT.FUNC_DECLARATION){n=n.parent;if(!n||!n.type){n=null;break}}if(n){args=n.params;for(j=0;j<args.length;j++){arg=args[j];if(arg.type===NT.IDENTIFIER){if(arg.name===varName){ret=true;break}}}}return ret};AST.prototype.isCommonDocApi=function(method){return COMMON_DOC_METHODS[method]};AST.prototype.parseDefine=function(node,obj){var modules,names,len,i;if(!node.arguments||node.arguments.length<2){return null}modules=node.arguments[0].elements;names=node.arguments[1].params;obj=obj||null;if(modules&&names&&modules.length){len=Math.min(modules.length,names.length);obj=obj?obj:{};for(i=0;i<len;i++){obj[names[i].name]=modules[i].value}}return obj};AST.prototype.parseImport=function(node,obj){var source,specifiers,spec,name,i;obj=obj||{};source=node.source&&node.source.value;if(node.specifiers){specifiers=node.specifiers;for(var i=0;i<specifiers.length;i++){spec=specifiers[i];if((spec.type===NT.IMPORT_DEF_SPECIFIER||spec.type===NT.IMPORT_SPECIFIER)&&spec.local){name=spec.local.name;obj[name]=source}}}return obj};AST.prototype._walkAddParent=function(fn){var stack=[this._ast],i,j,key,len,node,child,subchild;for(i=0;i<stack.length;i+=1){node=stack[i];if(node.type==="Line"||node.type==="EmptyStatement"){continue}fn(node);for(key in node){if(key!==PARENT){if(key===RANGE||key===LOC){continue}child=node[key];if(child instanceof Array){for(j=0,len=child.length;j<len;j+=1){subchild=child[j];if(subchild){subchild.parent=node;stack.push(subchild)}}}else if(child!=void 0&&typeof child.type==="string"){child.parent=node;stack.push(child)}}}}};module.exports=AST;
|
package/lib/AstJson.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 PROP="P";const RBRACE="}";const LBRACE="{";const LSQUARE="[";const RSQUARE="]";const NUMBER="N";const STRING="S";const BOOL="B";const NULL="NL";const COLON=":";const DQUOTE="\"";const ESCAPE="\\";const COMMA=",";const UNARY_MINUS="-";const $DIGIT="$digit";const EOF="";function AstJson(msgContext){this._msgContext=msgContext};AstJson.prototype.parse=function(data){var ret;this._data=data;this._index=-1;this._row=1;this._col=0;this._curChar=null;this._objStack=[];this._listStack=[];this._curProp=null;this._curObj=null;this._tokValue=null;ret=this._parse();return ret};AstJson.prototype._parse=function(){var tok;do{switch(tok){case STRING:case NUMBER:case BOOL:case NULL:{if(this._curProp){this._curProp.value=this._tokValue}else{this._curProp=this._tokValue}this._curList.push(this._curProp);this._curProp=null;break}case PROP:{this._curProp={name:this._tokValue.rawValue,pos:{row:this._startRow,col:this._startCol,index:this._startIndex}};this._next(COLON);break}case LBRACE:{if(this._curProp){this._curProp.value=this._tokValue}if(this._curObj){this._objStack.push(this._curObj)}this._curObj=this._tokValue;this._curObj.members=[];if(this._curList){if(this._curProp)this._curList.push(this._curProp);else this._curList.push(this._curObj)}this._listStack.push(this._curList);this._curList=this._curObj.members;break}case RBRACE:{if(this._objStack.length){this._curObj=this._objStack.pop()}if(this._listStack.length){this._curList=this._listStack.pop()}break}case LSQUARE:{if(this._curList){this._listStack.push(this._curList)}if(this._curProp){this._curProp.value=this._tokValue;this._curList.push(this._curProp)}else if(this._curList){this._curList.push(this._tokValue)}this._curList=this._tokValue.members;this._curProp=null;break}case RSQUARE:{this._curList=this._listStack.pop();break}}}while((tok=this._getToken())!==EOF);return this._startToken===LBRACE?this._curObj:this._curList};AstJson.prototype._getToken=function(){var s;while(true){s=this._getNextChar();if(s===DQUOTE){this._tokValue=this._getString();this._getTokValue("string",this._tokValue,true);return this._peekNext(COLON)?PROP:STRING}else if(this._isNumber(s)){this._tokValue=this._getNumber(s);this._getTokValue("number",this._tokValue,true);return NUMBER}else if(s==="t"||s==="f"){this._tokValue=this._getBoolean(s);this._getTokValue("boolean",this._tokValue,true);return BOOL}else if(s==="n"){this._tokValue=this._getNull();this._getTokValue("null",this._tokValue,true);return NULL}else if(s===LBRACE){this._tokValue={type:"Object",value:"{",pos:{row:this._row,col:this._col,index:this._index}};if(!this._startToken){this._startToken=LBRACE}return LBRACE}else if(s===RBRACE){return RBRACE}else if(s===LSQUARE){this._tokValue={type:"array",pos:{row:this._row,col:this._col,index:this._index},members:[]};if(!this._startToken){this._startToken=LSQUARE}return LSQUARE}else if(s===RSQUARE){return RSQUARE}else if(s===EOF){return EOF}else if(s===COMMA){continue}else{if(this._msgContext){this._msgContext.assert("JSON -> AST - unexpected char '"+s+"'")}return s}}};AstJson.prototype._getString=function(){var str="",s,inEscape;this._startRow=this._row;this._startCol=this._col;this._startIndex=this._index;while(true){s=this._getChar();if(s===ESCAPE){inEscape=true;continue}if(!inEscape){if(s===DQUOTE){return{value:str,rawValue:str}}}inEscape=false;str+=s}};AstJson.prototype._getNumber=function(s){var str=s;this._startRow=this._row;this._startCol=this._col;this._startIndex=this._index;while(true){s=this._getChar();if(this._isNumber(s)){if(s!==UNARY_MINUS){str+=s;continue}}this._unget();break}return{value:parseInt(str),rawValue:str}};AstJson.prototype._getBoolean=function(s){var ret={};this._startRow=this._row;this._startCol=this._col;this._startIndex=this._index;if(s==="t"){this._next("r");this._next("u");this._next("e");ret.value=true;ret.rawValue="true"}else{this._next("a");this._next("l");this._next("s");this._next("e");ret.value=false;ret.rawValue="false"}return ret};AstJson.prototype._getNull=function(){this._startRow=this._row;this._startCol=this._col;this._startIndex=this._index;this._next("u");this._next("l");this._next("l");return{value:null,rawValue:"null"}};AstJson.prototype._getTokValue=function(type,tokValue,startRc){this._tokValue={type:type,value:this._tokValue.value,rawValue:this._tokValue.rawValue,pos:{row:startRc?this._startRow:this._row,col:startRc?this._startCol:this._col,index:this._startIndex}}};AstJson.prototype._next=function(s){while(true){if(this._getNextChar()===s){break}}};AstJson.prototype._peekNext=function(s){var n,r,c,val,ret=false;n=this._index;r=this._row;c=this._col;if(s===$DIGIT){val=this._getNextChar();ret=!isNaN(parseInt(val,10))}else{ret=this._getNextChar()===s}this._index=n;this._row=r;this._col=c;return ret};AstJson.prototype._getNextChar=function(){var s;while(true){s=this._getChar();if(s===EOF){return EOF}if(!_isWhite(s)){return s}}};AstJson.prototype._getChar=function(){if(!this._doNotadvance){this._index=this._index>=0?++this._index:0}else{this._unget=false}if(this._index<this._data.length){this._curChar=this._data.substr(this._index,1);if(this._curChar==="\n"){this._row++;this._col=0}else if(this._curChar!=="\r"){this._col++}return this._curChar}return EOF};AstJson.prototype._unget=function(){this._doNotAdvance=true};AstJson.prototype._isNumber=function(s){var num;if(s===UNARY_MINUS){num=this._peekNext($DIGIT);return num>="0"&&num<="9"}return!isNaN(parseInt(s,10))};function _isWhite(s){return s==" "||s==="\n"||s==="\r"||s==="\t"};module.exports=AstJson;
|
|
6
|
+
const PROP="P";const RBRACE="}";const LBRACE="{";const LSQUARE="[";const RSQUARE="]";const NUMBER="N";const STRING="S";const BOOL="B";const NULL="NL";const COLON=":";const DQUOTE="\"";const ESCAPE="\\";const COMMA=",";const UNARY_MINUS="-";const $DIGIT="$digit";const EOF="";function AstJson(msgContext){this._msgContext=msgContext};AstJson.prototype.parse=function(data){var ret;this._data=data;this._index=-1;this._row=1;this._col=0;this._curChar=null;this._objStack=[];this._listStack=[];this._curProp=null;this._curObj=null;this._tokValue=null;ret=this._parse();return ret};AstJson.prototype._parse=function(){var tok;do{switch(tok){case STRING:case NUMBER:case BOOL:case NULL:{if(this._curProp){this._curProp.value=this._tokValue}else{this._curProp=this._tokValue}this._curList.push(this._curProp);this._curProp=null;break}case PROP:{this._curProp={name:this._tokValue.rawValue,pos:{row:this._startRow,col:this._startCol,start:this._startIndex,end:this._getTokEndIndex(this._tokValue.rawValue,this._startIndex,"string"),index:this._startIndex}};this._next(COLON);break}case LBRACE:{if(this._curProp){this._curProp.value=this._tokValue}if(this._curObj){this._objStack.push(this._curObj)}this._curObj=this._tokValue;this._curObj.members=[];if(this._curList){if(this._curProp)this._curList.push(this._curProp);else this._curList.push(this._curObj)}this._listStack.push(this._curList);this._curList=this._curObj.members;break}case RBRACE:{if(this._objStack.length){this._curObj=this._objStack.pop()}if(this._listStack.length){this._curList=this._listStack.pop()}break}case LSQUARE:{if(this._curList){this._listStack.push(this._curList)}if(this._curProp){this._curProp.value=this._tokValue;this._curList.push(this._curProp)}else if(this._curList){this._curList.push(this._tokValue)}this._curList=this._tokValue.members;this._curProp=null;break}case RSQUARE:{this._curList=this._listStack.pop();break}}}while((tok=this._getToken())!==EOF);return this._startToken===LBRACE?this._curObj:this._curList};AstJson.prototype._getToken=function(){var s;while(true){s=this._getNextChar();if(s===DQUOTE){this._tokValue=this._getString();this._getTokValue("string",this._tokValue,true);return this._peekNext(COLON)?PROP:STRING}else if(this._isNumber(s)){this._tokValue=this._getNumber(s);this._getTokValue("number",this._tokValue,true);return NUMBER}else if(s==="t"||s==="f"){this._tokValue=this._getBoolean(s);this._getTokValue("boolean",this._tokValue,true);return BOOL}else if(s==="n"){this._tokValue=this._getNull();this._getTokValue("null",this._tokValue,true);return NULL}else if(s===LBRACE){this._tokValue={type:"Object",value:"{",pos:{row:this._row,col:this._col,start:this._index,end:this._index,index:this._index}};if(!this._startToken){this._startToken=LBRACE}return LBRACE}else if(s===RBRACE){return RBRACE}else if(s===LSQUARE){this._tokValue={type:"array",pos:{row:this._row,col:this._col,start:this._index,end:this._index,index:this._index},members:[]};if(!this._startToken){this._startToken=LSQUARE}return LSQUARE}else if(s===RSQUARE){return RSQUARE}else if(s===EOF){return EOF}else if(s===COMMA){continue}else{if(this._msgContext){this._msgContext.assert("JSON -> AST - unexpected char '"+s+"'")}return s}}};AstJson.prototype._getString=function(){var str="",s,inEscape;this._startRow=this._row;this._startCol=this._col;this._startIndex=this._index;while(true){s=this._getChar();if(s===ESCAPE){inEscape=true;continue}if(!inEscape){if(s===DQUOTE){return{value:str,rawValue:str}}}inEscape=false;str+=s}};AstJson.prototype._getNumber=function(s){var str=s;this._startRow=this._row;this._startCol=this._col;this._startIndex=this._index;while(true){s=this._getChar();if(this._isNumber(s)){if(s!==UNARY_MINUS){str+=s;continue}}this._unget();break}return{value:parseInt(str),rawValue:str}};AstJson.prototype._getBoolean=function(s){var ret={};this._startRow=this._row;this._startCol=this._col;this._startIndex=this._index;if(s==="t"){this._next("r");this._next("u");this._next("e");ret.value=true;ret.rawValue="true"}else{this._next("a");this._next("l");this._next("s");this._next("e");ret.value=false;ret.rawValue="false"}return ret};AstJson.prototype._getNull=function(){this._startRow=this._row;this._startCol=this._col;this._startIndex=this._index;this._next("u");this._next("l");this._next("l");return{value:null,rawValue:"null"}};AstJson.prototype._getTokValue=function(type,tokValue,startRc){this._tokValue={type:type,value:this._tokValue.value,rawValue:this._tokValue.rawValue,pos:{row:startRc?this._startRow:this._row,col:startRc?this._startCol:this._col,start:this._startIndex,end:this._getTokEndIndex(this._tokValue.rawValue,this._startIndex,type),index:this._startIndex}}};AstJson.prototype._next=function(s){while(true){if(this._getNextChar()===s){break}}};AstJson.prototype._peekNext=function(s){var n,r,c,val,ret=false;n=this._index;r=this._row;c=this._col;if(s===$DIGIT){val=this._getNextChar();ret=!isNaN(parseInt(val,10))}else{ret=this._getNextChar()===s}this._index=n;this._row=r;this._col=c;return ret};AstJson.prototype._getNextChar=function(){var s;while(true){s=this._getChar();if(s===EOF){return EOF}if(!_isWhite(s)){return s}}};AstJson.prototype._getChar=function(){if(!this._doNotadvance){this._index=this._index>=0?++this._index:0}else{this._unget=false}if(this._index<this._data.length){this._curChar=this._data.substr(this._index,1);if(this._curChar==="\n"){this._row++;this._col=0}else if(this._curChar!=="\r"){this._col++}return this._curChar}return EOF};AstJson.prototype._unget=function(){this._doNotAdvance=true};AstJson.prototype._getTokEndIndex=function(s,start,type){var end=start;if(type==="string"){end+=2}return end+s.length-1};AstJson.prototype._isNumber=function(s){var num;if(s===UNARY_MINUS){num=this._peekNext($DIGIT);return num>="0"&&num<="9"}return!isNaN(parseInt(s,10))};function _isWhite(s){return s==" "||s==="\n"||s==="\r"||s==="\t"};module.exports=AstJson;
|
package/lib/AstMd.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 parser=require("markdown-it");const PARA_OPEN="paragraph_open";const PARA_CLOSE="paragraph_close";const HEADING_OPEN="heading_open";const HEADING_CLOSE="heading_close";const LINK_OPEN="link_open";const IMAGE="image";const INLINE="inline";const FENCE="fence";const TEXT="text";const UL_OPEN="bullet_list_open";const UL_CLOSE="bullet_list_close";const OL_OPEN="ordered_list_open";const OL_CLOSE="ordered_list_close";const CODE="code";const HTTP="http://";const RE_BRACKET=/\[([^)]+)\].*:/g;const RE_DEL_BRACKET_COLON=/\[|\]|:/g;const RE_REFLINK=/\[[^[]*\]\s*\[([^[]*)\]/;function AstMd(appCtx){this._parser=new parser;this._parser.set({linkify:
|
|
6
|
+
var parser=require("markdown-it");const PARA_OPEN="paragraph_open";const PARA_CLOSE="paragraph_close";const HEADING_OPEN="heading_open";const HEADING_CLOSE="heading_close";const LINK_OPEN="link_open";const IMAGE="image";const INLINE="inline";const FENCE="fence";const TEXT="text";const UL_OPEN="bullet_list_open";const UL_CLOSE="bullet_list_close";const OL_OPEN="ordered_list_open";const OL_CLOSE="ordered_list_close";const CODE="code";const HTTP="http://";const RE_BRACKET=/\[([^)]+)\].*:/g;const RE_DEL_BRACKET_COLON=/\[|\]|:/g;const RE_REFLINK=/\[[^[]*\]\s*\[([^[]*)\]/;function AstMd(appCtx){this._parser=new parser;this._parser.set({linkify:appCtx.config.getMarkdownOptions().linkify});this._appCtx=appCtx;this._utils=appCtx.utils;this._state={};this._links=[];this._paras=[];this._images=[];this._code=[];this._lists=[];this._refLinks=undefined;this._lineMap=new Map};AstMd.prototype.parse=function(data){var state=this._state;state.para=state.heading=state.list=false;state.level=0;state.listType=undefined;this._curListItem=null;this._listsStack=[];this._listItemStack=[];this._stateStack=[];this._mapStack=[];this._links.length=this._paras.length=this._images.length=this._code.length=this._lists.length=0;this._refLinks={};this._ast=this._parser.parse(data,{});this._data=data;this._loadLineMap();return this._ast};AstMd.prototype.createHandler=function(){this._createHandlerContent();return{getLinks:this._getLinks.bind(this),getParas:this._getParas.bind(this),getImages:this._getImages.bind(this),getCode:this._getCode.bind(this),getLists:this._getLists.bind(this),getRefLinks:this._getRefLinks.bind(this),test:this._testParas.bind(this),getLine:this._getLine.bind(this),getLineDisp:this._getLineDisp.bind(this),getLineMap:this._getLineMap.bind(this)}};AstMd.prototype._createHandlerContent=function(){this._createRefs();this._walkChildren(this._ast,this._state)};AstMd.prototype._walkChildren=function(ast,state){var i,o,txt,link,refLink,obj,pos,pos2,start;for(i=0;i<ast.length;i++){o=ast[i];if(o.type===PARA_OPEN&&!state.list){state.para=true;this._map=this._setPos(o.map)}else if(o.type===PARA_CLOSE&&!state.list){state.para=false}else if(o.type===HEADING_OPEN&&!state.list){state.heading=true;this._map=this._setPos(o.map);state.level=_getLevel(o.tag)}else if(o.type===HEADING_CLOSE&&!state.list){state.heading=false;state.level=0}else if(o.type===UL_OPEN||o.type===OL_OPEN){if(this._curListItem){this._listItemStack.push(this._curListItem);this._stateStack.push(state);this._listsStack.push(this._lists);this._lists=this._curListItem.items[this._curListItem.items.length-1].children=[];state={};this._mapStack.push(this._map);this._map=this._setPos(o.map)}state.list=true;state.listType=o.tag;this._map=this._setPos(o.map);pos=this._lineMap.get(o.map[0]+1);pos2=null;if(o.map[0]+1<o.map[1]){pos2=this._lineMap.get(o.map[1])}this._curListItem={ordered:state.listType==="ol",items:[],pos:[{line:o.map[0]+1,start:pos.start,end:pos.end}]};if(pos2){this._curListItem.pos.push({line:o.map[1],start:pos2.start,end:pos2.end})}}else if(o.type===UL_CLOSE||o.type===OL_CLOSE){state.list=false;state.listType=undefined;this._lists.push(this._curListItem);this._curListItem=null;if(this._listItemStack.length){this._curListItem=this._listItemStack.pop();this._lists=this._listsStack.pop();state=this._stateStack.pop();this._map=this._mapStack.pop()}}else if(o.type===INLINE){if(state.list){this._curListItem.items.push({item:o.children[0].content})}else if(state.para||state.heading){pos=this._lineMap.get(o.map[0]+1);pos2=null;if(o.map[0]+1<o.map[1]){pos2=this._lineMap.get(o.map[1])}obj={level:state.level,text:o.content,pos:[{line:o.map[0]+1,start:pos.start,end:pos.end}]};if(pos2){obj.pos.push({line:o.map[1],start:pos2.start,end:pos2.end})}this._paras.push(obj)}else if(o.content.charAt(0)==="!"){var jj=42}}else if(o.type===LINK_OPEN){let bContinue=true;txt=_peekContent(ast,i,TEXT);link=o.attrs[0][1];if(this._map){pos=this._getColsExtent(txt?txt:link)}if(o.markup==="linkify"){let t=ast[i+1].content;if(t.toLowerCase().endsWith(".md")&&!t.startsWith("http")){bContinue=false}}if(bContinue){if(refLink=this._isRefLink(pos.line)){pos=this._getRefLinkPos(pos.line,refLink);obj={text:txt||null,inline:false,refKey:refLink,pos:pos}}else{start=this._getLineDisp(pos.line,pos.col);obj={inline:true,link:link,text:txt||null,pos:{line:pos.line,col:pos.col,start:start,end:start+=link.length-1}}}this._links.push(obj)}}else if(o.type===IMAGE){link=o.attrs[0][1];pos=this._getColsExtent(link);start=this._getLineDisp(pos.line,pos.col);obj={alt:o.content,pos:{line:pos.line,col:pos.col,start:start,end:start+=link.length-1}};if(this._refLinks[link]){obj.inline=false,obj.refKey=link}else{obj.inline=true,obj.link=link}this._images.push(obj)}else if(o.type===FENCE&&o.tag===CODE){pos=this._lineMap.get(o.map[0]+1);pos2=null;if(o.map[0]+1<o.map[1]){pos2=this._lineMap.get(o.map[1])}obj={code:o.content,pos:[{line:o.map[0]+1,start:pos.start,end:pos.end}]};if(pos2){obj.pos.push({line:o.map[1],start:pos2.start,end:pos2.end})}this._code.push(obj)}if(o.children){this._walkChildren(o.children,state)}}};AstMd.prototype._getLinks=function(){return this._links};AstMd.prototype._getParas=function(){return this._paras};AstMd.prototype._getImages=function(){return this._images};AstMd.prototype._getCode=function(){return this._code};AstMd.prototype._getLists=function(){return this._lists};AstMd.prototype._getRefLinks=function(){return this._refLinks};AstMd.prototype._getLineMap=function(){return this._lineMap};AstMd.prototype._testParas=function(regexp,firstMatch){var ret=null;var paras=this._getParas();try{for(let i=0;i<paras.length;i++){regexp.lastIndex=0;if(regexp.test(paras[i].text)){if(!ret){ret=[]}ret.push(paras[i]);if(firstMatch){break}}}}catch(e){}return ret?ret:null};AstMd.prototype._getColsExtent=function(txt){var lineNum,line,txt2,x=-1;for(lineNum=this._map[0];lineNum<=this._map[1];lineNum++){line=this._getLine(lineNum);line=line.replace(/\\/g,"");if(txt.startsWith(HTTP)){txt2=txt.substring(HTTP.length)}if((x=line.indexOf(txt))<0){if(txt2){x=line.indexOf(txt2)}}if(x>=0){return{line:lineNum,col:x+1}}}return null};AstMd.prototype._getLineDisp=function(lineNum,col){var ret=-1;if(lineNum<=this._lineMap.size){ret=this._lineMap.get(lineNum).start;if(typeof col==="number"){ret+=col-1}}return ret};AstMd.prototype._getLine=function(lineNum){var start,end,line,pos;;if(lineNum<=this._lineMap.size){pos=this._lineMap.get(lineNum);start=pos.start;end=pos.end;line=this._data.substring(start,end+1)}return line};AstMd.prototype._isRefLink=function(line){var line=this._getLine(line);var match=line.match(RE_REFLINK);return match?match[1]:null};AstMd.prototype._getRefLinkPos=function(lineNum,refLink){var line=this._getLine(lineNum);var x=line.indexOf(refLink);var pos=this._lineMap.get(lineNum);var start=pos.start+x;return{line:lineNum,col:x+1,start:start,end:start+refLink.length-1}};AstMd.prototype._setPos=function(ar){return[ar[0]+1,ar[1]]};AstMd.prototype._loadLineMap=function(){let data,map,line=1,lastDisp,i;this._lineMap.clear();data=this._data;map=this._lineMap;if(data.length){lastDisp=0;for(i=0;i<data.length;i++){if(data.charAt(i)==="\n"){map.set(line++,{start:lastDisp,end:i});lastDisp=i+1;if(lastDisp===data.length){return map}}}map.set(line,{start:lastDisp,end:i-1})}return map};AstMd.prototype._createRefs=function(){var line,col,match,ref,start,i,j,x;var link,title,obj;var lineCount=this._lineMap.size;for(i=1;i<=lineCount;i++){line=this._getLine(i);if((x=this._utils.eatWhitespace(line,0))<0){continue}if(line.charAt(x)==="["){if(match=line.match(RE_BRACKET)){match=match[0];j=match.indexOf(":");match=match.substring(0,j+1);ref=match.replace(RE_DEL_BRACKET_COLON,"").trim();x+=match.length;link=line.substr(x).trim();title=undefined;if(link.charAt(0)==="<"){j=link.indexOf(">",1);if(j>=0){title=link.substring(j+1).trim();title=title.replace(/[\'\\(\)"']*/g,"");link=link.substring(1,j)}}else{if((j=this._utils.getIndexToWhitespace(link))>=0){title=link.substring(j+1).trim();title=title.replace(/[\"\'"]/g,"");link=link.substring(0,j)}}col=x+1;for(j=x;j<line.length;j++){if(this._utils.isWhitespace(line.charAt(j))){col++}else{break}}start=this._getLineDisp(i,col);obj={link:link,pos:{line:i,col:col,start:start,end:start+link.length-1}};if(title){obj.title=title}this._refLinks[ref]=obj}}}};function _peekContent(ast,i,type){var o,ret;if(ast[i].markup!=="linkify"){o=ast[i+1];if(o.type===type){ret=o.content}}return ret?ret:""};function _getLevel(level){var val=0;if(level.charAt(0)==="h"){val=level.charCodeAt(1)-48}return val};module.exports=AstMd;
|
package/lib/AstNodeTypes.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
|
-
module.exports.ARRAY_EXPR="ArrayExpression";module.exports.ARROW_FUNC_EXPR="ArrowFunctionExpression";module.exports.ASSIGN_PATTERN="AssignmentPattern";module.exports.ASSIGN_EXPR="AssignmentExpression";module.exports.ASSIGNMENT_EXPR="AssignmentExpression";module.exports.AWAIT_EXPR="AwaitExpression";module.exports.BINARY_EXPR="BinaryExpression";module.exports.BLOCK_STMT="BlockStatement";module.exports.BREAK_STMT="BreakStatement";module.exports.CALL_EXPR="CallExpression";module.exports.CATCH_CLAUSE="CatchClause";module.exports.CLASS_BODY="ClassBody";module.exports.CLASS_DECLARATION="ClassDeclaration";module.exports.CLASS_EXPR="ClassExpression";module.exports.CLASS_PROP="ClassProperty";module.exports.CONDITIONAL_EXPR="ConditionalExpression";module.exports.CONTINUE_STMT="ContinueStatement";module.exports.DO_WHILE_STMT="DoWhileStatement";module.exports.DEBUG_STMT="DebuggerStatement";module.exports.EMPTY_STMT="EmptyStatement";module.exports.EX_REST_PROP="ExperimentalRestProperty";module.exports.EX_SPREAD_STMT="ExperimentalSpreadProperty";module.exports.EXPR_STMT="ExpressionStatement";module.exports.FOR_STMT="ForStatement";module.exports.FOR_IN_STMT="ForInStatement";module.exports.FOR_OF_STMT="ForOfStatement";module.exports.FUNC_DECLARATION="FunctionDeclaration";module.exports.FUNC_EXPR="FunctionExpression";module.exports.IDENTIFIER="Identifier";module.exports.IF_STMT="IfStatement";module.exports.LOGIC_EXPR="LogicalExpression";module.exports.LABELED_STMT="LabeledStatement";module.exports.LITERAL="Literal";module.exports.MEMBER_EXPR="MemberExpression";module.exports.META_PROP="MetaProperty";module.exports.METH_DEF="MethodDefinition";module.exports.NEW_EXPR="NewExpression";module.exports.OBJ_EXPR="ObjectExpression";module.exports.OBJ_PATTERN="ObjectPattern";module.exports.PROGRAM="Program";module.exports.PROPERTY="Property";module.exports.REST_ELEM="RestElement";module.exports.RETURN_STMT="ReturnStatement";module.exports.SEQUENCE_EXPR="SequenceExpression";module.exports.SPREAD_ELEM="SpreadElement";module.exports.SUPER="Super";module.exports.SWITCH_CASE="SwitchCase";module.exports.SWITCH_STMT="SwitchStatement";module.exports.TAGGED_TEMPLATE_EXPR="TaggedTemplateExpression";module.exports.TEMPLATE_ELEM="TemplateElement";module.exports.TEMPLATE_LIT="TemplateLiteral";module.exports.THIS_EXPR="ThisExpression";module.exports.THROW_EXPR="ThrowExpression";module.exports.TRY_STMT="TryStatement";module.exports.UNARY_EXPR="UnaryExpression";module.exports.UPDATE_EXPR="UpdateExpression";module.exports.VAR_DECLARATION="VariableDeclaration";module.exports.VAR_DECLARATOR="VariableDeclarator";module.exports.WHILE_STMT="WhileStatement";module.exports.WITH_STMT="WithStatement";module.exports.YIELD_EXPR="YieldExpression";module.exports.JSX_ID="JSXIdentifier";module.exports.JSX_NS_NAME="JSXNamespacedName";module.exports.JSX_EMPTY_EXPR="JSXEmptyExpression";module.exports.JSX_EXPR_CONTAINER="JSXExpressionContainer";module.exports.JSX_ELEM="JSXElement";module.exports.JSX_CLOSING_ELEM="JSXClosingElement";module.exports.JSX_OPENING_ELEM="JSXOpeningElement";module.exports.JSX_ATTRIB="JSXAttribute";module.exports.JSX_SPREAD_ATTRIB="JSXSpreadAttribute";module.exports.JSX_TEXT="JSXText";module.exports.EXPORT_DEFAULT_DECL="ExportDefaultDeclaration";module.exports.EXPORT_NAMED_DECL="ExportNamedDeclaration";module.exports.EXPORT_ALL_DECL="ExportAllDeclaration";module.exports.EXPORT_ASSIGNMENT="TSExportAssignment";module.exports.EXPORT_SPECIFIER="ExportSpecifier";module.exports.IMPORT_DECL="ImportDeclaration";module.exports.IMPORT_EQUALS_DECL="TSImportEqualsDeclaration";module.exports.IMPORT_SPECIFIER="ImportSpecifier";module.exports.IMPORT_DEF_SPECIFIER="ImportDefaultSpecifier";module.exports.IMPORT_NS_SPECIFIER="ImportNamespaceSpecifier";module.exports.ANY_KEYWORD="TSAnyKeyword";module.exports.ARRAY_TYPE="TSArrayType";module.exports.AS_EXPR="TSAsExpression";module.exports.BOOLEAN_KEYWORD="TSBooleanKeyword";module.exports.EXTERN_MOD_REF="TSExternalModuleReference";module.exports.FUNCTION_TYPE="TSFunctionType";module.exports.INTERFACE_BODY="TSInterfaceBody";module.exports.INTERFACE_DECL="TSInterfaceDeclaration";module.exports.INTERSECTION_TYPE="TSIntersectionType";module.exports.LITERAL_TYPE="TSLiteralType";module.exports.NUMBER_KEYWORD="TSNumberKeyword";module.exports.OBJECT_KEYWORD="TSObjectKeyword";module.exports.OPTIONAL_TYPE="TSOptionalType";module.exports.PROPERTY_SIGNATURE="TSPropertySignature";module.exports.STRING_KEYWORD="TSStringKeyword";module.exports.TUPLE_TYPE="TSTupleType";module.exports.TYPE_ALIAS_DECL="TSTypeAliasDeclaration";module.exports.TYPE_LITERAL="TSTypeLiteral";module.exports.TYPE_REF="TSTypeReference";module.exports.UNION_TYPE="TSUnionType";
|
|
6
|
+
module.exports.ARRAY_EXPR="ArrayExpression";module.exports.ARROW_FUNC_EXPR="ArrowFunctionExpression";module.exports.ASSIGN_PATTERN="AssignmentPattern";module.exports.ASSIGN_EXPR="AssignmentExpression";module.exports.ASSIGNMENT_EXPR="AssignmentExpression";module.exports.AWAIT_EXPR="AwaitExpression";module.exports.BINARY_EXPR="BinaryExpression";module.exports.BLOCK_STMT="BlockStatement";module.exports.BREAK_STMT="BreakStatement";module.exports.CALL_EXPR="CallExpression";module.exports.CATCH_CLAUSE="CatchClause";module.exports.CLASS_BODY="ClassBody";module.exports.CLASS_DECLARATION="ClassDeclaration";module.exports.CLASS_EXPR="ClassExpression";module.exports.CLASS_PROP="ClassProperty";module.exports.CONDITIONAL_EXPR="ConditionalExpression";module.exports.CONTINUE_STMT="ContinueStatement";module.exports.DO_WHILE_STMT="DoWhileStatement";module.exports.DEBUG_STMT="DebuggerStatement";module.exports.EMPTY_STMT="EmptyStatement";module.exports.EX_REST_PROP="ExperimentalRestProperty";module.exports.EX_SPREAD_STMT="ExperimentalSpreadProperty";module.exports.EXPR_STMT="ExpressionStatement";module.exports.FOR_STMT="ForStatement";module.exports.FOR_IN_STMT="ForInStatement";module.exports.FOR_OF_STMT="ForOfStatement";module.exports.FUNC_DECLARATION="FunctionDeclaration";module.exports.FUNC_EXPR="FunctionExpression";module.exports.IDENTIFIER="Identifier";module.exports.IF_STMT="IfStatement";module.exports.LOGIC_EXPR="LogicalExpression";module.exports.LABELED_STMT="LabeledStatement";module.exports.LITERAL="Literal";module.exports.MEMBER_EXPR="MemberExpression";module.exports.META_PROP="MetaProperty";module.exports.METH_DEF="MethodDefinition";module.exports.NEW_EXPR="NewExpression";module.exports.OBJ_EXPR="ObjectExpression";module.exports.OBJ_PATTERN="ObjectPattern";module.exports.PROGRAM="Program";module.exports.PROPERTY="Property";module.exports.REST_ELEM="RestElement";module.exports.RETURN_STMT="ReturnStatement";module.exports.SEQUENCE_EXPR="SequenceExpression";module.exports.SPREAD_ELEM="SpreadElement";module.exports.SUPER="Super";module.exports.SWITCH_CASE="SwitchCase";module.exports.SWITCH_STMT="SwitchStatement";module.exports.TAGGED_TEMPLATE_EXPR="TaggedTemplateExpression";module.exports.TEMPLATE_ELEM="TemplateElement";module.exports.TEMPLATE_LIT="TemplateLiteral";module.exports.THIS_EXPR="ThisExpression";module.exports.THROW_EXPR="ThrowExpression";module.exports.TRY_STMT="TryStatement";module.exports.UNARY_EXPR="UnaryExpression";module.exports.UPDATE_EXPR="UpdateExpression";module.exports.VAR_DECLARATION="VariableDeclaration";module.exports.VAR_DECLARATOR="VariableDeclarator";module.exports.WHILE_STMT="WhileStatement";module.exports.WITH_STMT="WithStatement";module.exports.YIELD_EXPR="YieldExpression";module.exports.JSX_ID="JSXIdentifier";module.exports.JSX_NS_NAME="JSXNamespacedName";module.exports.JSX_EMPTY_EXPR="JSXEmptyExpression";module.exports.JSX_EXPR_CONTAINER="JSXExpressionContainer";module.exports.JSX_ELEM="JSXElement";module.exports.JSX_CLOSING_ELEM="JSXClosingElement";module.exports.JSX_OPENING_ELEM="JSXOpeningElement";module.exports.JSX_ATTRIB="JSXAttribute";module.exports.JSX_SPREAD_ATTRIB="JSXSpreadAttribute";module.exports.JSX_TEXT="JSXText";module.exports.EXPORT_DEFAULT_DECL="ExportDefaultDeclaration";module.exports.EXPORT_NAMED_DECL="ExportNamedDeclaration";module.exports.EXPORT_ALL_DECL="ExportAllDeclaration";module.exports.EXPORT_ASSIGNMENT="TSExportAssignment";module.exports.EXPORT_SPECIFIER="ExportSpecifier";module.exports.IMPORT_DECL="ImportDeclaration";module.exports.IMPORT_EQUALS_DECL="TSImportEqualsDeclaration";module.exports.IMPORT_SPECIFIER="ImportSpecifier";module.exports.IMPORT_DEF_SPECIFIER="ImportDefaultSpecifier";module.exports.IMPORT_NS_SPECIFIER="ImportNamespaceSpecifier";module.exports.ANY_KEYWORD="TSAnyKeyword";module.exports.ARRAY_TYPE="TSArrayType";module.exports.AS_EXPR="TSAsExpression";module.exports.BOOLEAN_KEYWORD="TSBooleanKeyword";module.exports.EXTERN_MOD_REF="TSExternalModuleReference";module.exports.ENUM_TS_DECL="TSEnumDeclaration";module.exports.FUNCTION_TYPE="TSFunctionType";module.exports.INTERFACE_BODY="TSInterfaceBody";module.exports.INTERFACE_DECL="TSInterfaceDeclaration";module.exports.INTERSECTION_TYPE="TSIntersectionType";module.exports.LITERAL_TYPE="TSLiteralType";module.exports.NUMBER_KEYWORD="TSNumberKeyword";module.exports.OBJECT_KEYWORD="TSObjectKeyword";module.exports.OPTIONAL_TYPE="TSOptionalType";module.exports.PROPERTY_SIGNATURE="TSPropertySignature";module.exports.STRING_KEYWORD="TSStringKeyword";module.exports.TUPLE_TYPE="TSTupleType";module.exports.TYPE_ALIAS_DECL="TSTypeAliasDeclaration";module.exports.TYPE_LITERAL="TSTypeLiteral";module.exports.TYPE_REF="TSTypeReference";module.exports.UNION_TYPE="TSUnionType";
|
package/lib/Cli.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2018, 2022, Oracle and/or its affiliates.
|
|
3
|
+
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
|
+
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
|
+
*/
|
|
6
|
+
const _cmdLine=require("./cmdline");const SUP="\xB9";const ENV_JAF_COLOR="JAF_COLOR";const ENV_JAF_COLOUR="JAF_COLOUR";var Cli=function(nd,cwd,appCtx){this._nd=nd;this._cwd=cwd;this._appCtx=appCtx;this._utils=appCtx.utils;this._fsUtils=appCtx.fsUtils;this._rtf=null;this._clr=appCtx.colors;this._manual=null;this._groupList=null};Cli.prototype.checkArgs=function(rtf,fnShowVersion){this._rtf=rtf;this._showVersion=fnShowVersion;return _cmdLine.checkArgs(this._nd,rtf,this.showHelp.bind(this),fnShowVersion,this._appCtx)};Cli.prototype.checkImmedCmds=function(rtf){var ret=1;if(rtf.cmdMetaHist){let metahist=require("./metahist");metahist.show(this._nd,this._fsUtils)}else if(rtf.isManual){if(!this._manual){this._manual=require("./manual")}if(this._manual.showBuiltinMsgHelp(this._nd,rtf.manCheckL,rtf.isManPage,this._appCtx)){return 1}ret=-1}else if(rtf.jetverList){this._showJetVerList()}else if(rtf.defList){let defList=require("./deflist");defList.showList(this._nd,this._appCtx.colors)}else if(rtf.cmdNSList){let nslist=require("./nslist");nslist.showNamespaces()}else if(rtf.groupList){if(!this._grouplist){this._grouplist=require("./grouplist")}this._grouplist.showBuiltinGroups(this._nd,rtf.cmdArg,this._appCtx)}else if(rtf.disList){let dislist=require("./dislist");dislist.show(this._nd,rtf.cmdArg,this._appCtx)}else if(rtf.profList){let proflist=require("./proflist");proflist.show(this._nd,rtf.cmdArg,this._appCtx)}else if(rtf.amdList){let amdlist=require("./amdlist");amdlist.show(this._nd,rtf.cmdArg,this._appCtx)}else if(rtf.rloList){let rlolist=require("./rlolist");rlolist.show(this._nd,rtf.cmdArg,this._appCtx)}else if(rtf.betaList){let betalist=require("./betalist");betalist.show(this._nd,rtf.cmdArg,this._appCtx)}else if(rtf.scaffoldRuleSet){return this._nd.scaffoldRule.genRule(this._cwd,rtf.scaffoldRuleSet,this._nd,this._fsUtils)?1:-1}else{ret=0}return ret};Cli.prototype.checkEnvColor=function(){var env,theme;if((env=process.env[ENV_JAF_COLOR])||(env=process.env[ENV_JAF_COLOUR])){env=env.replace(/["']/g,"").toLowerCase().charAt(0);if(env==="y"||env==="t"||env==="d"||env==="l"){theme=env==="l"?"light":"dark"}else{theme="no"}}return theme};Cli.prototype.showExternalGroups=function(ruleSets){if(!this._grouplist){this._grouplist=require("./grouplist")}this._grouplist.showExternalGroups(ruleSets,this._rtf.cmdArg,this._nd,this._appCtx)};Cli.prototype.displayCmdLineOptionsSet=function(){if(this._rtf.verboseMode&&_cmdLine.isCmdLineOptionsSet(this._rtf)){_cmdLine.displayCmdLineOptionsSet(this._rtf,this._appCtx)}};Cli.prototype.showHelp=function(){let help=require("./help");help(this._showVersion,this._appCtx)};Cli.prototype.manualCheckForNonJet=function(rules){if(this._rtf.isManual){if(!this._manual){this._manual=require("./manual")}return this._manual.showExternalMsgHelp(rules,this._rtf.manCheckL,this._rtf.manCheckS,this._nd,this._appCtx)}return false};Cli.prototype._showJetVerList=function(){let keys,ver,a,built,isDefVer,list=this._nd.jetver.getVersions(),indent=" \u2022 ";let clr=this._clr;let sup=clr.BRIGHTYELLOW(SUP);keys=Object.keys(list).sort(function(a,b){var va=a.split(".");var vb=b.split(".");va.forEach(function(v,i,a){a[i]=parseInt(v)});vb.forEach(function(v,i,a){a[i]=parseInt(v)});if(va[0]>vb[0]){return 1}if(va[0]<vb[0]){return-1}if(va[1]>vb[1]){return 1}if(va[1]<vb[1]){return-1}if(va[2]>vb[2]){return 1}if(va[2]<vb[2]){return-1}return 0}).reverse();console.log("\n"+" JET versions supported:");const DEFAULTS=require("./defaults");keys.forEach(function(verName){ver=list[verName];a=verName.split(".");a.forEach(function(s,x){a[x]=parseInt(s)});if(a[0]<10){verName=" "+verName}built=" ("+ver.date+" "+ver.time+")";if(isDefVer=verName===DEFAULTS.JETVER){let def=" Default";built+=clr.BRIGHTYELLOW(def)+sup}verName=isDefVer?clr.BRIGHTYELLOW(verName):clr.CYAN(verName);console.log(indent+verName+built)});let footnote=clr.BRIGHTYELLOW("Default config 'jetVer' value if not specified.");console.log(`\n${sup} ${footnote}`)};Cli.prototype.dumpRules=function(rules,outPath){var ret=false;if(!(this._rtf.dumpRulesSet||this._rtf.dumpRulesJsonSet||this._rtf.dumpRulesSonarSet||this._rtf.dumpRulesInternalSet)){return ret}let ro;if(this._rtf.dumpRulesJsonSet){ro=rules.getRulesJson(true)}else if(this._rtf.dumpRulesSonarSet){ro=rules.getRulesSonar()}else{ro=rules.getRulesProse(this._rtf.dumpRulesInternalSet)}if(ro){if(outPath){let OutFile=require("../lib/outfile");OutFile.writeFileSyncJson(this._nd,outPath,ro)}else{if(this._rtf.dumpRulesJsonSet){console.log(JSON.stringify(ro,null,3))}else{console.log(ro)}}ret=true}return ret};Cli.prototype.displayFinalStats=function(stats,severity,fnConsole,fnInfo,unitTest,useStderr,elapsed){var CliStats=require("./cliStats");var cliStats=new CliStats(this._nd,stats,severity,fnConsole,fnInfo,unitTest,this._appCtx,useStderr);cliStats.displayStatsAndHisto(elapsed);cliStats.displayErrorsAndAsserts()};module.exports=Cli;
|
package/lib/Color.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2018, 2022, Oracle and/or its affiliates.
|
|
3
|
+
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
|
+
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
|
+
*/
|
|
6
|
+
function Clr(){this._theme=this.THEME_DARK;this._enabled=true}Clr.prototype.isColor=function(){return this._enabled};Clr.prototype.enable=function(b){if(b&&!this._enabled){this.BLACK=_fBlack,this.RED=_fRed;this.GREEN=_fGreen;this.BLUE=_fBlue;this.CYAN=_fCyan;this.PINK=_fBoldMagenta;this.MAGENTA=_fMagenta,this.YELLOW=_fYellow;this.BOLD_WHITE=_fBoldWhite,this.BOLD_RED=_fBoldRed;this.BOLD_GREEN=_fBoldGreen;this.BOLD_BLUE=_fBoldBlue;this.BOLD_MAGENTA=_fBoldMagenta;this.BOLD_CYAN=_fBoldCyan;this.BOLD_YELLOW=_fBoldYellow;this.BOLD_BLACK=_fBoldBlack;this.BRIGHTRED=_fBoldRed;this.BRIGHTGREEN=_fBoldGreen;this.BRIGHTBLUE=_fBoldBlue;this.BRIGHTMAGENTA=_fBoldMagenta;this.BRIGHTCYAN=_fBoldCyan;this.BRIGHTYELLOW=_fBoldYellow;this.BRIGHTWHITE=_fBoldWhite;this.BG_BLACK=_fBgBlack;this.BG_RED=_fBgRed;this.BG_GREEN=_fBgGreen,this.BG_YELLOW=_fBgYellow;this.BG_BLUE=_fBgBlue;this.BG_MAGENTA=_fBgMagenta;this.BG_CYAN=_fBgCyan;this.BG_WHITE=_fBgWhite;this.WHITEONBLUE=_fWhiteOnBlue;this.WHITEONRED=_fWhiteOnRed;this.BLACKONRED=_fBlackOnRed;this.INVERT=_fInvert}else if(this._enabled){this.WHITE=this.BLACK=this.RED=this.GREEN=this.BLUE=this.CYAN=this.PINK=this.YELLOW=_nop;this.BOLD_WHITE=this.BOLD_RED=this.BOLD_GREEN=this.BOLD_BLUE=this.BOLD_CYAN=this.BOLD_YELLOW=_nop;this.BRIGHTRED=this.BRIGHTGREEN=this.BRIGHTBLUE=this.BRIGHTCYAN=this.BRIGHTYELLOW=_nop;this.WHITEONBLUE=this.WHITEONRED=this.BLACKONRED=this.INVERT=_nop}this._enabled=b};Clr.prototype.getTheme=function(){return this._theme};Clr.prototype.setTheme=function(theme){if(theme===this.THEME_DARK||theme===this.THEME_LIGHT){if(theme===this.THEME_LIGHT&&this._theme===this.THEME_DARK){this.YELLOW=_fGreen;this.BRIGHTYELLOW=this.BOLDYELLOW=_fGreen;this.BRIGHTCYAN=this.BOLDCYAN=_fBoldBlue;this.BRIGHTWHITE=this.BOLDWHITE=_fBlack;this.CYAN=_fBlue}this._theme=theme}};Clr.prototype.RED=_fRed;Clr.prototype.GREEN=_fGreen;Clr.prototype.BLUE=_fBlue;Clr.prototype.CYAN=_fCyan;Clr.prototype.PINK=_fPink;Clr.prototype.YELLOW=_fYellow;Clr.prototype.WHITE=_fWhite;Clr.prototype.BOLDWHITE=_fBoldWhite;Clr.prototype.BOLDRED=_fBoldRed;Clr.prototype.BOLDGREEN=_fBoldGreen;Clr.prototype.BOLDBLUE=_fBoldBlue;Clr.prototype.BOLDCYAN=_fBoldCyan;Clr.prototype.BOLDYELLOW=_fBoldYellow;Clr.prototype.BOLDBLACK=_fBoldBlack;Clr.prototype.BRIGHTRED=_fBoldRed;Clr.prototype.BRIGHTGREEN=_fBoldGreen;Clr.prototype.BRIGHTBLUE=_fBoldBlue;Clr.prototype.BRIGHTMAGENTA=_fBoldMagenta;Clr.prototype.BRIGHTCYAN=_fBoldCyan;Clr.prototype.BRIGHTYELLOW=_fBoldYellow;Clr.prototype.BRIGHTWHITE=_fBoldWhite;Clr.prototype.WHITEONBLUE=_fWhiteOnBlue,Clr.prototype.WHITEONRED=_fWhiteOnRed,Clr.prototype.BLACKONRED=_fBlackOnRed,Clr.prototype.INVERT=_fInvert,Clr.prototype.THEME_DARK="dark";Clr.prototype.THEME_LIGHT="light";const _color={BLACK:"30m",RED:"31m",GREEN:"32m",YELLOW:"33m",BLUE:"34m",MAGENTA:"35m",PURPLE:"35m",PINK:"95m",CYAN:"36m",WHITE:"37m",BOLD_BLACK:"90m",BOLD_RED:"91m",BOLD_GREEN:"92m",BOLD_YELLOW:"93m",BOLD_BLUE:"94m",BOLD_MAGENTA:"95m",BOLD_CYAN:"96m",BOLD_WHITE:"97m",BG_BLACK:"40m",BG_RED:"41m",BG_GREEN:"42m",BG_YELLOW:"43m",BG_BLUE:"44m",BG_MAGENTA:"45m",BG_PURPLE:"45m",BG_PINK:"95m",BG_CYAN:"46m",BG_WHITE:"47m",BOLD_BG_BLACK:"100m",BOLD_BG_RED:"101m",BOLD_BG_GREEN:"102m",BOLD_BG_YELLOW:"103m",BOLD_BG_BLUE:"104m",BOLD_BG_MAGENTA:"105m",BOLD_BG_CYAN:"106m",BOLD_BG_WHITE:"107m",BRIGHTRED:"91m",BRIGHTGREEN:"92m",BRIGHTYELLOW:"93m",BRIGHTBLUE:"94m",BRIGHTMAGENTA:"95m",BRIGHTCYAN:"96m",BRIGHTWHITE:"97m",WHITEONBLUE:"104m",WHITEONRED:"101m",BLACKONRED:"101;30m",INVERT:"7m"};const START="\x1B[";const RESET="\x1B[0m";function _set(c,s){return c?START+c+s+RESET:s};function _nop(s){return s}function _fRed(s){return _set(_color.RED,s)}function _fGreen(s){return _set(_color.GREEN,s)}function _fBlue(s){return _set(_color.BLUE,s)}function _fCyan(s){return _set(_color.CYAN,s)}function _fYellow(s){return _set(_color.YELLOW,s)}function _fMagenta(s){return _set(_color.MAGENTA,s)}function _fPink(s){return _set(_color.BOLD_MAGENTA,s)}function _fWhite(s){return _set(_color.WHITE,s)};function _fBlack(s){return _set(_color.BLACK,s)}function _fBoldWhite(s){return _set(_color.BOLD_WHITE,s)}function _fBoldRed(s){return _set(_color.BOLD_RED,s)}function _fBoldGreen(s){return _set(_color.BOLD_GREEN,s)}function _fBoldBlue(s){return _set(_color.BOLD_BLUE,s)}function _fBoldMagenta(s){return _set(_color.BOLD_MAGENTA,s)}function _fBoldCyan(s){return _set(_color.BOLD_CYAN,s)}function _fBoldYellow(s){return _set(_color.BOLD_YELLOW,s)}function _fBoldBlack(s){return _set(_color.BOLD_BLACK,s)}function _fBgRed(s){return _set(_color.BG_RED,s)}function _fBgGreen(s){return _set(_color.BG_GREEN,s)}function _fBgBlue(s){return _set(_color.BG_BLUE,s)}function _fBgCyan(s){return _set(_color.BG_CYAN,s)}function _fBgYellow(s){return _set(_color.BG_YELLOW,s)}function _fBgMagenta(s){return _set(_color.BG_MAGENTA,s)}function _fBgWhite(s){return _set(_color.BG_WHITE,s)};function _fBgBlack(s){return _set(_color.BG_BLACK,s)}function _fWhiteOnBlue(s){return _set(_color.WHITEONBLUE,s)};function _fWhiteOnRed(s){return _set(_color.WHITEONRED,s)};function _fBlackOnRed(s){return _set(_color.BLACKONRED,s)};function _fBlackOnRed(s){return _set(_color.BLACKONRED,s)};function _fInvert(s){return _set(_color.INVERT,s)};module.exports=Clr;
|
package/lib/Comments.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 comObj={};const PREFIX="jaf-";const JAF_DISABLE="jaf-disable";const JAF_ENABLE="jaf-enable";const JAF_DISABLE_NEXT_LINE="jaf-disable-next-line";const JAF_DISABLE_LINE="jaf-disable-line";const JAF_GROUP="jaf-group";const CMDS=[JAF_DISABLE,JAF_ENABLE,JAF_DISABLE_LINE,JAF_DISABLE_NEXT_LINE,JAF_GROUP];const EOF=Infinity;function Comments(nodeDeps,rules,msgCtx,utils,isTS){this._rules=rules;this._msgCtx=msgCtx;this._utils=utils;this._isTS=isTS};Comments.prototype.reset=function(fnAst){if(this._comments){this._comments.length=0}if(this._groups){this._groups.length=0}if(fnAst){this._Ast=fnAst;this._data=fnAst.getData();this._rawComments=fnAst.getRawComments();this._processRawComments();if(this._comments&&this._comments.length){this._rationalize()}}};Comments.prototype.isDisabled=function(node){var index,i,c,ret=null;index=this._isTS?node.range[0]:node.start;if(this._comments){for(i=0;i<this._comments.length;i++){c=this._comments[i];if(c.end!=undefined&&index>=c.start&&index<c.end){comObj.rules=c.rules;comObj.invert=c.invert;ret=comObj;break}}}return ret};Comments.prototype._processRawComments=function(){if(this._isTS){this._SetTSRawPositions()}var i,cmd,raw;raw=this._rawComments;if(raw===undefined){this._comments=null;return}for(i=0;i<raw.length;i++){cmd=this._getCmd(raw[i],this._data);if(!cmd){continue}if(cmd){if(cmd.cmd!==JAF_GROUP){if(!this._comments){this._comments=[]}this._comments.push(cmd)}else{if(!this._groups){this._groups={}}this._groups[cmd.group]=cmd.rules}}}};Comments.prototype._SetTSRawPositions=function(){var rcoms,raw,i;rcoms=this._rawComments;for(i=0;i<rcoms.length;i++){raw=rcoms[i];raw.start=raw.range[0];raw.end=raw.range[1]}};Comments.prototype._rationalize=function(){this._dump();this._check1();this._check2();this._check3();this._check4();this._check5();this._check6();this._check7();this._check8();this._compact()};Comments.prototype._check1=function(){var com,i,prev,haveEnable=false,haveDisable=false,a=this._comments;for(i=0;i<a.length;i++){com=a[i];if(com){if(!com.cmd.startsWith(JAF_ENABLE)){break}a[i]=null}}for(i=0;i<a.length;i++){com=a[i];if(!com){continue}if(com.cmd===JAF_ENABLE){haveDisable=false;if(haveEnable){if(!com.rules){a[i]=null;haveEnable=true;continue}haveEnable=false}}else if(com.cmd===JAF_DISABLE){haveEnable=false;if(haveDisable){if(!com.rules){a[i]=null;haveDisable=true;continue}}haveDisable=false}else{haveEnable=haveDisable=false}}haveDisable=false;for(i=0;i<a.length;i++){com=a[i];if(!com){continue}if(com.cmd===JAF_DISABLE){if(haveDisable){if(!prev.rules&&com.rules){a[i]=null}}else{prev=com;haveDisable=true}}else{haveDisable=false}}this._dump("end check1")};Comments.prototype._check2=function(){var a,com,i,j;a=this._comments;for(i=0;i<a.length;i++){com=a[i];if(com&&com.rules){for(j=0;j<com.rules.length;j++){if(!this._rules.isRuleEnabled(com.rules[j])){com.rules.splice(j,1);j--}}if(!com.rules.length){a.splice(i,1);i--}}}this._dump("end check2")};Comments.prototype._check3=function(){var com,i,len;len=this._comments.length;for(i=0;i<len;i++){com=this._comments[i];if(com&&com.cmd===JAF_DISABLE_LINE){com.start=this._utils.eatWhitespace(this._data,com.start)}}this._dump("end check3")};Comments.prototype._check4=function(){var a,com,prev,lastQ,isLast,c,i,j,x,found=false;a=this._comments;for(i=0;i<a.length;i++){com=a[i];if(!com){continue}isLast=i===_getLast(a);if(com.cmd===JAF_DISABLE){if(!com.rules){for(j=i+1;j<a.length;j++){c=a[j];if(!c){continue}if(c.cmd===JAF_ENABLE){found=true;com.end=c.startX;if(!c.rules){a[j]=null;for(x=i+1;x<j;x++){a[x]=null}}else{c.invert=true;c.cmd=JAF_DISABLE;lastQ=c}i=j;break}else if(c.cmd.startsWith(JAF_DISABLE)){if(!c.rules){a[j]=null}else{com.end=c.startX;i--}break}else{a[j]=null}}if(!found){com.end=EOF}found=false}else{i=this._mergeScope(i)}}else if(com.cmd===JAF_DISABLE_NEXT_LINE||com.cmd===JAF_DISABLE_LINE){if(lastQ&&lastQ.end===undefined){lastQ.end=com.startX}}else if(com.cmd===JAF_ENABLE){prev=this._getPrevComment(i);prev=prev>=0?a[prev]:null;if(prev&&prev.cmd===JAF_DISABLE){if(prev.rules&&!isLast){com.cmd=JAF_DISABLE;if(com.rules){_mergeScopeRules(prev,com,true);com.invert=prev.invert}}else{this._comments.splice(i,1);i--}prev.end=com.start}}}this._dump("end check4")};Comments.prototype._check5=function(){var com,stmt,prev,obj,next,i;for(i=0;i<this._comments.length;i++){com=this._comments[i];if(com&&com.cmd===JAF_DISABLE_NEXT_LINE){stmt=this._Ast.getNodeFromIndex(this._utils.eatWhitespace(this._data,com.start));if(stmt){if(this._isTS){com.start=stmt.range[0];com.end=stmt.range[1]}else{com.start=stmt.start;com.end=stmt.end}}else{this._comments[i]=null;continue}prev=this._getPrevComment(i);prev=prev>=0?this._comments[prev]:null;if(prev&&prev.cmd===JAF_DISABLE){if(prev.end===undefined){prev.end=com.start;next=this._getNextComment(i);obj={cmd:JAF_DISABLE,rules:prev.rules,invert:prev.invert,start:com.end+1,end:next?next.start-1:EOF};this._comments.splice(i+1,0,obj);i++}}}}this._dump("end check5")};Comments.prototype._check6=function(){var com,stmt,prev,obj,next,i;for(i=0;i<this._comments.length;i++){com=this._comments[i];if(com&&com.cmd===JAF_DISABLE_LINE){stmt=this._Ast.getNodeFromIndex(this._utils.eatWhitespace(this._data,com.start));if(stmt){if(this._isTS){com.start=stmt.range[0];com.end=stmt.range[1]}else{com.start=stmt.start;com.end=stmt.end}}else{this._comments[i]=null;continue}prev=this._getPrevComment(i);prev=prev>=0?this._comments[prev]:null;if(prev&&prev.cmd===JAF_DISABLE){if(prev.end===undefined){prev.end=com.start;next=this._getNextComment(i);obj={cmd:JAF_DISABLE,rules:prev.rules,invert:prev.invert,start:com.end+1,end:next?next.start-1:EOF};this._comments.splice(i+1,0,obj);i++}}}}this._dump("end check6")};Comments.prototype._check7=function(){var com,prev,i;i=_getLast(this._comments);if(i>=0){com=this._comments[i];if(com.cmd===JAF_ENABLE){prev=this._getPrevComment(i);this._comments.splice(i,1);i--;prev=prev>=0?this._comments[prev]:null;if(prev&&prev.end===undefined){prev.end=com.start}}}this._dump("end check7");return i};Comments.prototype._check8=function(){var com,haveEOF=false,last,i;for(i=0;i<this._comments.length;i++){com=this._comments[i];if(com){last=com;if(com.end===EOF){if(haveEOF){this._comments[i]=null}else{haveEOF=true}}}}if(!haveEOF&&last&&last.cmd!==JAF_ENABLE&&last.end===undefined){if(this._comments.length){this._comments[this._comments.length-1].end=EOF}}this._dump("end check8")};Comments.prototype._compact=function(){var a=this._comments,i;for(i=0;i<a.length;i++){if(!a[i]){a.splice(i,1);i--}}this._dump("end compact",true)};Comments.prototype._mergeScope=function(i){var a,scope,prev,com,isEnable,isLast;a=this._comments;isLast=i===_getLast(a);com=this._comments[i];isEnable=com.cmd===JAF_ENABLE;scope=this._getPrevScope(i);if(scope<0){return i}scope=a[scope];prev=this._getPrevComment(i);prev=a[prev];if(isEnable||prev.rules){if(isEnable){if(!com.rules){prev.end=com.start;this._comments.splice(i,1);return i-1}com.cmd=JAF_DISABLE}if(com.rules){_mergeScopeRules(prev,com,isEnable);prev.end=com.start}}else{if(prev.end){return i}if(prev.cmd!==JAF_DISABLE){return i}this._comments.splice(i,1);i--}return i};function _mergeScopeRules(prev,com,isEnable){var prevRules,comRules,prevRulesLen,comRulesLen,i;prevRules=prev.rules;comRules=com.rules;prevRulesLen=prevRules?prevRules.length:0;comRulesLen=comRules?comRules.length:0;if(isEnable){if(prevRulesLen){for(i=0;i<prevRules.length;i++){if(!comRules.includes(prevRules[i])){comRules.push(prevRules[i])}}com.invert=prev.invert}else{com.invert=true}}else{if(prevRulesLen&&comRulesLen){if(!prev.invert){for(i=0;i<prevRulesLen;i++){if(!comRules.includes(prevRules[i])){comRules.push(prevRules[i])}}}else{for(i=0;i<comRulesLen;i++){var temp=[];if(!comRules.includes(prevRules[i])){temp.push(prevRules[i])}}com.rules=temp;com.invert=true}}}};Comments.prototype._getPrevComment=function(i){var i;for(--i;i>=0;i--){if(this._comments[i]){break}}return i};Comments.prototype._getPrevScope=function(i){var com,i;for(--i;i>=0;i--){com=this._comments[i];if(com&&com.cmd===JAF_DISABLE){break}}return i};Comments.prototype._getNextComment=function(index){var o;while(++index<this._comments.length){o=this._comments[index];if(o)return o}return null};function _getLast(a){var last=-1,i;for(i=a.length-1;i>=0;i--){if(a[i]){last=i;break}}return last};Comments.prototype._getCmd=function(comment,data){var ret=null,value,cmdIndex,x,cmd,rest,rules,a,i,entry,startOfLine=-1;value=comment.value.trim();if(!value.startsWith(PREFIX)){return null}x=this._utils.getIndexToWhitespace(value,0);cmd=x>=0?value.substring(0,x):value;cmdIndex=CMDS.indexOf(cmd);if(cmdIndex<0){return null}if(cmd===JAF_GROUP){return this._getGroup(value,x)}if(cmd===JAF_DISABLE_LINE){startOfLine=_getStartOfLineIndex(data,comment.start)}ret={cmd:cmd,rules:null,start:startOfLine>=0?startOfLine:comment.end,end:undefined,startX:comment.start,endX:comment.end};rest=x>=0?value.substring(x).trim():"";if(rest.length){a=rest.split(",");for(i=0;i<a.length;i++){entry=a[i];if(entry){entry=entry.trim();if(entry){if(!rules){ret.rules=rules=[]}rules.push(entry)}}}}return ret};function _getStartOfLineIndex(data,index){while(index){if(data.charAt(index)==="\n"){return index+1}index--}};Comments.prototype._getGroup=function(value,x){var group,rules,rule,rest,t,i,j,ret,ruleCount=0,x;rest=x>=0?value.substring(x).trim():"";if(!rest.length){return null}x=rest.charAt(0)==="{"?1:0;t=this._getToken(rest,x);if(t.tok==="STRING"){group=rest.substring(x,t.next)}rest=rest.substring(t.next);i=this._expect(rest,":");if(i>=0){i=this._expect(rest,"[",i);if(i>=0){j=rest.indexOf("]",i);if(j>=0){rules=rest.substring(i,j).trim().split(",");if(rules.length){ret={cmd:JAF_GROUP,group:group,rules:[]};for(i=0;i<rules.length;i++){rule=rules[i].trim();if(rule.length){rule=rule.replace(/\"/g,"");if(!/\s/.test(rule)){if(this._isValidRuleName(rule)){ret.rules.push(rule);ruleCount++}}}}if(ruleCount){return ret}}}}}return null};Comments.prototype._expect=function(str,need,x){var t;t=this._getToken(str,x);if(t.tok===need||t.tok===t.value){return t.next}return-1};Comments.prototype._getToken=function(str,x){var c,raw,len,i,j;i=x|0;len=str.length;for(;i<len;i++){c=str[i];if(this._utils.isWhitespace(c)){continue}if(this._isGroupChar(c)){for(j=i+1;j<len;j++){c=str[j];if(this._isGroupChar(c)){continue}raw=str.substring(i,j);return{tok:"STRING",value:raw,next:j}}}else if(this._utils.isDigit(c)){for(j=i+1;j<len;j++){c=str[j];if(this._utils.isAdigit(c)){continue}raw=str.substring(i,j);return{tok:"NUMBER",value:parseInt(raw),raw:raw,next:j}}}else{return{tok:c,value:c,next:i+1}}}return null};Comments.prototype._isGroupChar=function(c){return this._utils.isAlphaNum(c)||c==="-"||c=="_"};Comments.prototype._isValidRuleName=function(rule){var c,i,len,ret=true;len=rule?rule.length:0;for(i=0;i<len;i++){c=rule.charAt(i);if(!this._isGroupChar(c)||i===0&&this._utils.isDigit(c)){ret=false;break}}return ret};Comments.prototype._dump=function(title,newLine){var show=this._msgCtx.isDebug?this._msgCtx.debug:function(){};var i,j,com,rules,s,len;len=this._comments?this._comments.length:0;show("\nComments"+(title?" ("+title+")":"")+": "+(len===0?" - empty":""));for(i=0;i<len;i++){com=this._comments[i];if(!com){show("["+i+"]");continue}s="";rules=com.rules;if(rules){s="[";for(j=0;j<rules.length;j++){if(j){s+=", "}s+=rules[j]}s+="]";s+=com.invert?":invert":""}show("["+i+"] "+com.cmd+(rules?" "+s:""));show(" ("+com.start+", "+(com.end===EOF?"EOF":com.end)+") ["+com.startX+", "+com.endX+"]")}if(newLine)show("\n")};module.exports=Comments;
|
|
6
|
+
const PREFIX="jaf-";const JAF_DISABLE="jaf-disable";const JAF_ENABLE="jaf-enable";const JAF_DISABLE_NEXT_LINE="jaf-disable-next-line";const JAF_DISABLE_LINE="jaf-disable-line";const JAF_GROUP="jaf-group";const CMDS=[JAF_DISABLE,JAF_ENABLE,JAF_DISABLE_LINE,JAF_DISABLE_NEXT_LINE,JAF_GROUP];const EOF=Infinity;function Comments(nodeDeps,rules,msgCtx,utils,isTS){this._rules=rules;this._msgCtx=msgCtx;this._utils=utils;this._isTS=isTS;this._comObj={}};Comments.prototype.reset=function(fnAst){if(this._comments){this._comments.length=0}if(this._groups){this._groups.length=0}if(fnAst){this._Ast=fnAst;this._data=fnAst.getData();this._rawComments=fnAst.getRawComments();this._processRawComments();if(this._comments&&this._comments.length){this._rationalize()}}};Comments.prototype.isDisabled=function(node){var index,i,c,ret=null;index=this._isTS?node.range[0]:node.start;if(this._comments){for(i=0;i<this._comments.length;i++){c=this._comments[i];if(c.end!=undefined&&index>=c.start&&index<c.end){this._comObj.rules=c.rules;this._comObj.invert=c.invert;ret=this._comObj;break}}}return ret};Comments.prototype._processRawComments=function(){if(this._isTS){this._SetTSRawPositions()}var i,cmd,raw;raw=this._rawComments;if(raw===undefined){this._comments=null;return}for(i=0;i<raw.length;i++){cmd=this._getCmd(raw[i],this._data);if(!cmd){continue}if(cmd){if(cmd.cmd!==JAF_GROUP){if(!this._comments){this._comments=[]}this._comments.push(cmd)}else{if(!this._groups){this._groups={}}this._groups[cmd.group]=cmd.rules}}}};Comments.prototype._SetTSRawPositions=function(){var rcoms,raw,i;rcoms=this._rawComments;for(i=0;i<rcoms.length;i++){raw=rcoms[i];raw.start=raw.range[0];raw.end=raw.range[1]}};Comments.prototype._rationalize=function(){this._dump();this._check1();this._check2();this._check3();this._check4();this._check5();this._check6();this._check7();this._check8();this._compact()};Comments.prototype._check1=function(){var com,i,prev,haveEnable=false,haveDisable=false,a=this._comments;for(i=0;i<a.length;i++){com=a[i];if(com){if(!com.cmd.startsWith(JAF_ENABLE)){break}a[i]=null}}for(i=0;i<a.length;i++){com=a[i];if(!com){continue}if(com.cmd===JAF_ENABLE){haveDisable=false;if(haveEnable){if(!com.rules){a[i]=null;haveEnable=true;continue}haveEnable=false}}else if(com.cmd===JAF_DISABLE){haveEnable=false;if(haveDisable){if(!com.rules){a[i]=null;haveDisable=true;continue}}haveDisable=false}else{haveEnable=haveDisable=false}}haveDisable=false;for(i=0;i<a.length;i++){com=a[i];if(!com){continue}if(com.cmd===JAF_DISABLE){if(haveDisable){if(!prev.rules&&com.rules){a[i]=null}}else{prev=com;haveDisable=true}}else{haveDisable=false}}this._dump("end check1")};Comments.prototype._check2=function(){var a,com,i,j;a=this._comments;for(i=0;i<a.length;i++){com=a[i];if(com&&com.rules){for(j=0;j<com.rules.length;j++){if(!this._rules.isRuleEnabled(com.rules[j])){com.rules.splice(j,1);j--}}if(!com.rules.length){a.splice(i,1);i--}}}this._dump("end check2")};Comments.prototype._check3=function(){var com,i,len;len=this._comments.length;for(i=0;i<len;i++){com=this._comments[i];if(com&&com.cmd===JAF_DISABLE_LINE){com.start=this._utils.eatWhitespace(this._data,com.start)}}this._dump("end check3")};Comments.prototype._check4=function(){var a,com,prev,lastQ,isLast,c,i,j,x,found=false;a=this._comments;for(i=0;i<a.length;i++){com=a[i];if(!com){continue}isLast=i===_getLast(a);if(com.cmd===JAF_DISABLE){if(!com.rules){for(j=i+1;j<a.length;j++){c=a[j];if(!c){continue}if(c.cmd===JAF_ENABLE){found=true;com.end=c.startX;if(!c.rules){a[j]=null;for(x=i+1;x<j;x++){a[x]=null}}else{c.invert=true;c.cmd=JAF_DISABLE;lastQ=c}i=j;break}else if(c.cmd.startsWith(JAF_DISABLE)){if(!c.rules){a[j]=null}else{com.end=c.startX;i--}break}else{a[j]=null}}if(!found){com.end=EOF}found=false}else{i=this._mergeScope(i)}}else if(com.cmd===JAF_DISABLE_NEXT_LINE||com.cmd===JAF_DISABLE_LINE){if(lastQ&&lastQ.end===undefined){lastQ.end=com.startX}}else if(com.cmd===JAF_ENABLE){prev=this._getPrevComment(i);prev=prev>=0?a[prev]:null;if(prev&&prev.cmd===JAF_DISABLE){if(prev.rules&&!isLast){com.cmd=JAF_DISABLE;if(com.rules){_mergeScopeRules(prev,com,true);com.invert=prev.invert}}else{this._comments.splice(i,1);i--}prev.end=com.start}}}this._dump("end check4")};Comments.prototype._check5=function(){var com,stmt,prev,obj,next,i;for(i=0;i<this._comments.length;i++){com=this._comments[i];if(com&&com.cmd===JAF_DISABLE_NEXT_LINE){stmt=this._Ast.getNodeFromIndex(this._utils.eatWhitespace(this._data,com.start));if(stmt){if(this._isTS){com.start=stmt.range[0];com.end=stmt.range[1]}else{com.start=stmt.start;com.end=stmt.end}}else{this._comments[i]=null;continue}prev=this._getPrevComment(i);prev=prev>=0?this._comments[prev]:null;if(prev&&prev.cmd===JAF_DISABLE){if(prev.end===undefined){prev.end=com.start;next=this._getNextComment(i);obj={cmd:JAF_DISABLE,rules:prev.rules,invert:prev.invert,start:com.end+1,end:next?next.start-1:EOF};this._comments.splice(i+1,0,obj);i++}}}}this._dump("end check5")};Comments.prototype._check6=function(){var com,stmt,prev,obj,next,i;for(i=0;i<this._comments.length;i++){com=this._comments[i];if(com&&com.cmd===JAF_DISABLE_LINE){stmt=this._Ast.getNodeFromIndex(this._utils.eatWhitespace(this._data,com.start));if(stmt){if(this._isTS){com.start=stmt.range[0];com.end=stmt.range[1]}else{com.start=stmt.start;com.end=stmt.end}}else{this._comments[i]=null;continue}prev=this._getPrevComment(i);prev=prev>=0?this._comments[prev]:null;if(prev&&prev.cmd===JAF_DISABLE){if(prev.end===undefined){prev.end=com.start;next=this._getNextComment(i);obj={cmd:JAF_DISABLE,rules:prev.rules,invert:prev.invert,start:com.end+1,end:next?next.start-1:EOF};this._comments.splice(i+1,0,obj);i++}}}}this._dump("end check6")};Comments.prototype._check7=function(){var com,prev,i;i=_getLast(this._comments);if(i>=0){com=this._comments[i];if(com.cmd===JAF_ENABLE){prev=this._getPrevComment(i);this._comments.splice(i,1);i--;prev=prev>=0?this._comments[prev]:null;if(prev&&prev.end===undefined){prev.end=com.start}}}this._dump("end check7");return i};Comments.prototype._check8=function(){var com,haveEOF=false,last,i;for(i=0;i<this._comments.length;i++){com=this._comments[i];if(com){last=com;if(com.end===EOF){if(haveEOF){this._comments[i]=null}else{haveEOF=true}}}}if(!haveEOF&&last&&last.cmd!==JAF_ENABLE&&last.end===undefined){if(this._comments.length){this._comments[this._comments.length-1].end=EOF}}this._dump("end check8")};Comments.prototype._compact=function(){var a=this._comments,i;for(i=0;i<a.length;i++){if(!a[i]){a.splice(i,1);i--}}this._dump("end compact",true)};Comments.prototype._mergeScope=function(i){var a,scope,prev,com,isEnable,isLast;a=this._comments;isLast=i===_getLast(a);com=this._comments[i];isEnable=com.cmd===JAF_ENABLE;scope=this._getPrevScope(i);if(scope<0){return i}scope=a[scope];prev=this._getPrevComment(i);prev=a[prev];if(isEnable||prev.rules){if(isEnable){if(!com.rules){prev.end=com.start;this._comments.splice(i,1);return i-1}com.cmd=JAF_DISABLE}if(com.rules){_mergeScopeRules(prev,com,isEnable);prev.end=com.start}}else{if(prev.end){return i}if(prev.cmd!==JAF_DISABLE){return i}this._comments.splice(i,1);i--}return i};function _mergeScopeRules(prev,com,isEnable){var prevRules,comRules,prevRulesLen,comRulesLen,i;prevRules=prev.rules;comRules=com.rules;prevRulesLen=prevRules?prevRules.length:0;comRulesLen=comRules?comRules.length:0;if(isEnable){if(prevRulesLen){for(i=0;i<prevRules.length;i++){if(!comRules.includes(prevRules[i])){comRules.push(prevRules[i])}}com.invert=prev.invert}else{com.invert=true}}else{if(prevRulesLen&&comRulesLen){if(!prev.invert){for(i=0;i<prevRulesLen;i++){if(!comRules.includes(prevRules[i])){comRules.push(prevRules[i])}}}else{for(i=0;i<comRulesLen;i++){var temp=[];if(!comRules.includes(prevRules[i])){temp.push(prevRules[i])}}com.rules=temp;com.invert=true}}}};Comments.prototype._getPrevComment=function(i){var i;for(--i;i>=0;i--){if(this._comments[i]){break}}return i};Comments.prototype._getPrevScope=function(i){var com,i;for(--i;i>=0;i--){com=this._comments[i];if(com&&com.cmd===JAF_DISABLE){break}}return i};Comments.prototype._getNextComment=function(index){var o;while(++index<this._comments.length){o=this._comments[index];if(o)return o}return null};function _getLast(a){var last=-1,i;for(i=a.length-1;i>=0;i--){if(a[i]){last=i;break}}return last};Comments.prototype._getCmd=function(comment,data){var ret=null,value,cmdIndex,x,cmd,rest,rules,a,i,entry,startOfLine=-1;value=comment.value.trim();if(!value.startsWith(PREFIX)){return null}x=this._utils.getIndexToWhitespace(value,0);cmd=x>=0?value.substring(0,x):value;cmdIndex=CMDS.indexOf(cmd);if(cmdIndex<0){return null}if(cmd===JAF_GROUP){return this._getGroup(value,x)}if(cmd===JAF_DISABLE_LINE){startOfLine=_getStartOfLineIndex(data,comment.start)}ret={cmd:cmd,rules:null,start:startOfLine>=0?startOfLine:comment.end,end:undefined,startX:comment.start,endX:comment.end};rest=x>=0?value.substring(x).trim():"";if(rest.length){a=rest.split(",");for(i=0;i<a.length;i++){entry=a[i];if(entry){entry=entry.trim();if(entry){if(!rules){ret.rules=rules=[]}rules.push(entry)}}}}return ret};function _getStartOfLineIndex(data,index){while(index){if(data.charAt(index)==="\n"){return index+1}index--}};Comments.prototype._getGroup=function(value,x){var group,rules,rule,rest,t,i,j,ret,ruleCount=0,x;rest=x>=0?value.substring(x).trim():"";if(!rest.length){return null}x=rest.charAt(0)==="{"?1:0;t=this._getToken(rest,x);if(t.tok==="STRING"){group=rest.substring(x,t.next)}rest=rest.substring(t.next);i=this._expect(rest,":");if(i>=0){i=this._expect(rest,"[",i);if(i>=0){j=rest.indexOf("]",i);if(j>=0){rules=rest.substring(i,j).trim().split(",");if(rules.length){ret={cmd:JAF_GROUP,group:group,rules:[]};for(i=0;i<rules.length;i++){rule=rules[i].trim();if(rule.length){rule=rule.replace(/\"/g,"");if(!/\s/.test(rule)){if(this._isValidRuleName(rule)){ret.rules.push(rule);ruleCount++}}}}if(ruleCount){return ret}}}}}return null};Comments.prototype._expect=function(str,need,x){var t;t=this._getToken(str,x);if(t.tok===need||t.tok===t.value){return t.next}return-1};Comments.prototype._getToken=function(str,x){var c,raw,len,i,j;i=x|0;len=str.length;for(;i<len;i++){c=str[i];if(this._utils.isWhitespace(c)){continue}if(this._isGroupChar(c)){for(j=i+1;j<len;j++){c=str[j];if(this._isGroupChar(c)){continue}raw=str.substring(i,j);return{tok:"STRING",value:raw,next:j}}}else if(this._utils.isDigit(c)){for(j=i+1;j<len;j++){c=str[j];if(this._utils.isAdigit(c)){continue}raw=str.substring(i,j);return{tok:"NUMBER",value:parseInt(raw),raw:raw,next:j}}}else{return{tok:c,value:c,next:i+1}}}return null};Comments.prototype._isGroupChar=function(c){return this._utils.isAlphaNum(c)||c==="-"||c=="_"};Comments.prototype._isValidRuleName=function(rule){var c,i,len,ret=true;len=rule?rule.length:0;for(i=0;i<len;i++){c=rule.charAt(i);if(!this._isGroupChar(c)||i===0&&this._utils.isDigit(c)){ret=false;break}}return ret};Comments.prototype._dump=function(title,newLine){var show=this._msgCtx.isDebug?this._msgCtx.debug:function(){};var i,j,com,rules,s,len;len=this._comments?this._comments.length:0;show("\nComments"+(title?" ("+title+")":"")+": "+(len===0?" - empty":""));for(i=0;i<len;i++){com=this._comments[i];if(!com){show("["+i+"]");continue}s="";rules=com.rules;if(rules){s="[";for(j=0;j<rules.length;j++){if(j){s+=", "}s+=rules[j]}s+="]";s+=com.invert?":invert":""}show("["+i+"] "+com.cmd+(rules?" "+s:""));show(" ("+com.start+", "+(com.end===EOF?"EOF":com.end)+") ["+com.startX+", "+com.endX+"]")}if(newLine)show("\n")};module.exports=Comments;
|
package/lib/ComponentSvcs.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 SCHEMA_NAME="component-schema.json";const COMPONENT_JSON="component.json";const COMP_TYPES=["composite","core","pack","reference","resource","vbcs-pattern","vbcs-template"];const SCHEMA_PATH="schema";const RULE_INIT_SCHEMA="jaf-init-schema";const JAF_RSI=0;const RE_FWDSLASHIFY=/\\/g;function ComponentSvcs(nd,metaPath,cfg,tmpDir,appCtx){this._nd=nd;this._error=appCtx.error;this._warn=appCtx.warn;this._debug=appCtx.debug;this._reporter=appCtx.reporter;this._Issue=appCtx.Issue;this._flushIssues=appCtx.flushIssues;this._getMsgId=appCtx.getMsgId;this._rules=appCtx.rules;this._compOptions=cfg.getComponentOptions();this._tempDir=tmpDir;this._schemaName=SCHEMA_NAME;this._schemaPath=nd.path.dirname(metaPath);this._schemaPath=nd.path.dirname(this._schemaPath);this._schemaPath=nd.path.join(this._schemaPath,SCHEMA_PATH,SCHEMA_NAME);this._schemaExists=nd.fs.existsSync(this._schemaPath);this._schemaChecked=true;if(!this._schemaExists&&!this._schemaMsgEmitted){this._error("Schema '"+this._schemaPath+"' not found! Component schema checking disabled.");this._schemaMsgEmitted=true}if(appCtx.debugMode){this._debug("Schema -> "+this._schemaPath)}this._zipUtils=require("./ZipUtils");this._zipUtils=new this._zipUtils(nd)};ComponentSvcs.prototype.loadZip=function(zipPath){return this._zipUtils.loadZip(zipPath)};ComponentSvcs.prototype.getZipContents=function(zipPath){return this._zipUtils.getContents(zipPath)};ComponentSvcs.prototype.extractFileFromZip=function(filePath,zipPath){return this._zipUtils.extractFileFromZip(filePath,zipPath)};ComponentSvcs.prototype.validateComponentJson=function(obj,fromLocation){var name,results,result,issue,ctx,opts,i;if(!obj.name){this._error("component definition at '"+fromLocation+"' has no 'name' property!");return false}else{if(typeof obj.name!=="string"){this._error("custom component at '"+fromLocation+"' has invalid 'name' property!");return false}}opts=this._rules.getRuleOptions(RULE_INIT_SCHEMA,JAF_RSI);if(!opts.enabled){return true}if(!this._schemaExists){return false}name=obj.name;if(!this._compOptions||this._compOptions.applySchema){results=this.validateComponentJsonWithSchema(obj);if(results){fromLocation=fromLocation.replace(/\\/g,"/");this._warn("\nSchema validation of component <"+name+"> : "+results.length+" issue"+(results.length===1?" was":"s were")+" found!
|
|
6
|
+
const SCHEMA_NAME="component-schema.json";const COMPONENT_JSON="component.json";const COMP_TYPES=["composite","core","pack","reference","resource","vbcs-pattern","vbcs-template"];const SCHEMA_PATH="schema";const RULE_INIT_SCHEMA="jaf-init-schema";const JAF_RSI=0;const RE_FWDSLASHIFY=/\\/g;function ComponentSvcs(nd,metaPath,cfg,tmpDir,appCtx){this._nd=nd;this._error=appCtx.error;this._warn=appCtx.warn;this._debug=appCtx.debug;this._reporter=appCtx.reporter;this._Issue=appCtx.Issue;this._flushIssues=appCtx.flushIssues;this._getMsgId=appCtx.getMsgId;this._rules=appCtx.rules;this._compOptions=cfg.getComponentOptions();this._tempDir=tmpDir;this._schemaName=SCHEMA_NAME;this._schemaPath=nd.path.dirname(metaPath);this._schemaPath=nd.path.dirname(this._schemaPath);this._schemaPath=nd.path.join(this._schemaPath,SCHEMA_PATH,SCHEMA_NAME);this._schemaExists=nd.fs.existsSync(this._schemaPath);this._schemaChecked=true;if(!this._schemaExists&&!this._schemaMsgEmitted){this._error("Schema '"+this._schemaPath+"' not found! Component schema checking disabled.");this._schemaMsgEmitted=true}if(appCtx.debugMode){this._debug("Schema -> "+this._schemaPath)}this._fsUtils=appCtx.fsUtils;this._zipUtils=require("./ZipUtils");this._zipUtils=new this._zipUtils(nd,this._fsUtils,appCtx.assert)};ComponentSvcs.prototype.loadZip=function(zipPath){return this._zipUtils.loadZip(zipPath)};ComponentSvcs.prototype.getZipContents=function(zipPath){return this._zipUtils.getContents(zipPath)};ComponentSvcs.prototype.extractFileFromZip=function(filePath,zipPath){return this._zipUtils.extractFileFromZip(filePath,zipPath)};ComponentSvcs.prototype.validateComponentJson=function(obj,fromLocation){var name,results,result,issue,ctx,opts,i;if(!obj.name){this._error("component definition at '"+fromLocation+"' has no 'name' property!");return false}else{if(typeof obj.name!=="string"){this._error("custom component at '"+fromLocation+"' has invalid 'name' property!");return false}}opts=this._rules.getRuleOptions(RULE_INIT_SCHEMA,JAF_RSI);if(!opts.enabled){return true}if(!this._schemaExists){return false}name=obj.pack?obj.pack+"-"+obj.name:obj.name;if(!this._compOptions||this._compOptions.applySchema){results=this.validateComponentJsonWithSchema(obj);if(results){fromLocation=fromLocation.replace(/\\/g,"/");this._warn("\nSchema validation of component <"+name+"> : "+results.length+" issue"+(results.length===1?" was":"s were")+" found!");for(i=0;i<results.length;i++){result=results[i];issue=new this._Issue(result.msg.length?result.msg:JSON.stringify(result.error,null,4));ctx=this._makeIssueContext(fromLocation,RULE_INIT_SCHEMA);issue.msgId=this._getMsgId(ctx,RULE_INIT_SCHEMA);this._rules.getRulePack(ctx._rsi)._setCBCtx(ctx);this._reporter.addIssue(issue,ctx)}this._flushIssues()}}return true};ComponentSvcs.prototype.extractComponentJsonFromZip=function(fpath){var text,obj,ret=null;this._debug("extracting component.json from '"+fpath+"'");ret={obj:null,data:null,msg:null,error:false};text=this._zipUtils.extractFileFromZip(COMPONENT_JSON,fpath);if(typeof text==="string"){if(text.length){ret.data=text;try{ret.obj=JSON.parse(text)}catch(e){ret.msg=e.message}}}else{obj.error=true}return ret};ComponentSvcs.prototype.validateComponentJsonWithSchema=function(obj){return this._nd.schema.validateComponentJson(obj)};ComponentSvcs.prototype.loadUrl=function(url){if(!this._netUtils){this._netUtils=require("./NetUtils");this._netUtils=new this._netUtils}return this._netUtils.loadUrl(url)};ComponentSvcs.prototype.writeZipBufferToFile=function(buffer){var ret;try{this._tmpName=this._zipUtils.createTempZipFilename();ret=this._zipUtils.writeBufferToFile(buffer,this._nd.path.join(this._tempDir,this._tmpName))}catch(e){ret=e}return ret};ComponentSvcs.prototype.getLastZipFilePath=function(){return this._zipUtils.getLastFilepath()};ComponentSvcs.prototype.deleteZipFile=function(filePath){this._zipUtils.deleteFile(filePath)};ComponentSvcs.prototype.isValidType=function(type){return type?COMP_TYPES.indexOf(type)>=0:true};ComponentSvcs.prototype.getSchemaName=function(){return this._schemaName};ComponentSvcs.prototype.stripUrlQuery=function(url){return this._netUtils.stripQuery(url)};ComponentSvcs.prototype._makeIssueContext=function(fromLocation,ruleName){return{filepath:_fwdSlashify(this._nd.path.join(fromLocation,"component.json")),opts:this._rules.getRuleOptions(ruleName,JAF_RSI),rulePack:this._rules.getRulePack(JAF_RSI),_rsi:JAF_RSI,ruleName:ruleName,position:{line:0,col:0,start:0,end:0}}};function _fwdSlashify(path){return path.replace(RE_FWDSLASHIFY,"/")};module.exports=ComponentSvcs;
|
package/lib/Components.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
|
-
"use strict";const COMPONENT_JSON="component.json";const PROP_SLOTS="slots";const PROP_PROPS="props";const PROP_EVENTS="events";const PROP_STYLECLASSES="styleClasses";const PROP_IMPLEMENTS="implements";const PROP_FOLDER="folder";const PROP_VERSION="version";const PROP_UNSUP_THEME="unsupTheme";const PROP_STATUS="status";const PROP_SUBCOMPONENT_TYPE="subcomponentType";const PROP_TYPE="type";const PROP_PACK="pack";const DEPRECATED="deprecated";const PROPERTY_VALUE="propertyValue";const PROPERTY_TYPE="propertyType";const PACK_PRIVATE="packPrivate";const DYNAMIC_FORM_ELEM="DynamicFormElement";const DYNAMIC_TABLE_ELEM="DynamicTableElement";const VB_FRAGMENT_ELEM="VbFragmentElement";const REGXPR=/string|number|object|array|boolean|[\|.<>]/gi;function Components(nd,runMode,compSvcs,urlBase,urls,filePaths,metaLib,jetCore,msgCtx,runOpts,utils){this._nd=nd;this._tagLookup={};this._styleLookup={};this._path=null;this._reqAttrs=null;this._metaLib=metaLib;this._utils=utils;this._compSvcs=compSvcs;this._isAMD=runMode==="amd";this._error=msgCtx.error;this._warn=msgCtx.warn;this._debug=msgCtx.debug;this._info=msgCtx.info;this._msg=msgCtx.msg;this._console=msgCtx.console;this._isDebug=msgCtx.isDebug;this._isVerbose=msgCtx.isVerbose;this._count=0;this._isOk=true;this._runOpts=runOpts;this._init(urlBase,urls,filePaths,jetCore)};Components.prototype.isTag=function(tagName){return!!this._tagLookup[tagName]};Components.prototype.isTagAttr=function(tagName,attrName){return this.isTagProp(tagName,attrName)};Components.prototype.isTagDeprecated=function(tag){var tag,stats,status,ret=null;if(tag=this._tagLookup[_removeChevrons(tag)]){if(stats=tag.status){for(status of stats){if(!status.hasOwnProperty("target")){ret=status;break}}}}return ret};Components.prototype.isTagAttrDeprecated=function(tagName,attrName){var prop,status,stats,o,ret=null;prop=this.getTagProp(tagName,attrName);if(prop&&(stats=prop.status)){ret=[];for(status of stats){if(status.type===DEPRECATED){o={type:DEPRECATED};if(status.hasOwnProperty("target")){o.target=status.target}if(status.hasOwnProperty("description")){o.description=status.description}if(status.hasOwnProperty("since")){o.since=status.since}if(status.hasOwnProperty("value")){o.value=status.value}ret.push(o)}}ret=ret.length?ret:null}return ret};Components.prototype.isTagAttrTranslatable=function(tag,attr){var prop=this.getTagProp(tag,attr);return prop&&prop.translatable};Components.prototype.isTagAttrReadOnly=function(tag,attr){var prop=this.getTagProp(tag,attr);return prop&&prop.readonly};Components.prototype.isTagProp=function(tagName,propName){return!!this.getTagProp(tagName,propName)};Components.prototype.getTagProp=function(tagName,propName){var tag,props;tag=this._tagLookup[_removeChevrons(tagName)];props=tag?tag[PROP_PROPS]:null;if(props){propName=propName.charAt(0)===":"?propName.substring(1):propName;propName=_deCamelCaseProp(propName)}return props?props[propName]:false};Components.prototype.getTagPropType=function(tagName,propName){var prop,ret;if(prop=this.getTagProp(tagName,propName)){ret=prop?prop.type:undefined}return ret};Components.prototype.getTagMetadata=function(tag){return this._tagLookup[_removeChevrons(tag)]};Components.prototype.isTagEvent=function(tagName,eventName){var propName,o,b;o=this._tagLookup[tagName];if(o){if(eventName.startsWith("on-")){b=o.events&&o.events[eventName];if(b)return b;if(o.implements&&(o.implements.includes(DYNAMIC_FORM_ELEM)||o.implements.includes(DYNAMIC_TABLE_ELEM)||o.implements.includes(VB_FRAGMENT_ELEM))){return true}if(eventName.endsWith("-changed")){if(o.props){propName=eventName.replace("-changed","").substring(3);return!!o.props[propName]}}}}return false};Components.prototype.isTagStyle=function(tag,style){if(this._tagLookup[tag]){let tags,styles,sc;if(tags=Object.keys(this._tagLookup)){for(let i=0;i<tags.length;i++){if(styles=this._tagLookup[tags[i]].styleClasses){if(sc=styles[style]){return true}}}}}return false};Components.prototype.isStyle=function(style){return!!this._styleLookup[style]};Components.prototype.getStyleMetadata=function(style){var tag,styles,sc,ret=null;if(tag=this._styleLookup[style]){if(styles=this._tagLookup[tag].styleClasses){if(sc=styles[style]){ret={tag:tag,meta:sc}}}}return ret};Components.prototype.getStyleSelector=function(style){var sm=this.getStyleMetadata(style);return sm&&sm.meta?sm.meta.styleSelector:null};Components.prototype.hasTagSlotName=function(tagName,slotName){var o=this._tagLookup[tagName];return!!(o&&o.slots&&o.slots[slotName])};Components.prototype.getPreferredSlotContent=function(tag,slotName,impls){var o,slot,prefContent=null,comps=null,content;if(this._utils.hasAnyProps(impls)){if(o=this._tagLookup[tag]){if(o.slots){if(slot=o.slots[slotName]){if(prefContent=slot.preferredContent){prefContent.forEach(impl=>{if(content=impls[impl]){if(!comps){comps=[]}comps.push(...content)}})}}}}}return prefContent||comps?{interfaces:prefContent,components:comps}:null};Components.prototype.getTagSlotMetadata=function(tag,slot){var o,ret;if(o=this._tagLookup[tag]){if(o.slots){if(slot=o.slots[slot]){ret=slot}}}return ret};Components.prototype.hasTagAttrValues=function(tagName,attrName){var prop,ret=false;if(prop=this.getTagProp(tagName,attrName)){ret=!!prop.enumValues}return ret};Components.prototype.isTagAttrValue=function(tagName,attrName,value){var prop,ret;if(prop=this.getTagProp(tagName,attrName)){if(prop&&prop.enumValues){ret=prop.enumValues.indexOf(value)>=0}}return ret};Components.prototype.isTagAttrEnumDeprecated=function(tag,attr,val){var prop,stats,status,ret=null;if(prop=this.getTagProp(tag,attr)){if(prop.status){stats=prop.status;for(status of stats){if(status.type===DEPRECATED&&status.target==="propertyValue"){if(status.value&&status.value.includes(val)){ret={type:DEPRECATED};if(status.hasOwnProperty("target")){ret.target=status.target}if(status.hasOwnProperty("description")){ret.description=status.description}if(status.hasOwnProperty("since")){ret.since=status.since}if(status.hasOwnProperty("value")){ret.value=status.value}break}}}}}return ret};Components.prototype.isTagSupportedInTheme=function(tag,theme){var o,unsup,ret=true;o=this._tagLookup[tag];if(o){unsup=o[PROP_UNSUP_THEME];if(unsup){ret=!unsup.includes(theme)}}return ret};Components.prototype.isAttrSupportedInTheme=function(tag,attr,theme){var prop,unsup,ret=true;if(prop=this.getTagProp(tag,attr)){if(unsup=prop[PROP_UNSUP_THEME]){ret=!unsup.includes(theme)}}return ret};Components.prototype.isTagPackPrivate=function(tag){var o,ret;tag=_removeChevrons(tag);if(o=this._tagLookup[tag]){ret=o[PROP_SUBCOMPONENT_TYPE]===PACK_PRIVATE}return ret};Components.prototype.getRequiredAttrs=function(tagName){var tag,props,attr,attrName,obj,ret=null;tagName=_removeChevrons(tagName);if(this._reqAttrs){let r=this._reqAttrs[tagName];if(r){return typeof r==="boolean"?null:r}}tag=this._tagLookup[tagName];if(tag&&tag.props){if(!this._reqAttrs){this._reqAttrs={}}if(!this._reqAttrs[tagName]){this._reqAttrs[tagName]=true}props=tag.props;for(attrName in props){attr=props[attrName];if(attr.required){if(!obj){obj=[]}obj.push(_deCamelCaseProp(attrName))}}}if(obj&&obj.length){this._reqAttrs[tagName]=obj;ret=obj}return ret};Components.prototype.getNames=function(){var name,a=[];for(name in this._tagLookup){a.push({name:name,version:this._tagLookup[name].version})}return a};Components.prototype.getCount=function(){return this._count};Components.prototype.isOk=function(){return this._isOk};Components.prototype._init=function(base,urls,filePaths,jetCore){if(this._isAMD){return}if(base){base=base.trim();if(base.charAt(base.length-1)!=="/"){base=base+"/"}}else{base=""}this._processFilePaths(filePaths);this._processUrls(base,urls);this._createStyleLookup();this._processJetCore(jetCore)};Components.prototype._processFilePaths=function(filePaths){var obj,compEntry,fpath,i,j;if(!filePaths){return}this._console("\nPre-processing user-declared web component metadata...");for(i=0;i<filePaths.length;i++){compEntry=filePaths[i];var dirStack=this._nd.glob.sync(compEntry);for(j=0;j<dirStack.length;j++){fpath=dirStack[j];if(this._runOpts.isDryRun||this._runOpts.isDebug){let msg="-".repeat(70)+"\n"+(this._runOpts.isDryRun?"* ":"")+"processing component path '"+fpath+"' ...";if(this._runOpts.isDryRun){console.log(msg)}else{this._debug(msg)}}if(fpath.toLowerCase().endsWith(".zip")){obj=this._compSvcs._extractComponentJsonFromZip(fpath);if(obj.obj){this.processComponentJson(obj.obj,fpath,true)}else if(obj.msg){this._error("Failed to parse component.json : "+obj.msg+" - "+fpath)}else if(obj.error){this._error("Failed to unzip '"+fpath+"'")}continue}if(this._isComponentJsonPath(fpath)){obj=this._readComponentJson(fpath);if(obj){if(obj.type&&obj.type==="pack"){continue}this.processComponentJson(obj,this._nd.path.dirname(fpath),true)}continue}this._recurse(fpath)}}if(this._isDebug){this._debug("-".repeat(70))}};Components.prototype._recurse=function(fpath){var dirs,inFile,obj,i;try{dirs=this._nd.fs.readdirSync(fpath);if(this._isDebug){this._debug(` processing ${fpath} ${dirs.length} component dirs ...`)}for(i=0;i<dirs.length;i++){inFile=dirs[i];if(inFile===COMPONENT_JSON){inFile=this._nd.path.join(fpath,COMPONENT_JSON);if(this._isDebug){this._debug(" processing "+inFile+"...")}obj=this._readComponentJson(inFile);if(obj){if(!obj.type||obj.type==="composite"){this.processComponentJson(obj,fpath,true)}}else{return}}var curPath=this._nd.path.join(fpath,inFile);if(this._nd.fsUtils.getFileType(curPath)==="d"){this._recurse(curPath)}}}catch(e){this._error("Component check failed - "+e);this._isOk=false}};Components.prototype._processUrls=function(base,urls){var url,i;if(!urls){return}for(i=0;i<urls.length;i++){url=urls[i];if(this._runOpts.isDryRun||this._runOpts.isDebug){let msg;msg="-".repeat(70)+"\nprocessing URL '"+url+"'";if(this._runOpts.isDryRun){console.log(msg);continue}else{this._debug(msg)}}if(_isRelativeUrl(url)){url=base+url;if(_isRelativeUrl(url)){this._error("component URL incomplete - '"+url+"'");continue}}this._processUrl(url)}};Components.prototype._processUrl=function(url){var resp,obj,rc,tempFile,tmp;try{resp=this._compSvcs.loadUrl(url);if(resp.eCode==="ETIMEDOUT"){this._error("config.componentUrls - request timed-out for '"+url+"'");this._isOk=false;return}try{if(resp.type==="json"){if(resp.body){obj=JSON.parse(resp.body);if(!this.processComponentJson(obj,url,false)){this._isOk=false}}else{this._error("Server responded with "+resp.statusCode+" URL: '"+url+"'")}}else if(resp.type=="zip"){rc=this._compSvcs.writeZipBufferToFile(resp.body);if(typeof rc==="boolean"&&rc){tempFile=this._compSvcs.getLastZipFilePath();obj=this._compSvcs.extractComponentJsonFromZip(tempFile);if(obj.obj){this.processComponentJson(obj.obj,url,true)}else if(obj.msg){this._error("Failed to parse component.json : "+obj.msg+" - "+url)}else if(obj.error){this._error("Failed to unzip '"+url+"'")}this._compSvcs.deleteZipFile(tempFile)}else{this._error("Failed to create local temp zip file from URL '"+url+"' : rc.message");this._isOk=false}}else{tmp=typeof resp.type==="string"?resp.type:"?";this._error("Server responded with unexpected data ('"+tmp+"') : '"+url+"'");this._isOk=false}}catch(e){this._error("Invalid JSON - URL '"+url+"' : "+e);this._isOk=false}}catch(e1){this._error("URL access failed "+(e1.message.includes("ENOTFOUND")?"(NOT FOUND)":"")+" - URL '"+url+"'");this._isOk=false}};Components.prototype.processComponentJson=function(obj,fromLocation){var comp,props,events,event,compName;if(!this._isAMD){if(this._runOpts.isDryRun){console.log(" Would have processed '"+fromLocation+"'");return}if(obj.type&&obj.type==="pack"){return this._processJetPack(obj,fromLocation)}if(!this._compSvcs.validateComponentJson(obj,fromLocation)){this._isOk=false;return false}}compName=obj.pack?obj.pack+"-"+obj.name:obj.name;if(this._tagLookup[compName]){this._warn(`Ignoring duplicate component '${compName}' at '${fromLocation}'`);return true}this._tagLookup[compName]=comp={};comp[PROP_FOLDER]=fromLocation;comp[PROP_VERSION]=obj.version;if(obj.slots){comp[PROP_SLOTS]=obj.slots}if(obj.properties){comp[PROP_PROPS]=props={};this._extractProps(props,null,obj.properties,obj.name)}if(obj.events){comp[PROP_EVENTS]=events={};for(event in obj.events){event=_deCamelCaseEvent(event);events[event]=true}}if(obj.implements){comp[PROP_IMPLEMENTS]=obj.implements;this._metaLib.processImplements(compName,obj.implements)}if(obj.extension&&obj.extension.theme&&obj.extension.theme.unsupportedThemes){comp[PROP_UNSUP_THEME]=obj.extension.theme.unsupportedThemes}if(obj.subcomponentType){comp[PROP_SUBCOMPONENT_TYPE]=obj.subcomponentType}if(obj.type){comp[PROP_TYPE]=obj.type}if(obj.pack){comp[PROP_PACK]=obj.pack}if(obj.status){comp[PROP_STATUS]=obj.status}if(obj.styleClasses){comp[PROP_STYLECLASSES]=this._extractStyles(obj.styleClasses)}this._count++;return true};Components.prototype._extractProps=function(propObj,propSoFar,properties,name,rdonly){var prop,newProp,thisProp,soFar,obj;for(prop in properties){newProp=_deCamelCaseProp(prop);soFar=(propSoFar?propSoFar+".":"")+newProp;propObj[soFar]=obj={};thisProp=properties[prop];if(thisProp.hasOwnProperty("enumValues")){if(Array.isArray(thisProp.enumValues)){obj.enumValues=thisProp.enumValues}else{this._error(`Web component'${name}' property '${soFar}' has invalid 'enumValues' in component.json`)}}if(thisProp.hasOwnProperty("status")){obj.status=thisProp.status}if(thisProp.hasOwnProperty("type")){obj.type=thisProp.type}if(thisProp.required){obj.required=true}if(thisProp.extension&&thisProp.extension.theme&&thisProp.extension.theme.unsupportedThemes){obj[PROP_UNSUP_THEME]=thisProp.extension.theme.unsupportedThemes}if(thisProp.hasOwnProperty("translatable")){obj.translatable=true}if(typeof thisProp.readonly==="boolean"){obj.readonly=thisProp.readOnly}else{if(rdonly){obj.readonly=true}}if(thisProp.hasOwnProperty("properties")){obj.properties=true;this._extractProps(propObj,soFar,thisProp.properties,name,obj.readonly)}}};Components.prototype._extractStyles=function(styleClasses){var so,si,obj,ret={},i,j;if(!Array.isArray(styleClasses)){return ret}for(i=0;i<styleClasses.length;i++){so=styleClasses[i];if(so.kind==="class"){ret[so.name]=this._extractStyleClass(so)}else if(so.kind==="set"&&so.styleItems&&Array.isArray(so.styleItems)){ret[so.name]=obj={kind:"set"};if(so.status){obj.status=so.status}obj.styleClasses={};for(j=0;j<so.styleItems.length;j++){si=so.styleItems[j];obj.styleClasses[si.name]=this._extractStyleClass(si)}}else if(so.kind==="template"){}}return ret};Components.prototype._extractStyleClass=function(so){var obj={};if(so.styleSelector){obj.styleSelector=so.styleSelector}if(so.status){obj.status=so.status}return obj};Components.prototype._processJetPack=function(obj,fromLocation){var deps,dep,urlKey,depUrl,msg,i;if(this._runOpts.isDryRun||this._runOpts.isDebug){msg="processing JET Pack "+obj.name+" (version: "+obj.version+") : '"+fromLocation+"'";if(this._runOpts.isDryRun){console.log("* "+msg);return}else{this._debug(msg)}}if(!fromLocation.includes("http")){this._error("JET packs loaded via config 'components' property (file based) are currently not supported");return false}i=fromLocation.indexOf(obj.name);if(i>=0){urlKey=fromLocation.substring(0,i)}else{this._error("Cannot handle Jet Pack URL format to load dependencies : "+fromLocation)}deps=obj.dependencies;if(deps){for(dep in deps){depUrl=urlKey+dep+"/versions/"+obj.dependencies[dep]+"/content/component.json";if(this._isDebug){this._debug(` processing dependency ${dep} ${obj.dependencies[dep]}`)}this._processUrls("",[depUrl])}}return false};Components.prototype._processJetCore=function(jetCorePath){var files,file,obj,i;if(!jetCorePath){return}this._console("-".repeat(70)+"\nPerforming schema analysis on JET Core components (dt) using '"+this._compSvcs.getSchemaName()+"'...");try{files=this._nd.fs.readdirSync(jetCorePath);this._console(` processing ${files.length} $jetCore components...`);for(i=0;i<files.length;i++){file=files[i];if(file.endsWith(".json")){file=this._nd.path.join(jetCorePath,file);try{obj=this._readComponentJson(file);if(obj){this._compSvcs.validateComponentJson(obj,file)}}catch(e){}}}}catch(e1){this._error("!!! $JetCore Component check failed - "+e1)}this._console(" processing "+(files?files.length+" ":"")+"$jetCore components completed");this._console("-".repeat(70))};Components.prototype._createStyleLookup=function(){var tag,o,scl,st;for(tag in this._tagLookup){o=this._tagLookup[tag];if(scl=o.styleClasses){for(st in scl){this._styleLookup[st]=tag}}}};Components.prototype._readComponentJson=function(inFile){var obj=null;if(this._isDebug){this._debug(` loading '${inFile}'`)}obj=this._nd.jsonLoader.load(inFile,this._nd,this._error,false,this._utils);if(!obj){this._isOk=false}return obj};Components.prototype._isComponentJsonPath=function(filePath){return filePath.toLowerCase().endsWith(COMPONENT_JSON)};function _deCamelCaseProp(str){return str.replace(/([a-zA-Z])(?=[A-Z])/g,"$1-").toLowerCase()};function _deCamelCaseEvent(str){return"on-"+_deCamelCaseProp(str)};function _isRelativeUrl(url){url=url.toLowerCase();return!(url.indexOf("http://")===0||url.indexOf("https://")===0)};function _removeChevrons(tagName){if(tagName){let len=tagName.length-1;let start=tagName.charAt(0)==="<"?1:0;let end=tagName.charAt(len)===">"?len:++len;tagName=tagName.substring(start,end)}return tagName};module.exports=Components;
|
|
6
|
+
"use strict";const COMPONENT_JSON="component.json";const PROP_SLOTS="slots";const PROP_DYNAMIC_SLOTS="dynamicSlots";const PROP_PROPS="props";const PROP_EVENTS="events";const PROP_STYLECLASSES="styleClasses";const PROP_IMPLEMENTS="implements";const PROP_REQUIRED="required";const PROP_FOLDER="folder";const PROP_VERSION="version";const PROP_UNSUP_THEME="unsupTheme";const PROP_STATUS="status";const PROP_SUBCOMPONENT_TYPE="subcomponentType";const PROP_TYPE="type";const PROP_PACK="pack";const DEPRECATED="deprecated";const PROPERTY_VALUE="propertyValue";const PROPERTY_TYPE="propertyType";const PACK_PRIVATE="packPrivate";const MAINTENANCE="maintenance";const SUPERSEDES="supersedes";const DYNAMIC_FORM_ELEM="DynamicFormElement";const DYNAMIC_TABLE_ELEM="DynamicTableElement";const VB_FRAGMENT_ELEM="VbFragmentElement";const OJ_C="oj-c";const REGXPR=/string|number|object|array|boolean|[\|.<>]/gi;function Components(nd,runMode,cwd,compSvcs,urlBase,urls,filePaths,metaLib,ojcPack,jetCore,runOpts,msgCtx,appCtx){this._nd=nd;this._tagLookup={};this._jetTagLookup={};this._styleLookup={};this._maintenance=null;this._supersedes=null;this._path=null;this._reqAttrs=null;this._metaLib=metaLib;this._ojcPack=ojcPack;this._utils=appCtx.utils;this._fsUtils=appCtx.fsUtils;this._compSvcs=compSvcs;this._isAMD=runMode==="amd";this._cwd=cwd;this._error=msgCtx.error;this._warn=msgCtx.warn;this._debug=msgCtx.debug;this._info=msgCtx.info;this._msg=msgCtx.msg;this._console=msgCtx.console;this._isDebug=msgCtx.isDebug;this._isVerbose=msgCtx.isVerbose;this._count=0;this._isOk=true;this._runOpts=runOpts;this._init(urlBase,urls,filePaths,jetCore)};Components.prototype.isTag=function(tagName){return!!this._tagLookup[_removeChevrons(tagName)]};Components.prototype.isJetTag=function(tagName){return!!this._jetTagLookup[_removeChevrons(tagName)]};Components.prototype.isKnownTag=function(tagName){tagName=_removeChevrons(tagName);return this._jetTagLookup[tagName]||this._tagLookup[tagName]};Components.prototype.isTagAttr=function(tagName,attrName){return this.isTagProp(tagName,attrName)||this.isJetTagProp(tagName,attrName)};Components.prototype.isJetTagAttr=function(tagName,attrName){return this.isJetTagProp(tagName,attrName)};Components.prototype.isTagDeprecated=function(tag){var comp,stats,status,ret=null;tag=_removeChevrons(tag);if(comp=this._tagLookup[tag]||this._jetTagLookup[tag]){if(stats=comp.status){for(status of stats){if(status.type===DEPRECATED&&!status.hasOwnProperty("target")){ret=status;break}}}}return ret};Components.prototype.isTagAttrDeprecated=function(tagName,attrName){var prop,status,stats,o,ret=null;if((prop=this.getAnyTagProp(tagName,attrName))&&(stats=prop.status)){ret=[];for(status of stats){if(status.type===DEPRECATED){o={type:DEPRECATED};if(status.hasOwnProperty("target")){o.target=status.target}if(status.hasOwnProperty("description")){o.description=status.description}if(status.hasOwnProperty("since")){o.since=status.since}if(status.hasOwnProperty("value")){o.value=status.value}ret.push(o)}}ret=ret.length?ret:null}return ret};Components.prototype.isTagAttrTranslatable=function(tag,attr){var prop=this.getAnyTagProp(tag,attr);return prop&&prop.translatable};Components.prototype.isTagAttrReadOnly=function(tag,attr){var prop=this.getAnyTagProp(tag,attr);return prop&&prop.readonly};Components.prototype.isTagProp=function(tagName,propName){return!!this.getTagProp(tagName,propName)};Components.prototype.isJetTagProp=function(tagName,propName){return!!this.getJetTagProp(tagName,propName)};Components.prototype.getTagProp=function(tagName,propName){var ret;if(this.isTag(tagName)){ret=this._getTagProp(tagName,propName,false)}return ret?ret:null};Components.prototype.getJetTagProp=function(tagName,propName){var ret;if(this.isJetTag(tagName)){ret=this._getTagProp(tagName,propName,true)}return ret?ret:null};Components.prototype.getAnyTagProp=function(tagName,propName){return this._getTagProp(tagName,propName,true)||this._getTagProp(tagName,propName,false)};Components.prototype._getTagProp=function(tagName,propName,isOJC){var tag,props,list;list=isOJC?this._jetTagLookup:this._tagLookup;tag=list[_removeChevrons(tagName)];props=tag?tag[PROP_PROPS]:null;if(props){propName=propName.charAt(0)===":"?propName.substring(1):propName;propName=_deCamelCaseProp(propName)}return props?props[propName]:null};Components.prototype.getTagPropType=function(tagName,propName){var prop,ret;if(prop=this.getTagProp(tagName,propName)){ret=prop?prop.type:undefined}return ret};Components.prototype.getTagMetadata=function(tag){tag=_removeChevrons(tag);return this._tagLookup[tag]||this._jetTagLookup[tag]};Components.prototype.getJetTag=function(tag){var meta;return(meta=this._jetTagLookup[tag])?meta:null};Components.prototype.isTagEvent=function(tagName,eventName){var propName,o,b;o=this._tagLookup[tagName]||this._jetTagLookup[tagName];if(o){if(eventName.startsWith("on-")){b=o.events&&o.events[eventName];if(b)return b;if(o.implements&&(o.implements.includes(DYNAMIC_FORM_ELEM)||o.implements.includes(DYNAMIC_TABLE_ELEM)||o.implements.includes(VB_FRAGMENT_ELEM))){return true}if(eventName.endsWith("-changed")){if(o.props){propName=eventName.replace("-changed","").substring(3);return!!o.props[propName]}}}}return false};Components.prototype.isTagStyle=function(tag,style){var meta;if(meta=this._tagLookup[tag]||this._jetTagLookup[tag]){let styles,sc;if(styles=meta.styleClasses){if(sc=styles[style]){return true}}}return false};Components.prototype.isStyle=function(style){return!!this._styleLookup[style]};Components.prototype.getStyleMetadata=function(style){var tag,styles,sc,ret=null;if(tag=this._styleLookup[style]){if(styles=this._tagLookup[tag].styleClasses){if(sc=styles[style]){ret={tag:tag,meta:sc}}}}return ret};Components.prototype.getStyleSelector=function(style){var sm=this.getStyleMetadata(style);return sm&&sm.meta?sm.meta.styleSelector:null};Components.prototype.hasTagSlotName=function(tagName,slotName){var o=this._tagLookup[tagName]||this._jetTagLookup[tagName];return!!(o&&o.slots&&o.slots[slotName])};Components.prototype.getPreferredSlotContent=function(tag,slotName,impls){var o,slot,prefContent=null,comps=null,content;if(this._utils.hasAnyProps(impls)){if(o=this._tagLookup[tag]||this._jetTagLookup(tag)){if(o.slots){if(slot=o.slots[slotName]){if(prefContent=slot.preferredContent){prefContent.forEach(impl=>{if(content=impls[impl]){if(!comps){comps=[]}comps.push(...content)}})}}}}}return prefContent||comps?{interfaces:prefContent,components:comps}:null};Components.prototype.getTagSlotMetadata=function(tag,slot){var o,ret;if(o=this._tagLookup[tag]||this._jetTagLookup[tag]){if(o.slots){if(slot=o.slots[slot]){ret=slot}}}return ret};Components.prototype.hasTagDynamicSlot=function(tag){var o,ret=false;if(o=this._tagLookup[tag]||this._jetTagLookup[tag]){if(o.hasOwnProperty(PROP_DYNAMIC_SLOTS)){ret=true}}return ret};Components.prototype.hasTagAttrValues=function(tagName,attrName){var prop,ret=false;if((prop=this.getTagProp(tagName,attrName))||(prop=this.getJetTagProp(tagName,attrName))){ret=!!prop.enumValues}return ret};Components.prototype.isTagAttrValue=function(tagName,attrName,value){var prop,ret;if((prop=this.getTagProp(tagName,attrName))||(prop=this.getJetTagProp(tagName,attrName))){if(prop&&prop.enumValues){ret=prop.enumValues.indexOf(value)>=0}}return ret};Components.prototype.isTagAttrEnumDeprecated=function(tag,attr,val){var prop,stats,status,ret=null;if(prop=this.getAnyTagProp(tag,attr)){if(stats=prop.status){for(status of stats){if(status.type===DEPRECATED&&status.target===PROPERTY_VALUE){if(status.value&&status.value.includes(val)){ret={type:DEPRECATED};if(status.hasOwnProperty("target")){ret.target=status.target}if(status.hasOwnProperty("description")){ret.description=status.description}if(status.hasOwnProperty("since")){ret.since=status.since}if(status.hasOwnProperty("value")){ret.value=status.value}break}}}}}return ret};Components.prototype.isTagSupportedInTheme=function(tag,theme){var o,unsup,ret=true;if(o=this.getTagMetadata(tag)){unsup=o[PROP_UNSUP_THEME];if(unsup){ret=!unsup.includes(theme)}}return ret};Components.prototype.isAttrSupportedInTheme=function(tag,attr,theme){var prop,unsup,ret=true;if(prop=this.getAnyTagProp(tag,attr)){if(unsup=prop[PROP_UNSUP_THEME]){ret=!unsup.includes(theme)}}return ret};Components.prototype.isTagPackPrivate=function(tag){var o,ret;tag=_removeChevrons(tag);if(o=this._tagLookup[tag]||this._jetTagLookup[tag]){ret=o[PROP_SUBCOMPONENT_TYPE]===PACK_PRIVATE}return ret};Components.prototype.getSubcomponentType=function(tag){var o,ret;if(o=this._tagLookup[tag]||this._jetTagLookup[tag]){ret=o[PROP_SUBCOMPONENT_TYPE]}return ret||null};Components.prototype.getRequiredProps=function(tagName){var tag,props,prop,propName,obj,ret=null;tagName=_removeChevrons(tagName);if(this._reqAttrs){let r=this._reqAttrs[tagName];if(r){return typeof r==="boolean"?null:r}}tag=this._tagLookup[tagName]||this._jetTagLookup[tagName];if(tag&&tag.props){if(!this._reqAttrs){this._reqAttrs={}}if(!this._reqAttrs[tagName]){this._reqAttrs[tagName]=true}props=tag.props;for(propName in props){prop=props[propName];if(prop.required){if(!obj){obj=[]}obj.push(_deCamelCaseProp(propName))}}}if(obj&&obj.length){this._reqAttrs[tagName]=obj;ret=obj}return ret};Components.prototype.getRequiredAttrs=function(tagName){return this.getRequiredProps(tagName)};Components.prototype.getInterfaces=function(tag){var o,ret;if(o=this._tagLookup[tag]||this._jetTagLookup[tag]){ret=o.implements}return ret||null};Components.prototype.getUserNames=function(){var name,a=[];for(name in this._tagLookup){a.push({name:name,version:this._tagLookup[name].version})}return a};Components.prototype.getJetNames=function(){var name,a=[];for(name in this._jetTagLookup){a.push({name:name,version:this._jetTagLookup[name].version})}return a};Components.prototype.getCount=function(){return this._count};Components.prototype.isTagMaintenance=function(tag){return this._maintenance&&this._maintenance.has(tag)};Components.prototype.isTagSupersedes=function(tag){return this._supersedes&&this._supersedes.has(tag)};Components.prototype.getTagMaintenanceStatus=function(tag){return this.getTagStatus(tag,MAINTENANCE)};Components.prototype.getTagSupersedesStatus=function(tag){return this.getTagStatus(tag,SUPERSEDES)};Components.prototype.getTagStatus=function(tag,type){var ret=null;if(type===SUPERSEDES&&this.isTagSupersedes(tag)||type===MAINTENANCE&&this.isTagMaintenance(tag)||type===DEPRECATED&&this.isTagDeprecated(tag)){let comp,arStat,i;if(comp=this._tagLookup[tag]||this._jetTagLookup[tag]){arStat=comp.status;for(i=0;i<arStat.length;i++){if(arStat[i].type===type){ret=arStat[i];break}}}}return ret};Components.prototype.isOk=function(){return this._isOk};Components.prototype._init=function(base,urls,filePaths,jetCore){if(this._isAMD){this._processJetCorePack();return}if(base){base=base.trim();if(base.charAt(base.length-1)!=="/"){base=base+"/"}}else{base=""}this._processFilePaths(filePaths);this._processUrls(base,urls);this._processJetCorePack();this._createStyleLookup();this._processJetCore(jetCore)};Components.prototype._processFilePaths=function(filePaths){var obj,compEntry,fpath,i,j;if(!filePaths){return}this._console("\nPre-processing user-declared web component metadata...");for(i=0;i<filePaths.length;i++){compEntry=filePaths[i];var dirStack=this._nd.glob.sync(compEntry);for(j=0;j<dirStack.length;j++){fpath=dirStack[j];if(this._runOpts.isDryRun||this._runOpts.isDebug){let msg="-".repeat(70)+"\n"+(this._runOpts.isDryRun?"* ":"")+"processing component path '"+fpath+"' ...";if(this._runOpts.isDryRun){console.log(msg)}else{this._debug(msg)}}if(fpath.toLowerCase().endsWith(".zip")){obj=this._compSvcs._extractComponentJsonFromZip(fpath);if(obj.obj){this.processComponentJson(obj.obj,fpath,true)}else if(obj.msg){this._error("Failed to parse component.json : "+obj.msg+" - "+fpath)}else if(obj.error){this._error("Failed to unzip '"+fpath+"'")}continue}if(this._isComponentJsonPath(fpath)){obj=this._readComponentJson(fpath);if(obj){if(obj.type&&obj.type==="pack"){continue}this.processComponentJson(obj,this._nd.path.dirname(fpath),true)}continue}this._recurse(fpath)}}if(this._isDebug){this._debug("-".repeat(70))}};Components.prototype._recurse=function(fpath){var dirs,inFile,obj,i;try{dirs=this._nd.fs.readdirSync(fpath);if(this._isDebug){this._debug(` processing ${fpath} ${dirs.length} component dirs ...`)}for(i=0;i<dirs.length;i++){inFile=dirs[i];if(inFile===COMPONENT_JSON){inFile=this._nd.path.join(fpath,COMPONENT_JSON);if(this._isDebug){this._debug(" processing "+inFile+"...")}obj=this._readComponentJson(inFile);if(obj){if(!obj.type||obj.type==="composite"){this.processComponentJson(obj,fpath,true)}}else{return}}var curPath=this._nd.path.join(fpath,inFile);if(this._fsUtils.getFileType(curPath)==="d"){this._recurse(curPath)}}}catch(e){this._error("Component check failed - "+e);this._isOk=false}};Components.prototype._processUrls=function(base,urls){var url,i;if(!urls){return}for(i=0;i<urls.length;i++){url=urls[i];if(this._runOpts.isDryRun||this._runOpts.isDebug){let msg;msg="-".repeat(70)+"\nprocessing URL '"+url+"'";if(this._runOpts.isDryRun){console.log(msg);continue}else{this._debug(msg)}}if(_isRelativeUrl(url)){url=base+url;if(_isRelativeUrl(url)){this._error("component URL incomplete - '"+url+"'");continue}}this._processUrl(url)}};Components.prototype._processUrl=function(url){var resp,obj,rc,tempFile,tmp;try{resp=this._compSvcs.loadUrl(url);if(resp.eCode==="ETIMEDOUT"){this._error("config.componentUrls - request timed-out for '"+url+"'");this._isOk=false;return}try{if(resp.type==="json"){if(resp.body){obj=JSON.parse(resp.body);if(!this.processComponentJson(obj,url,false)){this._isOk=false}}else{this._error("Server responded with "+resp.statusCode+" URL: '"+url+"'")}}else if(resp.type=="zip"){rc=this._compSvcs.writeZipBufferToFile(resp.body);if(typeof rc==="boolean"&&rc){tempFile=this._compSvcs.getLastZipFilePath();obj=this._compSvcs.extractComponentJsonFromZip(tempFile);if(obj.obj){this.processComponentJson(obj.obj,url,true)}else if(obj.msg){this._error("Failed to parse component.json : "+obj.msg+" - "+url)}else if(obj.error){this._error("Failed to unzip '"+url+"'")}this._compSvcs.deleteZipFile(tempFile)}else{this._error("Failed to create local temp zip file from URL '"+url+"' : rc.message");this._isOk=false}}else{tmp=typeof resp.type==="string"?resp.type:"?";this._error("Server responded with unexpected data ('"+tmp+"') : '"+url+"'");this._isOk=false}}catch(e){this._error("Invalid JSON - URL '"+url+"' : "+e);this._isOk=false}}catch(e1){this._error("URL access failed "+(e1.message.includes("ENOTFOUND")?"(NOT FOUND)":"")+" - URL '"+url+"'");this._isOk=false}};Components.prototype._processJetCorePack=function(){var comps,comp;if(comps=this._ojcPack.getComponents()){for(comp in comps){this.processComponentJson(comps[comp],"oj-c")}}};Components.prototype.processComponentJson=function(obj,fromLocation){var comp,props,events,event,compName,metaObj;var isOJC;compName=obj.pack?obj.pack+"-"+obj.name:obj.name;isOJC=obj.pack===OJ_C;if(!this._isAMD){if(this._runOpts.isDryRun){console.log(" Would have processed '"+fromLocation+"'");return}if(obj.type&&obj.type==="pack"){return this._processJetPack(obj,fromLocation)}if(!isOJC){if(!this._compSvcs.validateComponentJson(obj,fromLocation)){this._isOk=false;return false}}}if(this._tagLookup[compName]||this._jetTagLookup[compName]){this._warn(`Ignoring duplicate component '${compName}' at '${fromLocation}'`);return true}if(isOJC){this._jetTagLookup[compName]=comp={}}else{this._tagLookup[compName]=comp={}}comp[PROP_FOLDER]=fromLocation;comp[PROP_VERSION]=obj.version;if(obj.extension&&obj.extension.audit&&obj.extension.audit.ignore){this._metaLib.addIgnoredRules(compName,"tag",null,obj.extension.audit.ignore)}if(obj.hasOwnProperty(PROP_SLOTS)){comp[PROP_SLOTS]=obj[PROP_SLOTS]}if(obj.hasOwnProperty(PROP_DYNAMIC_SLOTS)){comp[PROP_DYNAMIC_SLOTS]=true}if(obj.properties){comp[PROP_PROPS]=props={};this._extractProps(props,null,obj.properties,obj.name)}if(obj.events){comp[PROP_EVENTS]=events={};for(event in obj.events){event=_deCamelCaseEvent(event);events[event]=true;metaObj=obj.events;if(metaObj.extension&&metaObj.extension.audit&&metaObj.extension.audit.ignore){this._metaLib.addIgnoredRules(compName,"event",event,metaObj.extension.audit.ignore)}}}if(obj.implements){comp[PROP_IMPLEMENTS]=obj.implements;this._metaLib.processImplements(compName,obj.implements)}if(obj.status){let status,i;metaObj=obj.status;for(i=0;i<metaObj.length;i++){status=metaObj[i];if(status.type===MAINTENANCE){if(!this._maintenance){this._maintenance=new Set}this._maintenance.add(compName)}else if(status.type===SUPERSEDES){if(!this._supercedes){this._supersedes=new Set}this._supersedes.add(compName)}}}if(obj.extension&&obj.extension.theme&&obj.extension.theme.unsupportedThemes){comp[PROP_UNSUP_THEME]=obj.extension.theme.unsupportedThemes}if(obj.hasOwnProperty(PROP_SUBCOMPONENT_TYPE)){comp[PROP_SUBCOMPONENT_TYPE]=obj[PROP_SUBCOMPONENT_TYPE]}if(obj.type){comp[PROP_TYPE]=obj.type}if(obj.pack){comp[PROP_PACK]=obj.pack}if(obj.hasOwnProperty("required")){comp[PROP_REQUIRED]=obj.required}if(obj.status){comp[PROP_STATUS]=obj.status}if(obj.styleClasses){comp[PROP_STYLECLASSES]=this._extractStyles(obj.styleClasses)}this._count++;return true};Components.prototype._extractProps=function(propObj,propSoFar,properties,name,rdonly){var prop,newProp,thisProp,soFar,obj;for(prop in properties){newProp=_deCamelCaseProp(prop);soFar=(propSoFar?propSoFar+".":"")+newProp;propObj[soFar]=obj={};thisProp=properties[prop];if(thisProp.hasOwnProperty("enumValues")){if(Array.isArray(thisProp.enumValues)){obj.enumValues=thisProp.enumValues}else{this._error(`Web component'${name}' property '${soFar}' has invalid 'enumValues' in component.json`)}}if(thisProp.hasOwnProperty("status")){obj.status=thisProp.status}if(thisProp.hasOwnProperty("type")){obj.type=thisProp.type}if(thisProp.required){obj.required=true}if(thisProp.extension&&thisProp.extension.theme&&thisProp.extension.theme.unsupportedThemes){obj[PROP_UNSUP_THEME]=thisProp.extension.theme.unsupportedThemes}if(thisProp.hasOwnProperty("translatable")){obj.translatable=true}if(typeof thisProp.readonly==="boolean"){obj.readonly=thisProp.readOnly}else{if(rdonly){obj.readonly=true}}if(thisProp.hasOwnProperty("properties")){obj.properties=true;this._extractProps(propObj,soFar,thisProp.properties,name,obj.readonly)}}};Components.prototype._extractStyles=function(styleClasses){var so,si,obj,ret={},i,j;if(!Array.isArray(styleClasses)){return ret}for(i=0;i<styleClasses.length;i++){so=styleClasses[i];if(so.kind==="class"){ret[so.name]=this._extractStyleClass(so)}else if(so.kind==="set"&&so.styleItems&&Array.isArray(so.styleItems)){ret[so.name]=obj={kind:"set"};if(so.status){obj.status=so.status}obj.styleClasses={};for(j=0;j<so.styleItems.length;j++){si=so.styleItems[j];obj.styleClasses[si.name]=this._extractStyleClass(si)}}else if(so.kind==="template"){}}return ret};Components.prototype._extractStyleClass=function(so){var obj={};if(so.styleSelector){obj.styleSelector=so.styleSelector}if(so.status){obj.status=so.status}return obj};Components.prototype._processJetPack=function(obj,fromLocation){var deps,dep,urlKey,depUrl,msg,i;if(this._runOpts.isDryRun||this._runOpts.isDebug){msg="processing JET Pack "+obj.name+" (version: "+obj.version+") : '"+fromLocation+"'";if(this._runOpts.isDryRun){console.log("* "+msg);return}else{this._debug(msg)}}if(!fromLocation.includes("http")){this._error("JET packs loaded via config 'components' property (file based) are currently not supported");return false}i=fromLocation.indexOf(obj.name);if(i>=0){urlKey=fromLocation.substring(0,i)}else{this._error("Cannot handle Jet Pack URL format to load dependencies : "+fromLocation)}deps=obj.dependencies;if(deps){for(dep in deps){depUrl=urlKey+dep+"/versions/"+obj.dependencies[dep]+"/content/component.json";if(this._isDebug){this._debug(` processing dependency ${dep} ${obj.dependencies[dep]}`)}this._processUrls("",[depUrl])}}return false};Components.prototype._processJetCore=function(jetCorePath){var files,file,obj,i;if(!jetCorePath){return}this._console("-".repeat(70)+"\nPerforming schema analysis on JET Core components (dt) using '"+this._compSvcs.getSchemaName()+"'...");try{files=this._nd.fs.readdirSync(jetCorePath);this._console(` processing ${files.length} $jetCore components...`);for(i=0;i<files.length;i++){file=files[i];if(file.endsWith(".json")){file=this._nd.path.join(jetCorePath,file);try{obj=this._readComponentJson(file);if(obj){this._compSvcs.validateComponentJson(obj,file)}}catch(e){}}}}catch(e1){this._error("!!! $JetCore Component check failed - "+e1)}this._console(" processing "+(files?files.length+" ":"")+"$jetCore components completed");this._console("-".repeat(70))};Components.prototype._createStyleLookup=function(){var tag,o,scl,st;for(tag in this._tagLookup){o=this._tagLookup[tag];if(scl=o.styleClasses){for(st in scl){this._styleLookup[st]=tag}}}};Components.prototype._readComponentJson=function(inFile){var obj=null;if(this._isDebug){this._debug(` loading '${inFile}'`)}obj=this._nd.jsonLoader.load(inFile,this._nd,this._error,false,this._utils);if(!obj){this._isOk=false}return obj};Components.prototype._isComponentJsonPath=function(filePath){return filePath.toLowerCase().endsWith(COMPONENT_JSON)};Components.prototype.dumpComponentNames=function(){var names;names=this.getUserNames();if(!names.length){this._console("[info]: No valid user web components declared!","I")}else{this._console("[info] :--------- Declared Web Components ---------","I");this._dumpComponentNames(names);this._console("[info]: -------- End Declared Web Components ---------\n","I")}names=this.getJetNames();if(!names.length){this._console("[info]: No valid user JET Core Pack components declared!","I")}else{this._console("[info] :--------- Declared JET OJ-C Pack Web Components ---------","I");this._dumpComponentNames(names);this._console("[info]: -------- End Declared OJ-C Pack Web Components ---------\n","I")}};Components.prototype._dumpComponentNames=function(names){var meta,obj,i;for(i=0;i<names.length;i++){obj=names[i];this._console(` ${obj.name} (${obj.version})`,"I");meta=this.getTagMetadata(obj.name);if(meta.implements){this._console(` Impls: ${meta.implements.join(",")}`)}}};function _deCamelCaseProp(str){return str.replace(/([a-zA-Z])(?=[A-Z])/g,"$1-").toLowerCase()};function _deCamelCaseEvent(str){return"on-"+_deCamelCaseProp(str)};function _isRelativeUrl(url){url=url.toLowerCase();return!(url.indexOf("http://")===0||url.indexOf("https://")===0)};function _removeChevrons(tagName){if(tagName){let len=tagName.length-1;let start=tagName.charAt(0)==="<"?1:0;let end=tagName.charAt(len)===">"?len:++len;tagName=tagName.substring(start,end)}return tagName};module.exports=Components;
|
package/lib/Config.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 nodeDeps;const Helper=require("./ConfigLib");const MACROS=require("../lib/macros");const DEFAULTS=require("./defaults");var JET_VERSIONS;const TYPE_BOOLEAN="boolean";const AT_INCLUDE="@include(";const QUOTE="\"";const TSCONFIG="tsconfig.json";var Config=function(nd,base,iniPath,fnApplyMacros,rules,severity,cliGroups,cliSev,msgCtx,modeCtx,utils,cbDebug){this._path=iniPath;this._dir=null;this._config=null;this._tsCfgObj=null;this._preBuilt=false;this._isOJET=modeCtx.isOJET;this._isCLI=modeCtx.isCLI;this._isAPI=modeCtx.isAPI;this._isAMD=modeCtx.isAMD;this._isCliMode=modeCtx.isCLI||modeCtx.isOJETCLI;this._rules=rules;this._utils=utils;this._severity=severity;this._helper=new Helper(this,nd,severity,utils,msgCtx,modeCtx);this.applyMacros=fnApplyMacros;this._bErrors=false;this._console=msgCtx.console;this._error=msgCtx.error;this._warn=msgCtx.warn;this._info=msgCtx.info;this._debug=msgCtx.debug;this._isDebug=msgCtx.isDebug;this._isVerbose=msgCtx.isVerbose;JET_VERSIONS=nd.jetver.getVersions();this._cliGroups=cliGroups;this._cliSev=cliSev;nodeDeps=nd;if(iniPath){this._init(base,iniPath,cbDebug)}};Config.prototype.getConfig=function(){var tmp=JSON.parse(JSON.stringify(this._config));if(tmp._sev){delete tmp._sev}return tmp};Config.prototype.getFiles=function(){return this._config.files};Config.prototype.getExclude=function(){return this._config.exclude};Config.prototype.getOptions=function(){return this._config.options};Config.prototype.getJetVer=function(){return this._config.jetVer};Config.prototype.getComponentsBaseUrl=function(){return this._config.componentsBaseUrl};Config.prototype.getComponentsBase=function(){return this._config.componentsBase};Config.prototype.getComponents=function(){return this._config.components};Config.prototype.getComponentUrls=function(){return this._config.componentUrls};Config.prototype.getComponentOptions=function(){return this._config.componentOptions};Config.prototype.getTypescript=function(){return this._config.typescript};Config.prototype.getTsConfig=function(){var ret;if(this._config.typescript){ret=this._config.typescript.tsconfig}return ret};Config.prototype.getTsConfigObj=function(){return this._tsCfgObj};Config.prototype.getOutPath=function(){return this._config.outPath};Config.prototype.getRulePacks=function(){return this._config.rulePacks};Config.prototype.getRuleMods=function(){return this._config.ruleMods};Config.prototype.getEnable=function(){return this._config.ruleMods&&this._config.ruleMods.enable?this._config.ruleMods.enable:undefined};Config.prototype.getDisable=function(){return this._config.ruleMods&&this._config.ruleMods.disable?this._config.ruleMods.disable:undefined};Config.prototype.getRuleDescriptions=function(){return this._config.ruleDescriptions};Config.prototype.getRulesFired=function(){return this._config.rulesFired};Config.prototype.getGroups=function(){return this._config.groups};Config.prototype.setGroups=function(groups){this._config.groups=groups};Config.prototype.getDefGroups=function(){return this._config.defGroups};Config.prototype.getRunRuleNames=function(){return this._config.ruleNames};Config.prototype.isBuiltinJetRules=function(){return this._config.builtinJetRules};Config.prototype.isBuiltinCspRules=function(){return this._config.builtinCspRules};Config.prototype.isBuiltinJetWcRules=function(){return this._config.builtinJetWcRules};Config.prototype.isBuiltinJetWcOracleRules=function(){return this._config.builtinJetWcOracleRules};Config.prototype.isBuiltinSpocRules=function(){return this._config.builtinSpocRules};Config.prototype.isBuiltinOjcMigrationRules=function(){return this._config.builtinOjcMigrationRules};Config.prototype.isBuiltinWebDriverTestRules=function(){return this._config.builtinWebDriverTestRules};Config.prototype.getMessages=function(){return this._config.messages};Config.prototype.setMessages=function(msgid,state){return this._helper.setMessages(msgid,state)};Config.prototype.getFollowLinks=function(){return this._config.followLinks};Config.prototype.getFormat=function(){return this._config.format};Config.prototype.getProseFormat=function(){return this._config.proseFormat};Config.prototype.getLineFormat=function(){return this._config.lineFormat};Config.prototype.getBase=function(){return this._config.base};Config.prototype.getStylesets=function(){return this._config.stylesets};Config.prototype.getNameSpaces=function(){return this._config.nameSpaces};Config.prototype.getCommon=function(){return this._config.common||{}};Config.prototype.getSeverity=function(){return this._config.severity};Config.prototype.setSeverity=function(severity){return this._config.severity=severity};Config.prototype.getSevMap=function(){return this._config.sevMap};Config.prototype.getTheme=function(){return this._config.theme};Config.prototype.getComments=function(){return this._config.comments};Config.prototype.getEcmaVer=function(){return this._config.ecmaVer};Config.prototype.getTabs=function(){return this._config.tabs};Config.prototype.getTitle=function(){return this._config.title};Config.prototype.getRetCode=function(){var ret,o;if(this._config&&this._config.options){o=this._config.options;if(o.retCode!==undefined){ret=o.retCode}else if(o.rc!==undefined){ret=o.rc}else{ret="auto"}}else{ret="auto"}return ret};Config.prototype.isOk=function(){return!this._bErrors};Config.prototype.getUserDefs=function(){return this._config.userDefs};Config.prototype.getAppendFileList=function(){return this._helper.getAddFileList()};Config.prototype.getJetPagesOnly=function(){return this._config.jetPagesOnly};Config.prototype.getTempDir=function(){return this._config.tempDir};Config.prototype.getOrigConfig=function(){return this._origConfig};Config.prototype.get$JetCore=function(){return this._config.$JetCore};Config.prototype._init=function(base,iniPath,cbDebug){var i,s,val,val2,bUseDefaults=false;if(typeof iniPath==="string"){this._dir=nodeDeps.path.dirname(iniPath);bUseDefaults=this._loadConfig(iniPath);if(this._bErrors){return}}else{this._config=iniPath;this._dir=nodeDeps.process.cwd();this._preBuilt=true}this._origConfig=this._config;this._config=_cloneConfig(this._config);this._helper.setConfig(this._config,this._preBuilt?null:iniPath,this._dir);if(this._config.options){this._isVerbose=!!this._config.options.verbose;this._isDebug=!!this._config.options.debug;cbDebug(this._isVerbose,this._isDebug);this._helper.setDebugStatus(this._isVerbose,this._isdebug)}if(!this._checkProperties()){this._bErrors=true;return}if(base){this._config.base=base}if(!this._config.base){this._config.base=this._dir}if(this._config.base===MACROS.cwd){this._config.base=nodeDeps.process.cwd()}if(!this._cleanBase()){return}if(!bUseDefaults&&!this._isOJET){this._info("[Info]: Analyzing "+(typeof iniPath==="string"?"config '"+iniPath+"'":"pre-built config object"),"I",true)}if(this._config.extends){if(!this._helper.processExtends(this._config)){this._bErrors=true;return}}if(typeof this._config.builtinJetRules!==TYPE_BOOLEAN){this._config.builtinJetRules=true}if(typeof this._config.builtinCspRules!==TYPE_BOOLEAN){this._config.builtinCspRules=false}if(typeof this._config.builtinJetWcRules!==TYPE_BOOLEAN){this._config.builtinJetWcRules=false}if(typeof this._config.builtinJetWcOracleRules!==TYPE_BOOLEAN){this._config.builtinJetWcOracleRules=false}if(typeof this._config.builtinWebDriverTestRules!==TYPE_BOOLEAN){this._config.builtinWebDriverTestRules=false}if(this._config.builtinSpocRules){if(typeof this._config.builtinSpocRules!==TYPE_BOOLEAN){this._error("Config entry 'builtinSpocRules' must be a boolean!");this._bErrors=true;return}if(this._config.builtinSpocRules){this._config.builtinJetRules=this._config.builtinJetWcRules=this._config.builtinJetWcOracleRules=false}}if(this._config.builtinOjcMigrationRules){if(typeof this._config.builtinOjcMigrationRules!==TYPE_BOOLEAN){this._error("Config entry 'builtinOjcMigrationRules' must be a boolean!");this._bErrors=true;return}else{this._config.builtinJetRules=this._config.builtinJetWcRules=this._config.builtinJetWcOracleRules=this._config.builtinCspRules=this._config.builtinSpocRules=false}}else{this._config.builtinOjcMigrationRules=false}this._config.jetPagesOnly=!!this._config.jetPagesOnly;if(!this._config.files){this._config.files=[]}if(!this._config.options){this._config.options={}}if(this._config.jetVer){val=this._config.jetVer;if(typeof val!=="string"){this._error("Config entry 'jetVer' is not a string!");this._bErrors=true;return}val=val.trim();val2=val.split(".");for(i=0;i<val2.length;i++){if(i===0&&val2[0].charAt(0).toLowerCase()==="v"){val2[0]=val2[0].substring(1)}s=parseInt(val2[i]);if(isNaN(s)){let part=["major","minor","patch"];this._error(`Config entry 'jetVer' --> '${val}' : '${part[i]}' value is invalid`);this._bErrors=true;return}val2[i]=""+s}val=val2.join(".");if(val2.length!==3||val2[2]==="0"){s=val2.length===3;val2=nodeDeps.jetver.getBestVersion(val,val2);if(!val2){s=s?`Config entry 'jetVer' --> '${val}' cannot be resolved to a supported JET version`:`Config entry 'jetVer' --> '${val}' is not a supported JET version`;this._error(s);this._bErrors=true;return}val=val2}if(!JET_VERSIONS[val]){this._error(`Config entry 'jetVer' --> '${val}' is not a supported JET version!`);this._bErrors=true;return}this._config.jetVer=val}else{this._config.jetVer=DEFAULTS.JETVER}if(!this._helper.processWebComponents()){this._bErrors=true;return}if(!this._helper.processRulePacks()){this._bErrors=true;return}if(!this._helper.processRuleMods()){this._bErrors=true;return}if(!this._helper.processFormat()){this._bErrors=true;return}if(!this._helper.processProseFormat()){this._bErrors=true;return}if(!this._helper.processLineFormat()){this._bErrors=true;return}if(!this._helper.processRuleDescriptions()){this._bErrors=true;return}if(!this._helper.processRulesFired()){this._bErrors=true;return}if(!this._helper.processSevMap()){this._bErrors=true;return}if(!this._helper.processSeverity(this._cliSev)){this._bErrors=true;return}if(!this._helper.processGroups(this._cliGroups)){this._bErrors=true;return}if(!this._helper.processDefGroups()){this._bErrors=true;return}if(!this._helper.processRuleNames()){this._bErrors=true;return}if(this._config.followLinks==null){this._config.followLinks=true}else{this._config.followLinks=!!this._config.followLinks}if(!Array.isArray(this._config.files)){this._error("Config entry 'files' is not an array!");this._bErrors=true;return}if(!this._helper.validateFileList(this._config.files)){this._bErrors=true;return}if(this._config.exclude){if(!Array.isArray(this._config.exclude)){this._error("Config entry 'exclude' is not an array!");this._bErrors=true;return}if(!this._helper.validateFileList(this._config.exclude)){this._bErrors=true;return}}else if(this._config.excludes){this._error("Config property 'excludes' found - did you mean 'exclude'?");this._bErrors=true;return}if(!this._helper.processAddFileList()){this._bErrors=true;return}if(this._config.stylesets){val=this._config.stylesets;if(!Array.isArray(val)){this._error("Config property 'stylesets' is not an array!");this._bErrors=true;return}}if(this._isAMD&&this._config.tempDir){this._error("Config entry 'tempDir' is not valid in AMD mode!");this._bErrors=true;return}if(this._config.tempDir){if(typeof this._config.tempDir!=="string"){this._error("Config property 'tempDir' is not a string!");this._bErrors=true;return}if(this._config.tempDir.startsWith(".")){this._config.tempDir=nodeDeps.path.resolve(nodeDeps.process.cwd(),this._config.tempDir)}}if(!this._helper.processTypeScript()){this._bErrors=true;return}if(!this._helper.processMessages()){this._bErrors=true;return}if(!this._helper.processNameSpaces()){this._bErrors=true;return}if(!this._helper.processTheme()){this._bErrors=true;return}if(!this._helper.processComments()){this._bErrors=true;return}if(!this._helper.processEcmaVer()){this._bErrors=true;return}if(!this._helper.processOptions()){this._bErrors=true;return}if(!this._helper.processTitle()){this._bErrors=true;return}if(!this._helper.processRetCode()){this._bErrors=true;return}if(!this._config.extends){this._cleanConfigPaths()}if(this._config.typescript&&(val=this._config.typescript.tsconfig)){if(!(this._tsCfgObj=this._loadTsConfig(val))){this._bErrors=true;return}}};Config.prototype.validateRetCode=function(val,cb){return this._helper.validateRetCode(val,cb)};Config.prototype._cleanConfigPaths=function(){var src,i,ftype,dir;if(!this._config.extends){this._info("[Info]: Using config base '"+this._config.base+"'","I")}src=this._config.files;if(src){for(i=0;i<src.length;i++){if(!src[i].startsWith("http")){if(!nodeDeps.path.isAbsolute(src[i])){src[i]=nodeDeps.path.normalize(src[i]);src[i]=nodeDeps.path.resolve(this._config.base,src[i])}}}}src=this._config.exclude;if(src){for(i=0;i<src.length;i++){if(!nodeDeps.path.isAbsolute(src[i])){src[i]=nodeDeps.path.normalize(src[i]);src[i]=nodeDeps.path.resolve(this._config.base,src[i])}}}src=this._config.components;if(src){for(i=0;i<src.length;i++){if(!nodeDeps.path.isAbsolute(src[i])){dir=nodeDeps.path.normalize(src[i]);dir=nodeDeps.path.resolve(this._config.base,dir);this._config.components[i]=dir}}}src=this._config.outPath;if(src&&src!=="$noout"){if(!nodeDeps.path.isAbsolute(src)){src=nodeDeps.path.normalize(src);src=nodeDeps.path.resolve(this._config.base,src);this._config.outPath=src}}src=this._config.rulePacks;if(src){for(i=0;i<src.length;i++){if(!nodeDeps.path.isAbsolute(src[i].path)){dir=nodeDeps.path.normalize(src[i].path);src[i].path=nodeDeps.path.resolve(this._config.base,dir)}if(src[i].path.endsWith(".zip")){continue}ftype=nodeDeps.fsUtils.getFileType(src[i].path);if(ftype!=="d"){this._error("'rulePacks (entry "+(i+1)+"): path' is not a directory - \""+src[i].path+"\"");this._bErrors=true;return}}}if(this._config.typescript&&this._config.typescript.tsconfig)src=this._config.typescript.tsconfig;if(src&&typeof src==="string"){if(!nodeDeps.path.isAbsolute(src)){dir=nodeDeps.path.normalize(src);dir=nodeDeps.path.resolve(this._config.base,dir)}else{dir=src}if(!dir.endsWith(TSCONFIG)){dir=nodeDeps.path.join(dir,TSCONFIG)}this._config.typescript.tsconfig=dir}if(this._bErrors){return};};Config.prototype._cleanBase=function(){var p,ft;p=this._config.base;p=nodeDeps.path.normalize(p);p=nodeDeps.path.resolve(this._dir,p);ft=nodeDeps.fsUtils.getFileType(p);if(ft!=="d"){this._error(`Config file 'base' is not a directory - '${p}'`);this._bErrors=true;return false}p=nodeDeps.path.join(p,"/");this._config.base=p;this._info(`[Info]: Using Config base '${p}'`,"I");return true};Config.prototype._loadConfig=function(iniPath){var data,stats,bUseDefaults=false,msg;try{stats=nodeDeps.fs.statSync(iniPath);if(!stats.isFile()){this._warn("\n[Warn]: Config file '"+iniPath+"' not found. Using defaults.\n");bUseDefaults=true}else{data=nodeDeps.fs.readFileSync(iniPath,"utf8");data=nodeDeps.decomment(data);data=this.processIncludes(data,iniPath);data=this.processTokens(data);if(this._bErrors){return}if(this._isDebug){if(!data){console.log("NO CONFIG DATA")}else{var a=data.split("\n");console.log("------------- Config Raw Text...");for(var i=0;i<a.length;i++){console.log(i+1+"] "+a[i])}console.log("-".repeat(40))}}if(data){this._config=JSON.parse(nodeDeps.decomment(data))}else{this._bErrors=true}}}catch(e){this._bErrors=true;if(e.code){if(e.message.startsWith("ENOENT:")){this._warn("\nConfig file \""+iniPath+"\" not found - using defaults.\n");this._bErrors=false;bUseDefaults=true}}else if(e.toString().startsWith("SyntaxError")){msg=_convertMsgToRowCol(e.message,data,this._utils)}else{msg=e.message}if(msg){msg=msg.replace(/\r/g,"");msg=msg.replace(/ +(?= )/g,"");this._error("Config parse error");this._error("Config file '"+iniPath+"' - "+msg)}}if(this._bErrors){return}if(bUseDefaults){this._config={exclude:["./**/*-min.js","./**/*-min.css","./**/node_modules/**/*.*"],builtinJetRules:true,builtinCspRules:false,builtinJetWcRules:false,builtinJetWcOracleRules:false,builtinOjcMigrationRules:false,followLinks:true,severity:this._severity.ALL,format:"prose",ecmaVer:DEFAULTS.ECMAVER,options:{verbose:false,color:true}}}return bUseDefaults};Config.prototype._checkProperties=function(){return this._helper.checkPropNames()};Config.prototype._loadTsConfig=function(fp){return nodeDeps.jsonLoader.load(fp,nodeDeps,m=>{this._error(`Error loading tsconfig : ${m}.`);this._bErrors=true},false,this._utils)};function _convertMsgToRowCol(msg,data,utils){var x,n,rc;x=msg.indexOf("position");if(x<0){return msg}n=parseInt(msg.substr(x+8).trim());rc=utils.getRowColFromIndex(data,n);return msg.substr(0,x)+"row "+rc.row+", col "+rc.col};Config.prototype.processTokens=function(data){const TOKENS="\"tokens\"";var token,sub,start,end,json,toks,count,subst,rc,x,n;if(this._isDebug){this._debug("Performing config 'tokens' substitution...")}x=data.indexOf(TOKENS);if(x<0)return data;x+=TOKENS.length;n=this._expect(data,x,":",true);if(n<0){rc=this._utils.getRowColFromIndex(data,x);this._error("Config: expected ':' after property "+TOKENS+" on line "+rc.row+" position "+rc.col+".");this._bErrors=true;return}n=this._expect(data,n,"{");if(n<0){rc=this._utils.getRowColFromIndex(data,n);this._error("Config: expected '{' after property "+TOKENS+" on line "+rc.row+".");this._bErrors=true;return}start=n;end=data.indexOf("}",start);if(end<0){rc=this._utils.getRowColFromIndex(data,x);this._error("Config: "+TOKENS+" property syntax error (on/after line "+rc.row+").");this._bErrors=true;return}json=data.substring(start,end+1);try{toks=JSON.parse(json)}catch(e){rc=this._utils.getRowColFromIndex(data,x);this._error("Config: syntax error "+TOKENS+" property (on/after line "+rc.row+").");this._bErrors=true;return}subst=0;count=0;for(token in toks){if(token.charAt(0)!=="@"){this._error("Config: token '"+token+"' : must be prefixed with '@'");this._bErrors=true;return}sub=toks[token];token=token.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");token=new RegExp(token,"g");if(this._isVerbose||this._isDebug){n=data.match(token).length;subst+=n>1?--n:0}data=data.replace(token,sub);count++}if(count){try{start=data.indexOf(TOKENS);start=this._expect(data,start+TOKENS.length,":",true);start=this._expect(data,start,"{");end=data.indexOf("}",start+1);data=data.substring(0,start)+json+data.substring(end+1);if(this._isVerbose||this._isDebug){this._info("[Info]: "+subst+" config token substitution"+(subst!==1?"s":"")+" performed with "+count+" token"+(count!==1?"s":"")+".")}}catch(e){this._error("Config: \"tokens\" substitution failed - review \"tokens\" property value");this._bErrors=true}}return data};Config.prototype._expect=function(data,x,s,bump){var ret=-1;x=this._utils.eatWhitespace(data,x);if(x>=0&&data.substr(x,s.length)===s){ret=x+(bump?s.length:0)}return ret};Config.prototype.processIncludes=function(data,filepath,chain){var a,i,line,x,path,comma;var inserts,insert,incPath;if(this._isDebug){this._debug("Checking for "+(chain?"sub ":"")+"@include. . .")}if((i=data.indexOf(AT_INCLUDE))<0||data.charAt(i-1)==="_"){if(this._isDebug){this._debug("No "+(chain?"sub ":"")+"@include found")}return data}inserts=[];a=data.split("\n");for(i=0;i<a.length;i++){line=a[i];x=line.indexOf(AT_INCLUDE);if(x<0){continue}path=_extractStringFromLine(line,x+AT_INCLUDE.length,this._utils);if(!path){this._error("Config - @include syntax error"+(chain?" in '"+filepath+"'":"!"));return null}incPath=nodeDeps.path.normalize(path);incPath=nodeDeps.path.resolve(this._dir,incPath);comma=_isTrailingComma(line,x+AT_INCLUDE.length,this._utils);try{if(this._isDebug){this._debug("Reading @include -> "+incPath)}insert=nodeDeps.fs.readFileSync(incPath,"utf8")}catch(e){this._error("Config @include - "+e);return null}if(!insert){this._error("Config - @include '"+incPath+"' not found!");return null}insert=this.processIncludes(insert,incPath,true);if(insert){inserts.push(i);inserts.push(insert+(comma?",":""))}else if(insert===null){return null}}if(inserts&&inserts.length){for(i=0;i<inserts.length;i++){a[inserts[i]]=inserts[++i]}}return a.join("\n")};function _extractStringFromLine(data,start,utils){var c,xEnd,wantQuote,antiQuote;start=utils.eatWhitespace(data,start);if(start<0){return null}c=data.charAt(start);wantQuote=c===QUOTE||c==="'"?c:null;if(wantQuote){antiQuote=c===QUOTE?"'":QUOTE;start++}for(xEnd=start;xEnd<data.length;xEnd++){c=data.charAt(xEnd);if(c===")"||wantQuote&&c===wantQuote){break}else if(c==="\n"||wantQuote&&c===antiQuote||!wantQuote&&(c===QUOTE||c==="'")){xEnd=-1;break}}if(xEnd<0||xEnd>=data.length||wantQuote&&data.charAt(xEnd)!==wantQuote){return null}data=data.substring(start,xEnd).trim();return data?data:null};function _isTrailingComma(s,x,utils){var n,ret=false;n=s.indexOf(")",x);if(n<0){return false}n=utils.eatWhitespace(s,n+1);if(n>=0){ret=s.charAt(n)===","}return ret};function _cloneConfig(o){return JSON.parse(JSON.stringify(o))};module.exports=Config;
|
|
6
|
+
const Helper=require("./ConfigLib");const MACROS=require("../lib/macros");const DEFAULTS=require("./defaults");var JET_VERSIONS;const TYPE_BOOLEAN="boolean";const AT_INCLUDE="@include(";const QUOTE="\"";const TSCONFIG="tsconfig.json";var Config=function(nd,base,iniPath,fnApplyMacros,rules,severity,cliGroups,cliSev,msgCtx,modeCtx,utils,fsUtils,cbDebug){this._path=iniPath;this._dir=null;this._config=null;this._tsCfgObj=null;this._preBuilt=false;this._isOJET=modeCtx.isOJET;this._isCLI=modeCtx.isCLI;this._isAPI=modeCtx.isAPI;this._isAMD=modeCtx.isAMD;this._isCliMode=modeCtx.isCLI||modeCtx.isOJETCLI;this._rules=rules;this._utils=utils;this._fsUtils=fsUtils;this._severity=severity;this._helper=new Helper(this,nd,severity,utils,fsUtils,msgCtx,modeCtx);this.applyMacros=fnApplyMacros;this._bErrors=false;this._console=msgCtx.console;this._error=msgCtx.error;this._warn=msgCtx.warn;this._info=msgCtx.info;this._debug=msgCtx.debug;this._isDebug=msgCtx.isDebug;this._isVerbose=msgCtx.isVerbose;JET_VERSIONS=nd.jetver.getVersions();this._cliGroups=cliGroups;this._cliSev=cliSev;this._nd=nd;if(iniPath){this._init(base,iniPath,cbDebug)}};Config.prototype.getConfig=function(){var tmp=JSON.parse(JSON.stringify(this._config));if(tmp._sev){delete tmp._sev}return tmp};Config.prototype.getFiles=function(){return this._config.files};Config.prototype.getExclude=function(){return this._config.exclude};Config.prototype.getOptions=function(){return this._config.options};Config.prototype.getJetVer=function(){return this._config.jetVer};Config.prototype.getComponentsBaseUrl=function(){return this._config.componentsBaseUrl};Config.prototype.getComponentsBase=function(){return this._config.componentsBase};Config.prototype.getComponents=function(){return this._config.components};Config.prototype.getComponentUrls=function(){return this._config.componentUrls};Config.prototype.getJetCorePack=function(){return this._config.jetCorePack};Config.prototype.getComponentOptions=function(){return this._config.componentOptions};Config.prototype.getTypescript=function(){return this._config.typescript};Config.prototype.getTsConfig=function(){var ret;if(this._config.typescript){ret=this._config.typescript.tsconfig}return ret};Config.prototype.getMarkdownOptions=function(){return this._config.markdownOptions};Config.prototype.getTsConfigObj=function(){return this._tsCfgObj};Config.prototype.getOutPath=function(){return this._config.outPath};Config.prototype.getRulePacks=function(){return this._config.rulePacks};Config.prototype.getRuleMods=function(){return this._config.ruleMods};Config.prototype.getEnable=function(){return this._config.ruleMods&&this._config.ruleMods.enable?this._config.ruleMods.enable:undefined};Config.prototype.getDisable=function(){return this._config.ruleMods&&this._config.ruleMods.disable?this._config.ruleMods.disable:undefined};Config.prototype.getRuleDescriptions=function(){return this._config.ruleDescriptions};Config.prototype.getRulesFired=function(){return this._config.rulesFired};Config.prototype.getGroups=function(){return this._config.groups};Config.prototype.setGroups=function(groups){this._config.groups=groups};Config.prototype.getDefGroups=function(){return this._config.defGroups};Config.prototype.getRunRuleNames=function(){return this._config.ruleNames};Config.prototype.isBuiltinJetRules=function(){return this._config.builtinJetRules};Config.prototype.isBuiltinCspRules=function(){return this._config.builtinCspRules};Config.prototype.isBuiltinJetWcRules=function(){return this._config.builtinJetWcRules};Config.prototype.isBuiltinJetWcOracleRules=function(){return this._config.builtinJetWcOracleRules};Config.prototype.isBuiltinSpocRules=function(){return this._config.builtinSpocRules};Config.prototype.isBuiltinOjcMigrationRules=function(){return this._config.builtinOjcMigrationRules};Config.prototype.isBuiltinWebDriverTestRules=function(){return this._config.builtinWebDriverTestRules};Config.prototype.getMessages=function(){return this._config.messages};Config.prototype.setMessages=function(msgid,state){return this._helper.setMessages(msgid,state)};Config.prototype.getFollowLinks=function(){return this._config.followLinks};Config.prototype.getFormat=function(){return this._config.format};Config.prototype.getProseFormat=function(){return this._config.proseFormat};Config.prototype.getLineFormat=function(){return this._config.lineFormat};Config.prototype.getBase=function(){return this._config.base};Config.prototype.getStylesets=function(){return this._config.stylesets};Config.prototype.getNameSpaces=function(){return this._config.nameSpaces};Config.prototype.getCommon=function(){return this._config.common||{}};Config.prototype.getSeverity=function(){return this._config.severity};Config.prototype.setSeverity=function(severity){return this._config.severity=severity};Config.prototype.getSevMap=function(){return this._config.sevMap};Config.prototype.getTheme=function(){return this._config.theme};Config.prototype.getComments=function(){return this._config.comments};Config.prototype.getEcmaVer=function(){return this._config.ecmaVer};Config.prototype.getTabs=function(){return this._config.tabs};Config.prototype.getTitle=function(){return this._config.title};Config.prototype.getRetCode=function(){var ret,o;if(this._config&&this._config.options){o=this._config.options;if(o.retCode!==undefined){ret=o.retCode}else if(o.rc!==undefined){ret=o.rc}else{ret="auto"}}else{ret="auto"}return ret};Config.prototype.isOk=function(){return!this._bErrors};Config.prototype.getUserDefs=function(){return this._config.userDefs};Config.prototype.getAppendFileList=function(){return this._helper.getAddFileList()};Config.prototype.getJetPagesOnly=function(){return this._config.jetPagesOnly};Config.prototype.getTempDir=function(){return this._config.tempDir};Config.prototype.getOrigConfig=function(){return this._origConfig};Config.prototype.get$JetCore=function(){return this._config.$JetCore};Config.prototype._init=function(base,iniPath,cbDebug){var i,s,val,val2,bUseDefaults=false;if(typeof iniPath==="string"){this._dir=this._nd.path.dirname(iniPath);bUseDefaults=this._loadConfig(iniPath);if(this._bErrors){return}}else{this._config=iniPath;this._dir=this._nd.process.cwd();this._preBuilt=true}this._origConfig=this._config;this._config=_cloneConfig(this._config);this._helper.setConfig(this._config,this._preBuilt?null:iniPath,this._dir);if(this._config.options){this._isVerbose=!!this._config.options.verbose;this._isDebug=!!this._config.options.debug;cbDebug(this._isVerbose,this._isDebug);this._helper.setDebugStatus(this._isVerbose,this._isdebug)}if(!this._checkProperties()){this._bErrors=true;return}if(base){this._config.base=base}if(!this._config.base){this._config.base=this._dir}if(this._config.base===MACROS.cwd){this._config.base=this._nd.process.cwd()}if(!this._cleanBase()){return}if(!bUseDefaults&&!this._isOJET){this._info("[Info]: Analyzing "+(typeof iniPath==="string"?"config '"+iniPath+"'":"pre-built config object"),"I",true)}if(this._config.extends){if(!this._helper.processExtends()){this._bErrors=true;return}}if(typeof this._config.builtinJetRules!==TYPE_BOOLEAN){this._config.builtinJetRules=true}if(typeof this._config.builtinCspRules!==TYPE_BOOLEAN){this._config.builtinCspRules=false}if(typeof this._config.builtinJetWcRules!==TYPE_BOOLEAN){this._config.builtinJetWcRules=false}if(typeof this._config.builtinJetWcOracleRules!==TYPE_BOOLEAN){this._config.builtinJetWcOracleRules=false}if(typeof this._config.builtinWebDriverTestRules!==TYPE_BOOLEAN){this._config.builtinWebDriverTestRules=false}if(this._config.builtinSpocRules){if(typeof this._config.builtinSpocRules!==TYPE_BOOLEAN){this._error("Config entry 'builtinSpocRules' must be a boolean!");this._bErrors=true;return}if(this._config.builtinSpocRules){this._config.builtinJetRules=this._config.builtinJetWcRules=this._config.builtinJetWcOracleRules=false}}if(this._config.builtinOjcMigrationRules){if(typeof this._config.builtinOjcMigrationRules!==TYPE_BOOLEAN){this._error("Config entry 'builtinOjcMigrationRules' must be a boolean!");this._bErrors=true;return}else{this._config.builtinJetRules=this._config.builtinJetWcRules=this._config.builtinJetWcOracleRules=this._config.builtinCspRules=this._config.builtinSpocRules=false}}else{this._config.builtinOjcMigrationRules=false}this._config.jetPagesOnly=!!this._config.jetPagesOnly;if(!this._config.files){this._config.files=[]}if(!this._config.options){this._config.options={}}if(this._config.jetVer){val=this._config.jetVer;if(typeof val!=="string"){this._error("Config entry 'jetVer' is not a string!");this._bErrors=true;return}val=val.trim();val2=val.split(".");for(i=0;i<val2.length;i++){if(i===0&&val2[0].charAt(0).toLowerCase()==="v"){val2[0]=val2[0].substring(1)}s=parseInt(val2[i]);if(isNaN(s)){let part=["major","minor","patch"];this._error(`Config entry 'jetVer' --> '${val}' : '${part[i]}' value is invalid`);this._bErrors=true;return}val2[i]=""+s}val=val2.join(".");if(val2.length!==3||val2[2]==="0"){s=val2.length===3;val2=this._nd.jetver.getBestVersion(val,val2);if(!val2){s=s?`Config entry 'jetVer' --> '${val}' cannot be resolved to a supported JET version`:`Config entry 'jetVer' --> '${val}' is not a supported JET version`;this._error(s);this._bErrors=true;return}val=val2}if(!JET_VERSIONS[val]){this._error(`Config entry 'jetVer' --> '${val}' is not a supported JET version!`);this._bErrors=true;return}this._config.jetVer=val}else{this._config.jetVer=DEFAULTS.JETVER}if(!this._helper.processJetCorePack()){this._bErrors=true;return}if(!this._helper.processWebComponents()){this._bErrors=true;return}if(!this._helper.processRulePacks()){this._bErrors=true;return}if(!this._helper.processRuleMods()){this._bErrors=true;return}if(!this._helper.processFormat()){this._bErrors=true;return}if(!this._helper.processProseFormat()){this._bErrors=true;return}if(!this._helper.processLineFormat()){this._bErrors=true;return}if(!this._helper.processRuleDescriptions()){this._bErrors=true;return}if(!this._helper.processRulesFired()){this._bErrors=true;return}if(!this._helper.processSevMap()){this._bErrors=true;return}if(!this._helper.processSeverity(this._cliSev)){this._bErrors=true;return}if(!this._helper.processGroups(this._cliGroups)){this._bErrors=true;return}if(!this._helper.processDefGroups()){this._bErrors=true;return}if(!this._helper.processRuleNames()){this._bErrors=true;return}if(this._config.followLinks==null){this._config.followLinks=true}else{this._config.followLinks=!!this._config.followLinks}if(!Array.isArray(this._config.files)){this._error("Config entry 'files' is not an array!");this._bErrors=true;return}if(!this._helper.validateFileList(this._config.files)){this._bErrors=true;return}if(this._config.exclude){if(!Array.isArray(this._config.exclude)){this._error("Config entry 'exclude' is not an array!");this._bErrors=true;return}if(!this._helper.validateFileList(this._config.exclude)){this._bErrors=true;return}}else if(this._config.excludes){this._error("Config property 'excludes' found - did you mean 'exclude'?");this._bErrors=true;return}if(!this._helper.processAddFileList()){this._bErrors=true;return}if(this._config.stylesets){val=this._config.stylesets;if(!Array.isArray(val)){this._error("Config property 'stylesets' is not an array!");this._bErrors=true;return}}if(this._isAMD&&this._config.tempDir){this._error("Config entry 'tempDir' is not valid in AMD mode!");this._bErrors=true;return}if(this._config.tempDir){if(typeof this._config.tempDir!=="string"){this._error("Config property 'tempDir' is not a string!");this._bErrors=true;return}if(this._config.tempDir.startsWith(".")){this._config.tempDir=this._nd.path.resolve(this._nd.process.cwd(),this._config.tempDir)}}if(!this._helper.processTypeScript()){this._bErrors=true;return}if(!this._helper.processMarkdownOpts()){this._bErrors=true;return}if(!this._helper.processMessages()){this._bErrors=true;return}if(!this._helper.processNameSpaces()){this._bErrors=true;return}if(!this._helper.processTheme()){this._bErrors=true;return}if(!this._helper.processComments()){this._bErrors=true;return}if(!this._helper.processEcmaVer()){this._bErrors=true;return}if(!this._helper.processOptions()){this._bErrors=true;return}if(!this._helper.processTitle()){this._bErrors=true;return}if(!this._helper.processRetCode()){this._bErrors=true;return}if(!this._config.extends){this._cleanConfigPaths()}if(this._config.typescript&&(val=this._config.typescript.tsconfig)){if(!(this._tsCfgObj=this._loadTsConfig(val))){this._bErrors=true;return}}};Config.prototype.validateRetCode=function(val,cb){return this._helper.validateRetCode(val,cb)};Config.prototype._cleanConfigPaths=function(){var src,i,ftype,dir;var nd=this._nd;var base=this._config.base;function _resolve(fp){if(!nd.path.isAbsolute(fp)){fp=nd.path.normalize(fp);fp=nd.path.resolve(base,fp)}return fp};if(!this._config.extends){this._info("[Info]: Using config base '"+this._config.base+"'","I")}if(src=this._config.files){for(i=0;i<src.length;i++){if(!src[i].startsWith("http")){src[i]=_resolve(src[i])}}}if(src=this._config.exclude){for(i=0;i<src.length;i++){src[i]=_resolve(src[i])}}if(src=this._config.components){for(i=0;i<src.length;i++){src[i]=_resolve(src[i])}}src=this._config.outPath;if(src&&src!=="$noout"){this._config.outPath=_resolve(src)}src=this._config.rulePacks;if(src){for(i=0;i<src.length;i++){if(!nd.path.isAbsolute(src[i].path)){dir=nd.path.normalize(src[i].path);src[i].path=nd.path.resolve(this._config.base,dir)}if(src[i].path.endsWith(".zip")){continue}ftype=this._fsUtils.getFileType(src[i].path);if(ftype!=="d"){this._error("'rulePacks (entry "+(i+1)+"): path' is not a directory - \""+src[i].path+"\"");this._bErrors=true;return}}}if(this._config.typescript&&this._config.typescript.tsconfig)src=this._config.typescript.tsconfig;if(src&&typeof src==="string"){if(!nd.path.isAbsolute(src)){dir=nd.path.normalize(src);dir=nd.path.resolve(this._config.base,dir)}else{dir=src}if(!dir.endsWith(TSCONFIG)){dir=nd.path.join(dir,TSCONFIG)}this._config.typescript.tsconfig=dir}if(src=this._config.jetCorePack){this._config.jetCorePack=_resolve(src)}if(this._bErrors){return};};Config.prototype._cleanBase=function(){var p,ft;var nd=this._nd;p=this._config.base;p=nd.path.normalize(p);p=nd.path.resolve(this._dir,p);ft=this._fsUtils.getFileType(p);if(ft!=="d"){this._error(`Config file 'base' is not a directory - '${p}'`);this._bErrors=true;return false}p=nd.path.join(p,"/");this._config.base=p;this._info(`[Info]: Using Config base '${p}'`,"I");return true};Config.prototype._loadConfig=function(iniPath){var data,stats,bUseDefaults=false,msg;var nd=this._nd;try{stats=nd.fs.statSync(iniPath);if(!stats.isFile()){this._warn("\n[Warn]: Config file '"+iniPath+"' not found. Using defaults.\n");bUseDefaults=true}else{data=nd.fs.readFileSync(iniPath,"utf8");data=nd.decomment(data);data=this.processIncludes(data,iniPath);data=this.processTokens(data);if(this._bErrors){return}if(this._isDebug){if(!data){console.log("NO CONFIG DATA")}else{var a=data.split("\n");console.log("------------- Config Raw Text...");for(var i=0;i<a.length;i++){console.log(i+1+"] "+a[i])}console.log("-".repeat(40))}}if(data){this._config=JSON.parse(nd.decomment(data))}else{this._bErrors=true}}}catch(e){this._bErrors=true;if(e.code){if(e.message.startsWith("ENOENT:")){this._warn("\nConfig file \""+iniPath+"\" not found - using defaults.\n");this._bErrors=false;bUseDefaults=true}}else if(e.toString().startsWith("SyntaxError")){msg=_convertMsgToRowCol(e.message,data,this._utils)}else{msg=e.message}if(msg){msg=msg.replace(/\r/g,"");msg=msg.replace(/ +(?= )/g,"");this._error("Config parse error");this._error("Config file '"+iniPath+"' - "+msg)}}if(this._bErrors){return}if(bUseDefaults){this._config={exclude:["./**/*-min.js","./**/*-min.css","./**/node_modules/**/*.*"],builtinJetRules:true,builtinCspRules:false,builtinJetWcRules:false,builtinJetWcOracleRules:false,builtinOjcMigrationRules:false,followLinks:true,severity:this._severity.ALL,format:"prose",ecmaVer:DEFAULTS.ECMAVER,options:{verbose:false,color:true}}}return bUseDefaults};Config.prototype._checkProperties=function(){return this._helper.checkPropNames()};Config.prototype._loadTsConfig=function(fp){return this._nd.jsonLoader.load(fp,this._nd,m=>{this._error(`Error loading tsconfig : ${m}.`);this._bErrors=true},false,this._utils)};function _convertMsgToRowCol(msg,data,utils){var x,n,rc;x=msg.indexOf("position");if(x<0){return msg}n=parseInt(msg.substr(x+8).trim());rc=utils.getRowColFromIndex(data,n);return msg.substr(0,x)+"row "+rc.row+", col "+rc.col};Config.prototype.processTokens=function(data){const TOKENS="\"tokens\"";var token,sub,start,end,json,toks,count,subst,rc,x,n;if(this._isDebug){this._debug("Performing config 'tokens' substitution...")}x=data.indexOf(TOKENS);if(x<0)return data;x+=TOKENS.length;n=this._expect(data,x,":",true);if(n<0){rc=this._utils.getRowColFromIndex(data,x);this._error("Config: expected ':' after property "+TOKENS+" on line "+rc.row+" position "+rc.col+".");this._bErrors=true;return}n=this._expect(data,n,"{");if(n<0){rc=this._utils.getRowColFromIndex(data,n);this._error("Config: expected '{' after property "+TOKENS+" on line "+rc.row+".");this._bErrors=true;return}start=n;end=data.indexOf("}",start);if(end<0){rc=this._utils.getRowColFromIndex(data,x);this._error("Config: "+TOKENS+" property syntax error (on/after line "+rc.row+").");this._bErrors=true;return}json=data.substring(start,end+1);try{toks=JSON.parse(json)}catch(e){rc=this._utils.getRowColFromIndex(data,x);this._error("Config: syntax error "+TOKENS+" property (on/after line "+rc.row+").");this._bErrors=true;return}subst=0;count=0;for(token in toks){if(token.charAt(0)!=="@"){this._error("Config: token '"+token+"' : must be prefixed with '@'");this._bErrors=true;return}sub=toks[token];token=token.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");token=new RegExp(token,"g");if(this._isVerbose||this._isDebug){n=data.match(token).length;subst+=n>1?--n:0}data=data.replace(token,sub);count++}if(count){try{start=data.indexOf(TOKENS);start=this._expect(data,start+TOKENS.length,":",true);start=this._expect(data,start,"{");end=data.indexOf("}",start+1);data=data.substring(0,start)+json+data.substring(end+1);if(this._isVerbose||this._isDebug){this._info("[Info]: "+subst+" config token substitution"+(subst!==1?"s":"")+" performed with "+count+" token"+(count!==1?"s":"")+".")}}catch(e){this._error("Config: \"tokens\" substitution failed - review \"tokens\" property value");this._bErrors=true}}return data};Config.prototype._expect=function(data,x,s,bump){var ret=-1;x=this._utils.eatWhitespace(data,x);if(x>=0&&data.substr(x,s.length)===s){ret=x+(bump?s.length:0)}return ret};Config.prototype.processIncludes=function(data,filepath,chain){var a,i,line,x,path,comma;var inserts,insert,incPath;var nd=this._nd;if(this._isDebug){this._debug("Checking for "+(chain?"sub ":"")+"@include. . .")}if((i=data.indexOf(AT_INCLUDE))<0||data.charAt(i-1)==="_"){if(this._isDebug){this._debug("No "+(chain?"sub ":"")+"@include found")}return data}inserts=[];a=data.split("\n");for(i=0;i<a.length;i++){line=a[i];x=line.indexOf(AT_INCLUDE);if(x<0){continue}path=_extractStringFromLine(line,x+AT_INCLUDE.length,this._utils);if(!path){this._error("Config - @include syntax error"+(chain?" in '"+filepath+"'":"!"));return null}incPath=nd.path.normalize(path);incPath=nd.path.resolve(this._dir,incPath);comma=_isTrailingComma(line,x+AT_INCLUDE.length,this._utils);try{if(this._isDebug){this._debug("Reading @include -> "+incPath)}insert=nd.fs.readFileSync(incPath,"utf8")}catch(e){this._error("Config @include - "+e);return null}if(!insert){this._error("Config - @include '"+incPath+"' not found!");return null}insert=this.processIncludes(insert,incPath,true);if(insert){inserts.push(i);inserts.push(insert+(comma?",":""))}else if(insert===null){return null}}if(inserts&&inserts.length){for(i=0;i<inserts.length;i++){a[inserts[i]]=inserts[++i]}}return a.join("\n")};function _extractStringFromLine(data,start,utils){var c,xEnd,wantQuote,antiQuote;start=utils.eatWhitespace(data,start);if(start<0){return null}c=data.charAt(start);wantQuote=c===QUOTE||c==="'"?c:null;if(wantQuote){antiQuote=c===QUOTE?"'":QUOTE;start++}for(xEnd=start;xEnd<data.length;xEnd++){c=data.charAt(xEnd);if(c===")"||wantQuote&&c===wantQuote){break}else if(c==="\n"||wantQuote&&c===antiQuote||!wantQuote&&(c===QUOTE||c==="'")){xEnd=-1;break}}if(xEnd<0||xEnd>=data.length||wantQuote&&data.charAt(xEnd)!==wantQuote){return null}data=data.substring(start,xEnd).trim();return data?data:null};function _isTrailingComma(s,x,utils){var n,ret=false;n=s.indexOf(")",x);if(n<0){return false}n=utils.eatWhitespace(s,n+1);if(n>=0){ret=s.charAt(n)===","}return ret};function _cloneConfig(o){return JSON.parse(JSON.stringify(o))};module.exports=Config;
|