@oracle/oraclejet-audit 12.0.0 → 12.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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;
@@ -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/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
+ 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,jetVer){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;
package/lib/DomUtils.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 jsonParser=require('really-relaxed-json').createParser();const HtmlUtils=require('./HtmlUtils');const NodeType=require('./NodeTypes');const OJCOMPONENT='ojComponent';const COMPONENT='component';const SVG_PATH_COMMANDS=['M','m','L','I','H','h','V','v','C','c','S','s','Q','q','T','t','A','a','Z','z'];const DOT='.';const ON_DASH='on-';function DomUtils(nodeDeps,appContext,oTabs,fileIndex){this._tree=null;this._nodeDeps=nodeDeps;this._appContext=appContext;this._tabs=oTabs;this._utils=appContext.utils;this._fileIndex=fileIndex};DomUtils.prototype.getFirst=function(){return this._tree.length?this._tree[0]:null};DomUtils.prototype.getLast=function(){var node;node=this._tree.length?this._tree[this._tree.length-1]:null;while(node&&node.children&&node.children.length){node=node.children[node.children.length-1]}return node};DomUtils.prototype.getFirstElem=function(){var node=this.getFirst();while(node){if(node.type===NodeType.TAG){break};node=node.next}return node};DomUtils.prototype.getChildren=function(node){return node.children};DomUtils.prototype.getParent=function(node){return node.parent};DomUtils.prototype.getSiblings=function(node){var parent;if(parent=this.getParent(node)){return this.getChildren(parent)}else{return this._tree}};DomUtils.prototype.getNext=function(node){return node.next||null};DomUtils.prototype.getAttribs=function(node){return node.attribs||null};DomUtils.prototype.getAttribValue=function(node,name){return node.attribs?node.attribs[name]:undefined};DomUtils.prototype.getAttribRawValue=function(ruleCtx,name){var val,pos;if(ruleCtx.tagNode.attribs){if(typeof(val=ruleCtx.tagNode.attribs[name])==='string'){pos=this.getAttrPosition(ruleCtx.data,ruleCtx.tagNode,name);return _getAttrRawValue(ruleCtx.data,pos.start,name,val,ruleCtx.utils.utils)}}};DomUtils.prototype.hasAttrib=function(node,name){return!!node.attribs&&hasOwnProperty.call(node.attribs,name)};DomUtils.prototype.hasChildren=function(node){return!!node.children};DomUtils.prototype.hasNext=function(node){return!!node.next};DomUtils.prototype.getName=function(node){return node.name};DomUtils.prototype.getType=function(node){return node.type};DomUtils.prototype.getElemsByName=function(name){var a=[],i,names;if(!this._tree){return a}names=typeof name==='string'?[name]:name;for(i=0;i<names.length;i++){names[i]=names[i].toLowerCase()}for(i=0;i<this._tree.length;i++){_getElemsByName2(this._tree[i],a,names)}return a};function _getElemsByName2(node,a,names){var children,i;if((node.type===NodeType.TAG||node.type===NodeType.SCRIPT)&&names.indexOf(node.name.toLowerCase())>=0){a.push(node)}if(node.children){children=node.children;for(i=0;i<children.length;i++){_getElemsByName2(children[i],a,names)}}};DomUtils.prototype.getElemById=function(id,labelId){var node,i;if(!this._tree){return null}for(i=0;i<this._tree.length;i++){node=this._tree[i];if(node.type===NodeType.TAG||_isHtmlScript(node)){node=this._getElemById2(node,id,labelId);if(node){return node}}}return null};DomUtils.prototype._getElemById2=function(node,id,labelId){var curNode,attrib,attr,attribLower,i;if((node.type===NodeType.TAG||_isHtmlScript(node))&&node.attribs){for(attrib in node.attribs){attribLower=attrib.toLowerCase();if(attribLower==='id'||labelId&&attribLower==='label-id'){if(node.attribs[attrib]===id){return node}}else if(attrib==='data-bind'){attr=this.extractAttribsFromDataBind(node.attribs[attrib]);if(attr&&attr['id']===id){return node}}}}if(node.children){for(i=0;i<node.children.length;i++){curNode=this._getElemById2(node.children[i],id,labelId);if(curNode){return curNode}}}return null};DomUtils.prototype.getElems=function(){var a=[],i;if(!this._tree){return a}for(i=0;i<this._tree.length;i++){_getElems2(this._tree[i],a)}return a};function _getElems2(node,a){var children,i;if(node.type===NodeType.TAG||node.type===NodeType.SCRIPT){a.push(node)}if(node.children){children=node.children;for(i=0;i<children.length;i++){_getElems2(children[i],a)}}};DomUtils.prototype.getScripts=function(){var head,ch,a=[];if(head=this.getHead()){if(ch=head.children){ch.forEach(elem=>{if(elem.type===NodeType.TAG&&elem.name==='script'){a.push(elem)}})}}return a};DomUtils.prototype.getLinks=function(){var head,ch,a=[];if(head=this.getHead()){if(ch=head.children){ch.forEach(elem=>{if(elem.type===NodeType.TAG&&elem.name==='link'){a.push(elem)}})}}return a};DomUtils.prototype.getHead=function(){var elem,ch,i;if(!this._tree){return null}for(i=0;i<this._tree.length;i++){elem=this._tree[i];if(elem.type===NodeType.TAG&&elem.name==='html'){if(ch=elem.children){for(i=0;i<ch.length;i++){elem=ch[i];if(elem.type===NodeType.TAG&&elem.name==='head'){return elem}}}break}}return null};DomUtils.prototype.getBody=function(){var elem,ch,i;if(!this._tree){return null}for(i=0;i<this._tree.length;i++){elem=this._tree[i];if(elem.type===NodeType.TAG&&elem.name==='html'){if(ch=elem.children){for(i=0;i<ch.length;i++){elem=ch[i];if(elem.type===NodeType.TAG&&elem.name==='body'){return elem}}}break}}return null};DomUtils.prototype.getComponentElems=function(){var a=[],i;if(!this._tree){return a}for(i=0;i<this._tree.length;i++){this._getComponentElems2(this._tree[i],a)}return a};DomUtils.prototype._getComponentElems2=function(node,a){var children,i;if(node.type===NodeType.TAG&&this._appContext.metaLib.isWCTag(node.name)){a.push(node)}if(node.children){children=node.children;for(i=0;i<children.length;i++){this._getComponentElems2(children[i],a)}}};DomUtils.prototype.isCommonAttr=function(attrName){attrName=attrName.toLowerCase();attrName=attrName.charAt(0)===':'?attrName.substr(1):attrName;return HtmlUtils.isCommonAttr(attrName)};DomUtils.prototype.isCommonEventAttr=function(attrName){attrName=attrName.toLowerCase();attrName=attrName.charAt(0)===':'?attrName.substr(1):attrName;if(attrName.startsWith('on-oj-')){return false}if(attrName.startsWith('on-')){attrName=attrName.substring(0,2)+attrName.substring(3)}return HtmlUtils.isCommonEventAttr(attrName)};DomUtils.prototype.isCommonElem=function(elem){return HtmlUtils.isCommonElem(elem)};DomUtils.prototype.isSvgElem=function(elem){return HtmlUtils.isSvgElem(elem)};DomUtils.prototype.isHtml5ObsoleteElem=function(tag){return HtmlUtils.isHtml5ObsoleteElem(tag)};DomUtils.prototype.isHtml5ObsoleteAttr=function(tagName,attrName){return HtmlUtils.isHtml5ObsoleteAttr(tagName,attrName)};DomUtils.prototype.isSelfClosingTag=function(tag){return HtmlUtils.isSelfClosingTag(tag)};DomUtils.prototype.isNamespaceTag=function(tagName){if(this._appContext.metaLib.isJetTag(tagName)){return true}return HtmlUtils.isNamespaceTag(tagName)};DomUtils.prototype.isNamespacePrefix=function(tagPrefix){return!!HtmlUtils.isNamespacePrefix(tagPrefix)};DomUtils.prototype.isChildOfElem=function(elemName,node){return!!this.isChildOfElemNode(elemName,node)};DomUtils.prototype.isChildOfElemNode=function(elemName,node){var ret=null;while(node.parent){if(node.parent.name===elemName){ret=node.parent;break}node=node.parent}return ret};DomUtils.prototype.getDataBindComponent=function(context){var node,val,attrVal,ret=null;node=context.tagNode;if(this.getAttribs(node)){attrVal=this.getAttribValue(node,'data-bind');if(attrVal){val=this.extractComponentFromDataBind(attrVal);if(val){ret='oj.'+val}}}return ret};DomUtils.prototype.getDataBindAttr=function(context){return this.getDataBindAttrsFromNode(context,context.node)};DomUtils.prototype.getDataBindAttrs=function(context){return this.getDataBindAttrsFromNode(context,context.node)};DomUtils.prototype.getDataBindAttrsFromNode=function(context,node){var attrVal,ret=null;if(this.getAttribs(node)){attrVal=this.getAttribValue(node,'data-bind');if(attrVal){ret=this.extractAttribsFromDataBind(attrVal)}}return ret};DomUtils.prototype.extractComponentFromDataBind=function(attrValue){var dataBind,componentName,x;x=attrValue.indexOf(OJCOMPONENT);if(x<0){return}componentName=null;if(attrValue.length>OJCOMPONENT.length){dataBind=attrValue.substring(x+OJCOMPONENT.length);x=dataBind.indexOf(COMPONENT);if(x>=0){dataBind=dataBind.substring(x+COMPONENT.length).trim();if(dataBind.charAt(0)===':'){x=dataBind.indexOf('oj');if(x>=0){dataBind=dataBind.substring(x);componentName=_extractComponentName(dataBind,this._utils)}}}}return componentName};function _extractComponentName(s,utils){var componentName,i,c;for(i=0;i<s.length;i++){c=s.charAt(i);if(c==='\''||c==='"'||utils.isWhitespace(c)){componentName=s.substring(0,i);break}}return componentName};DomUtils.prototype.extractAttribsFromDataBind=function(attrValue){var s,a,nextAttr,val,i,j,x,ret=null;if(attrValue.indexOf(':')<0){return ret}a=attrValue.split('attr');if(a.length<2){return ret}for(i=0;i<a.length;i++){a[i]=s=a[i].trim();if(s.charAt(0)===':'){s=s.substr(1).trim();if(s.charAt(0)==='{'){try{ret=jsonParser.stringToJson(s);ret=JSON.parse(ret)}catch(e){s=s.substring(1).trim();a=s.split(':');for(j=0;j<a.length;j++){if(nextAttr){if(!ret){ret={}}ret[nextAttr]=val=a[j].replace(/['\"]/g,'').trim();x=val.lastIndexOf('}');if(x>=0){ret[nextAttr]=val.substring(0,x).trim();break}nextAttr=null}if(j+1===a.length){break}a[j]=s=a[j].trim();s=s.replace(/['\"]/g,'').trim();if(s.length===0)continue;if(!ret){ret={}}ret[s]=val=a[++j].trim();x=val.indexOf(',');if(x>=0){ret[s]=val.substring(0,x).replace(/['\"]/g,'').trim();nextAttr=val.substring(x+1).trim();nextAttr=nextAttr.replace(/['\"]/g,'').trim();val=val.substring(0,x).replace(/['\"]/g,'').trim()}else{ret[s]=val.replace(/['\"]/g,'').trim()}x=val.lastIndexOf('}');if(x>=0){ret[s]=val.substring(0,x).trim();break}}}}break}}return ret};DomUtils.prototype.getAttrPosition=function(data,node,attrName){var startIndex=this.getAttrIndex(data,node,attrName);var endIndex=startIndex+attrName.length-1;var rowCol=this._utils.getRowColFromIndex(data,startIndex,'html');rowCol.start=startIndex;rowCol.end=endIndex;return rowCol};DomUtils.prototype.getAttrValuePosition=function(data,node,attrName){var attrPos,pos,endPos,ws,ret,good;var isDouble,isSingle,isUnquoted;attrPos=this.getAttrPosition(data,node,attrName);if(!attrPos||attrPos.start===node.startIndex){return}if((pos=this._utils.eatWhitespace(data,attrPos.end+1))>=0){if(data.charAt(pos++)==='='){if((endPos=this._utils.eatWhitespace(data,pos))>=0){isDouble=data.charAt(endPos)==='"';isSingle=data.charAt(endPos)==='\'';isUnquoted=!(isSingle||isDouble);if(isDouble){if((endPos=data.indexOf('"',pos+1))>=0){good=true}}else if(isSingle){if((endPos=data.indexOf('\'',pos+1))>=0){good=true}}else if(isUnquoted){ws=this._utils.getIndexToWhitespace(data,pos);endPos=data.indexOf('>',pos);if(ws>=0&&endPos>=0){endPos=(endPos<ws?endPos:ws)-1;good=true}}if(good){attrPos=this.getLineCol(data,pos);ret={row:attrPos.row,col:attrPos.col,start:pos,end:endPos}}}}}return ret};DomUtils.prototype.getLineCol=function(data,index){return this._fileIndex.getRowCol(data,{start:index},'html')};DomUtils.prototype.getAttrIndex=function(data,node,attrName){var attribs,index,temp,c,i,isQuote=attrName==='"'||attrName==='\'';attribs=node.attribs;if(!attribs){this._appContext.assert('no attrs in tag '+node.name+'(expected attr \''+attrName+')');return node.startIndex}if(!attribs.hasOwnProperty(attrName)&&!attribs.hasOwnProperty(':'+attrName)){this._appContext.assert('expected attr \''+attrName+'\' in tag '+node.name);return node.startIndex}index=data.indexOf(attrName,node.startIndex);while(true){index=data.indexOf(attrName,index);if(index>=0){temp=data.substring(index+attrName.length,index+100);i=this._utils.eatWhitespace(temp);if(i<0){return node.startIndex}c=temp.charAt(i);if(c==='='||c==='>'||!isQuote&&this._utils.isWhitespace(temp.charAt(0))){return index}index+=i+1;continue}this._appContext.assert('expected attr \''+attrName+'\' in tag '+node.name);return node.startIndex}};DomUtils.prototype.isNonFragmentJetPage=function(context){return this.hasBody(context)&&this.isJetPage(context)};DomUtils.prototype.hasBody=function(context){var i,siblings,ret=false;siblings=this.getSiblings(context.node);for(i=0;i<siblings.length;i++){if(this._hasBody2(siblings[i])){ret=true;break}}return ret};DomUtils.prototype._hasBody2=function(node){var i,children,ret=false;if(node.type===NodeType.TAG&&node.name.toLowerCase()==='body'){return true}if(node.children){children=node.children;for(i=0;i<children.length;i++){if(this._hasBody2(children[i])){ret=true;break}}}return ret};DomUtils.prototype.isJetPage=function(context){var i,siblings,ret=false;siblings=this.getSiblings(context.node);for(i=0;i<siblings.length;i++){if(this._isJetPage2(siblings[i])){ret=true;break}}return ret};DomUtils.prototype._isJetPage2=function(node){var i,children,ret=false;if(node.type===NodeType.TAG&&node.name.toLowerCase().startsWith('oj-')){return true}if(node.children){children=node.children;for(i=0;i<children.length;i++){if(this._isJetPage2(children[i])){ret=true;break}}}return ret};DomUtils.prototype.isValidJson=function(value,data){var data,ret;if(value.charAt(0)!=='{'){return true}try{data=JSON.parse(this._nodeDeps.decomment(value));ret=!!data}catch(e){if(typeof data==='string'&&e.toString().startsWith('SyntaxError')){var obj=_convertMsgToRowCol(e.message,data,this._utils);ret.msg=obj.msg;ret.line=obj.row;ret.col=obj.col;ret.position=obj.position}else{ret=e.message}}return ret};DomUtils.prototype.isAttrExprConstant=function(expr){return HtmlUtils.isAttrExprConstant(expr)};const RE_EXPRESSION=/^(?:\[{2})(.*)(?:\]{2})$|^(?:\{{2})(.*)(?:\}{2})$/;DomUtils.prototype.isExpression=function(s){var ret=false;if(s){ret=RE_EXPRESSION.test(s.trim())}return ret};DomUtils.prototype.getExpression=function(s){var ret=null;if(this.isExpression(s)){ret=s.substring(2,s.length-2).trim()}return ret};DomUtils.prototype.isSvgPath=function(s){var c=s.trim().charAt(0);return SVG_PATH_COMMANDS.indexOf(c)>=0};DomUtils.prototype.camelCase=function(str){var parts,i;function _camelCase(str){return str.replace(/(?:^\w|[A-Z]|\b\w)/g,function(word,index){return index==0?word.toLowerCase():word.toUpperCase()}).replace(/-|\s+/g,'')};parts=str.split(DOT);for(i=0;i<parts.length;i++){parts[i]=_camelCase(parts[i])}return parts.join(DOT)};DomUtils.prototype.kebabCase=function(str){return str.replace(/([a-zA-Z])(?=[A-Z])/g,'$1-').toLowerCase()};DomUtils.prototype.kekabCaseEvent=function(str){return ON_DASH+this.kebabCase(str)};function _isHtmlScript(node){var attribs=node.attribs;return node.type&&node.type===NodeType.SCRIPT&&attribs&&attribs.type&&attribs.type.indexOf('html')>=0};function _convertMsgToRowCol(msg,data,utils){var x,n,obj;x=msg.indexOf('position');if(x<0){return null}n=parseInt(msg.substr(x+8).trim());obj=utils.getRowColFromIndex(data,n);obj.msg=msg.substr(0,x)+'line '+obj.row+', col '+obj.col+' (position '+n+')';obj.position=n;return obj};function _getAttrRawValue(data,index,attrName,attrValue,utils){var ret=null,delim,i;i=index+attrName.length;if(data.charAt(i)==='='){i=utils.eatWhitespace(data,i+1);delim=data.substr(i,1);delim=delim==='\''||delim==='"'?delim:'"';ret=delim+attrValue+data.charAt(i+attrValue.length+1)}else{ret=attrValue}return ret};DomUtils.prototype.setDom=function(oDom){this._tree=oDom};module.exports=DomUtils;
6
+ const jsonParser=require('really-relaxed-json').createParser();const HtmlUtils=require('./HtmlUtils');const NodeType=require('./NodeTypes');const OJCOMPONENT='ojComponent';const COMPONENT='component';const SVG_PATH_COMMANDS=['M','m','L','I','H','h','V','v','C','c','S','s','Q','q','T','t','A','a','Z','z'];const DOT='.';const ON_DASH='on-';function DomUtils(nodeDeps,appContext,oTabs,fileIndex){this._tree=null;this._nodeDeps=nodeDeps;this._appContext=appContext;this._tabs=oTabs;this._utils=appContext.utils;this._fileIndex=fileIndex};DomUtils.prototype.getFirst=function(){return this._tree.length?this._tree[0]:null};DomUtils.prototype.getLast=function(){var node;node=this._tree.length?this._tree[this._tree.length-1]:null;while(node&&node.children&&node.children.length){node=node.children[node.children.length-1]}return node};DomUtils.prototype.getFirstElem=function(){var node=this.getFirst();while(node){if(node.type===NodeType.TAG){break};node=node.next}return node};DomUtils.prototype.getChildren=function(node){return node.children};DomUtils.prototype.getParent=function(node){return node.parent};DomUtils.prototype.getSiblings=function(node){var parent;if(parent=this.getParent(node)){return this.getChildren(parent)}else{return this._tree}};DomUtils.prototype.getNext=function(node){return node.next||null};DomUtils.prototype.getAttribs=function(node){return node.attribs||null};DomUtils.prototype.getAttribValue=function(node,name){return node.attribs?node.attribs[name]:undefined};DomUtils.prototype.getAttribRawValue=function(ruleCtx,name){var val,pos;if(ruleCtx.tagNode.attribs){if(typeof(val=ruleCtx.tagNode.attribs[name])==='string'){pos=this.getAttrPosition(ruleCtx.data,ruleCtx.tagNode,name);return _getAttrRawValue(ruleCtx.data,pos.start,name,val,ruleCtx.utils.utils)}}};DomUtils.prototype.hasAttrib=function(node,name){return!!node.attribs&&hasOwnProperty.call(node.attribs,name)};DomUtils.prototype.hasChildren=function(node){return!!node.children};DomUtils.prototype.hasNext=function(node){return!!node.next};DomUtils.prototype.getName=function(node){return node.name};DomUtils.prototype.getType=function(node){return node.type};DomUtils.prototype.getElemsByName=function(name){var a=[],i,names;if(!this._tree){return a}names=typeof name==='string'?[name]:name;for(i=0;i<names.length;i++){names[i]=names[i].toLowerCase()}for(i=0;i<this._tree.length;i++){_getElemsByName2(this._tree[i],a,names)}return a};function _getElemsByName2(node,a,names){var children,i;if((node.type===NodeType.TAG||node.type===NodeType.SCRIPT)&&names.indexOf(node.name.toLowerCase())>=0){a.push(node)}if(node.children){children=node.children;for(i=0;i<children.length;i++){_getElemsByName2(children[i],a,names)}}};DomUtils.prototype.getElemById=function(id,labelId){var node,i;if(!this._tree){return null}for(i=0;i<this._tree.length;i++){node=this._tree[i];if(node.type===NodeType.TAG||_isHtmlScript(node)){node=this._getElemById2(node,id,labelId);if(node){return node}}}return null};DomUtils.prototype._getElemById2=function(node,id,labelId){var curNode,attrib,attr,attribLower,i;if((node.type===NodeType.TAG||_isHtmlScript(node))&&node.attribs){for(attrib in node.attribs){attribLower=attrib.toLowerCase();if(attribLower==='id'||labelId&&attribLower==='label-id'){if(node.attribs[attrib]===id){return node}}else if(attrib==='data-bind'){attr=this.extractAttribsFromDataBind(node.attribs[attrib]);if(attr&&attr['id']===id){return node}}}}if(node.children){for(i=0;i<node.children.length;i++){curNode=this._getElemById2(node.children[i],id,labelId);if(curNode){return curNode}}}return null};DomUtils.prototype.getElems=function(){var a=[],i;if(!this._tree){return a}for(i=0;i<this._tree.length;i++){_getElems2(this._tree[i],a)}return a};function _getElems2(node,a){var children,i;if(node.type===NodeType.TAG||node.type===NodeType.SCRIPT){a.push(node)}if(node.children){children=node.children;for(i=0;i<children.length;i++){_getElems2(children[i],a)}}};DomUtils.prototype.getScripts=function(){var head,ch,a=[];if(head=this.getHead()){if(ch=head.children){ch.forEach(elem=>{if(elem.type===NodeType.TAG&&elem.name==='script'){a.push(elem)}})}}return a};DomUtils.prototype.getLinks=function(){var head,ch,a=[];if(head=this.getHead()){if(ch=head.children){ch.forEach(elem=>{if(elem.type===NodeType.TAG&&elem.name==='link'){a.push(elem)}})}}return a};DomUtils.prototype.getHead=function(){var elem,ch,i;if(!this._tree){return null}for(i=0;i<this._tree.length;i++){elem=this._tree[i];if(elem.type===NodeType.TAG&&elem.name==='html'){if(ch=elem.children){for(i=0;i<ch.length;i++){elem=ch[i];if(elem.type===NodeType.TAG&&elem.name==='head'){return elem}}}break}}return null};DomUtils.prototype.getBody=function(){var elem,ch,i;if(!this._tree){return null}for(i=0;i<this._tree.length;i++){elem=this._tree[i];if(elem.type===NodeType.TAG&&elem.name==='html'){if(ch=elem.children){for(i=0;i<ch.length;i++){elem=ch[i];if(elem.type===NodeType.TAG&&elem.name==='body'){return elem}}}break}}return null};DomUtils.prototype.getComponentElems=function(){var a=[],i;if(!this._tree){return a}for(i=0;i<this._tree.length;i++){this._getComponentElems2(this._tree[i],a)}return a};DomUtils.prototype._getComponentElems2=function(node,a){var children,i;if(node.type===NodeType.TAG&&this._appContext.metaLib.isWCTag(node.name)){a.push(node)}if(node.children){children=node.children;for(i=0;i<children.length;i++){this._getComponentElems2(children[i],a)}}};DomUtils.prototype.isCommonAttr=function(attrName){attrName=attrName.toLowerCase();attrName=attrName.charAt(0)===':'?attrName.substr(1):attrName;return HtmlUtils.isCommonAttr(attrName)};DomUtils.prototype.isCommonEventAttr=function(attrName){attrName=attrName.toLowerCase();attrName=attrName.charAt(0)===':'?attrName.substr(1):attrName;if(attrName.startsWith('on-oj-')){return false}if(attrName.startsWith('on-')){attrName=attrName.substring(0,2)+attrName.substring(3)}return HtmlUtils.isCommonEventAttr(attrName)};DomUtils.prototype.isCommonElem=function(elem){return HtmlUtils.isCommonElem(elem)};DomUtils.prototype.isSvgElem=function(elem){return HtmlUtils.isSvgElem(elem)};DomUtils.prototype.isHtml5ObsoleteElem=function(tag){return HtmlUtils.isHtml5ObsoleteElem(tag)};DomUtils.prototype.isHtml5ObsoleteAttr=function(tagName,attrName){return HtmlUtils.isHtml5ObsoleteAttr(tagName,attrName)};DomUtils.prototype.isSelfClosingTag=function(tag){return HtmlUtils.isSelfClosingTag(tag)};DomUtils.prototype.isNamespaceTag=function(tagName){if(this._appContext.metaLib.isJetTag(tagName)){return true}return HtmlUtils.isNamespaceTag(tagName)};DomUtils.prototype.isNamespacePrefix=function(tagPrefix){return!!HtmlUtils.isNamespacePrefix(tagPrefix)};DomUtils.prototype.isChildOfElem=function(elemName,node){return!!this.isChildOfElemNode(elemName,node)};DomUtils.prototype.isChildOfElemNode=function(elemName,node){var ret=null;while(node.parent){if(node.parent.name===elemName){ret=node.parent;break}node=node.parent}return ret};DomUtils.prototype.getDataBindComponent=function(context){var node,val,attrVal,ret=null;node=context.tagNode;if(this.getAttribs(node)){attrVal=this.getAttribValue(node,'data-bind');if(attrVal){val=this.extractComponentFromDataBind(attrVal);if(val){ret='oj.'+val}}}return ret};DomUtils.prototype.getDataBindAttr=function(context){return this.getDataBindAttrsFromNode(context,context.node)};DomUtils.prototype.getDataBindAttrs=function(context){return this.getDataBindAttrsFromNode(context,context.node)};DomUtils.prototype.getDataBindAttrsFromNode=function(context,node){var attrVal,ret=null;if(this.getAttribs(node)){attrVal=this.getAttribValue(node,'data-bind');if(attrVal){ret=this.extractAttribsFromDataBind(attrVal)}}return ret};DomUtils.prototype.extractComponentFromDataBind=function(attrValue){var dataBind,componentName,x;x=attrValue.indexOf(OJCOMPONENT);if(x<0){return}componentName=null;if(attrValue.length>OJCOMPONENT.length){dataBind=attrValue.substring(x+OJCOMPONENT.length);x=dataBind.indexOf(COMPONENT);if(x>=0){dataBind=dataBind.substring(x+COMPONENT.length).trim();if(dataBind.charAt(0)===':'){x=dataBind.indexOf('oj');if(x>=0){dataBind=dataBind.substring(x);componentName=_extractComponentName(dataBind,this._utils)}}}}return componentName};function _extractComponentName(s,utils){var componentName,i,c;for(i=0;i<s.length;i++){c=s.charAt(i);if(c==='\''||c==='"'||utils.isWhitespace(c)){componentName=s.substring(0,i);break}}return componentName};DomUtils.prototype.extractAttribsFromDataBind=function(attrValue){var s,a,nextAttr,val,i,j,x,ret=null;if(attrValue.indexOf(':')<0){return ret}a=attrValue.split('attr');if(a.length<2){return ret}for(i=0;i<a.length;i++){a[i]=s=a[i].trim();if(s.charAt(0)===':'){s=s.substr(1).trim();if(s.charAt(0)==='{'){try{ret=jsonParser.stringToJson(s);ret=JSON.parse(ret)}catch(e){s=s.substring(1).trim();a=s.split(':');for(j=0;j<a.length;j++){if(nextAttr){if(!ret){ret={}}ret[nextAttr]=val=a[j].replace(/['\"]/g,'').trim();x=val.lastIndexOf('}');if(x>=0){ret[nextAttr]=val.substring(0,x).trim();break}nextAttr=null}if(j+1===a.length){break}a[j]=s=a[j].trim();s=s.replace(/['\"]/g,'').trim();if(s.length===0)continue;if(!ret){ret={}}ret[s]=val=a[++j].trim();x=val.indexOf(',');if(x>=0){ret[s]=val.substring(0,x).replace(/['\"]/g,'').trim();nextAttr=val.substring(x+1).trim();nextAttr=nextAttr.replace(/['\"]/g,'').trim();val=val.substring(0,x).replace(/['\"]/g,'').trim()}else{ret[s]=val.replace(/['\"]/g,'').trim()}x=val.lastIndexOf('}');if(x>=0){ret[s]=val.substring(0,x).trim();break}}}}break}}return ret};DomUtils.prototype.getAttribPosition=function(data,node,attrName){var startIndex=this.getAttrIndex(data,node,attrName);var endIndex=startIndex+attrName.length-1;var pos=this._utils.getRowColFromIndex(data,startIndex,'html');pos.start=startIndex;pos.end=endIndex;return pos};DomUtils.prototype.getAttrPosition=function(data,node,attrName){return this.getAttribPosition(data,node,attrName)};DomUtils.prototype.getAttribValuePosition=function(data,node,attrName){var attrPos,pos,endPos,ws,ret,good;var isDouble,isSingle,isUnquoted;attrPos=this.getAttrPosition(data,node,attrName);if(!attrPos||attrPos.start===node.startIndex){return}if((pos=this._utils.eatWhitespace(data,attrPos.end+1))>=0){if(data.charAt(pos++)==='='){if((endPos=this._utils.eatWhitespace(data,pos))>=0){isDouble=data.charAt(endPos)==='"';isSingle=data.charAt(endPos)==='\'';isUnquoted=!(isSingle||isDouble);if(isDouble){if((endPos=data.indexOf('"',pos+1))>=0){good=true}}else if(isSingle){if((endPos=data.indexOf('\'',pos+1))>=0){good=true}}else if(isUnquoted){ws=this._utils.getIndexToWhitespace(data,pos);endPos=data.indexOf('>',pos);if(ws>=0&&endPos>=0){endPos=(endPos<ws?endPos:ws)-1;good=true}}if(good){attrPos=this.getLineCol(data,pos);ret={row:attrPos.row,col:attrPos.col,start:pos,end:endPos}}}}}return ret};DomUtils.prototype.getAttrValuePosition=function(data,node,attrName){return this.getAttribValuePosition(data,node,attrName)};DomUtils.prototype.getLineCol=function(data,index){return this._fileIndex.getRowCol(data,{start:index},'html')};DomUtils.prototype.getAttribIndex=function(data,node,attrName){var attribs,index,temp,c,i,isQuote=attrName==='"'||attrName==='\'';attribs=node.attribs;if(!attribs){this._appContext.assert('no attrs in tag '+node.name+'(expected attr \''+attrName+')');return node.startIndex}if(!attribs.hasOwnProperty(attrName)&&!attribs.hasOwnProperty(':'+attrName)){this._appContext.assert('expected attr \''+attrName+'\' in tag '+node.name);return node.startIndex}index=data.indexOf(attrName,node.startIndex);while(true){index=data.indexOf(attrName,index);if(index>=0){temp=data.substring(index+attrName.length,index+100);i=this._utils.eatWhitespace(temp);if(i<0){return node.startIndex}c=temp.charAt(i);if(c==='='||c==='>'||!isQuote&&this._utils.isWhitespace(temp.charAt(0))){return index}index+=i+1;continue}this._appContext.assert('expected attr \''+attrName+'\' in tag '+node.name);return node.startIndex}};DomUtils.prototype.getAttrIndex=function(data,node,attrName){return this.getAttribIndex(data,node,attrName)};DomUtils.prototype.isNonFragmentJetPage=function(context){return this.hasBody(context)&&this.isJetPage(context)};DomUtils.prototype.hasBody=function(context){var i,siblings,ret=false;siblings=this.getSiblings(context.node);for(i=0;i<siblings.length;i++){if(this._hasBody2(siblings[i])){ret=true;break}}return ret};DomUtils.prototype._hasBody2=function(node){var i,children,ret=false;if(node.type===NodeType.TAG&&node.name.toLowerCase()==='body'){return true}if(node.children){children=node.children;for(i=0;i<children.length;i++){if(this._hasBody2(children[i])){ret=true;break}}}return ret};DomUtils.prototype.isJetPage=function(context){var i,siblings,ret=false;siblings=this.getSiblings(context.node);for(i=0;i<siblings.length;i++){if(this._isJetPage2(siblings[i])){ret=true;break}}return ret};DomUtils.prototype._isJetPage2=function(node){var i,children,ret=false;if(node.type===NodeType.TAG&&node.name.toLowerCase().startsWith('oj-')){return true}if(node.children){children=node.children;for(i=0;i<children.length;i++){if(this._isJetPage2(children[i])){ret=true;break}}}return ret};DomUtils.prototype.isValidJson=function(value,data){var data,ret;if(value.charAt(0)!=='{'){return true}try{data=JSON.parse(this._nodeDeps.decomment(value));ret=!!data}catch(e){if(typeof data==='string'&&e.toString().startsWith('SyntaxError')){var obj=_convertMsgToRowCol(e.message,data,this._utils);ret.msg=obj.msg;ret.line=obj.row;ret.col=obj.col;ret.position=obj.position}else{ret=e.message}}return ret};DomUtils.prototype.isAttrExprConstant=function(expr){return HtmlUtils.isAttrExprConstant(expr)};const RE_EXPRESSION=/^(?:\[{2})(.*)(?:\]{2})$|^(?:\{{2})(.*)(?:\}{2})$/;DomUtils.prototype.isExpression=function(s){var ret=false;if(s){ret=RE_EXPRESSION.test(s.trim())}return ret};DomUtils.prototype.getExpression=function(s){var ret=null;if(this.isExpression(s)){ret=s.substring(2,s.length-2).trim()}return ret};DomUtils.prototype.isSvgPath=function(s){var c=s.trim().charAt(0);return SVG_PATH_COMMANDS.indexOf(c)>=0};DomUtils.prototype.camelCase=function(str){var parts,i;function _camelCase(str){return str.replace(/(?:^\w|[A-Z]|\b\w)/g,function(word,index){return index==0?word.toLowerCase():word.toUpperCase()}).replace(/-|\s+/g,'')};parts=str.split(DOT);for(i=0;i<parts.length;i++){parts[i]=_camelCase(parts[i])}return parts.join(DOT)};DomUtils.prototype.kebabCase=function(str){return str.replace(/([a-zA-Z])(?=[A-Z])/g,'$1-').toLowerCase()};DomUtils.prototype.kekabCaseEvent=function(str){return ON_DASH+this.kebabCase(str)};function _isHtmlScript(node){var attribs=node.attribs;return node.type&&node.type===NodeType.SCRIPT&&attribs&&attribs.type&&attribs.type.indexOf('html')>=0};function _convertMsgToRowCol(msg,data,utils){var x,n,obj;x=msg.indexOf('position');if(x<0){return null}n=parseInt(msg.substr(x+8).trim());obj=utils.getRowColFromIndex(data,n);obj.msg=msg.substr(0,x)+'line '+obj.row+', col '+obj.col+' (position '+n+')';obj.position=n;return obj};function _getAttrRawValue(data,index,attrName,attrValue,utils){var ret=null,delim,i;i=index+attrName.length;if(data.charAt(i)==='='){i=utils.eatWhitespace(data,i+1);delim=data.substr(i,1);delim=delim==='\''||delim==='"'?delim:'"';ret=delim+attrValue+data.charAt(i+attrValue.length+1)}else{ret=attrValue}return ret};DomUtils.prototype.setDom=function(oDom){this._tree=oDom};module.exports=DomUtils;
package/lib/Scope.js CHANGED
@@ -3,4 +3,4 @@
3
3
  * Licensed under The Universal Permissive License (UPL), Version 1.0
4
4
  * as shown at https://oss.oracle.com/licenses/upl/
5
5
  */
6
- var walker=require('./scopewalker');const TS_ANY='TSAnyKeyword';const TS_TYPEREF='TSTypeReference';const TS_ARRAY='TSArrayType';const STRING='string';const NUMBER='number';const BOOLEAN='boolean';const NULL='null';const OBJECT='Object';const FUNCTION='function';const ANY='any';const UNKNOWN='unknown';const PROGRAM='Program';const GLOBAL_SCOPE='_@global';const ANON='$anon';const DOCUMENT_METHODS={createElement:'Element',createTextNode:'Element',getElementById:'Element',getElementsByClassName:'HTMLCollection',getElementsByName:'HTMLCollection',getElementsByTagName:'HTMLCollection',getElementsByTagNameNS:'HTMLCollecion',hasFocus:'boolean',querySelector:'Element',querySelectorAll:'NodeList'};const DOCUMENT_MEMBERS={activeElement:'Element',anchors:'HTMLCollection',body:'Element',childElementCount:'number',dir:'string',documentElement:'Element',documentURI:'string',docType:'DTD',forms:'HTMLCollection',getElementById:'Element',head:'Element',hidden:'boolean',links:'HTMLCollection',scrollingElement:'Element',visibilityState:'string'};const INDENT=3;var _level=-INDENT;function _trace(t,n){function _rj(s,w){s=''+s;if(s.length<w){s=' '.repeat(w-s.length)+s}return s}_level+=t==='E'?INDENT:0;if(t==='E')console.log(`${_rj(n.loc.start.line,4)}] ${' '.repeat(_level)} ${n.type}`);else console.log(`${' '.repeat(4)} ${' '.repeat(_level)} ${n.type}`);_level-=t==='L'?INDENT:0};class Scope{constructor(msgCtx,config){this._msgCtx=msgCtx;this._config=config;this.reset()}reset(){this._fStack=[];this._bStack=[];this._imports=[];this._funcStack=[];this._idxStack=0;this._parents=[];this._blockStack=[];this._idxBlkStack=0;this._blkParents=[];this._nextAnonId=0;this._varKind;this._level=-INDENT}build(ast){this.reset();try{walker.traverse(ast,{enter:this._enter.bind(this),leave:this._leave.bind(this)})}catch(e){console.log(e.stack)}return{funcs:this._fStack,blocks:this._bStack}}_buildFuncIndexesToBlocks(){var i,j;for(i=0;i<this._fStack.length;i++){for(j=0;j<this._bStack.length;j++){if(this._bStack[j].func==i){this._fStack[i].blocks.push(j)}}}}getAccessor(){return new _scope(this._fStack,this._bStack)}_enter(node){var type;if(this._msgCtx.isDebug){_trace('E',node)}type=node.type;if(this._isNewScope(node)){this._addNewFunc(node)}else if(type==='VariableDeclarator'||type==='ClassProperty'){this._varDecl(node)}else if(type==='VariableDeclaration'){this._varKind=node.kind}else if(type==='BlockStatement'){this._addNewBlock(node)}else if(type==='ClassDeclaration'){this._inClass=true;this._className=node.id.name}else if(type==='ImportDeclaration'){this._addImport(node)}}_leave(node){if(this._msgCtx.isDebug){_trace('L',node)}if(this._isNewScope(node)){if(this._parents.length){this._parents.pop()}this._funcStack.pop()}else if(node.type==='BlockStatement'){if(this._blkParents.length){this._blkParents.pop()}this._blockStack.pop()}else if(node.type==='ClassDeclaration'){this._inClass=false;this._className=null}}_addNewFunc(node){var type,func,curParent,x;type=node.type;if(type===PROGRAM){func=GLOBAL_SCOPE}else if(node.kind==='method'||node.kind==='constructor'){func=node.key.name}else if(node.id){func=node.id.name}else if(type==='ClassBody'){func=this._className}else{this._getNextAnon()}if(this._parents.length){curParent=this._fStack[this._parents[this._parents.length-1]]}x=this._fStack.push({func:func,node:node,vars:{},args:{},blocks:[],children:[],parent:this._parents.length?this._parents[this._parents.length-1]:-1});x--;this._parents.push(x);if(curParent){curParent.children.push(x)}this._funcStack.push(x);this._addFuncArgs(node)}_addNewBlock(node){var func,curParent,x;var func=this._fStack[this._getCurFunc()];let n=this._fStack[this._getCurFunc()].node;if((n.kind==='method'||n.kind==='constructor')&&this._isMethodRange(n,node)||n.kind!=='method'&&n.kind!=='constructor'&&node.range===n.body.range){return}if(this._blkParents.length){curParent=this._bStack[this._blkParents[this._blkParents.length-1]]}x=this._bStack.push({func:this._getCurFunc(),node:node,lets:{},children:[],parent:this._blkParents.length?this._blkParents[this._blkParents.length-1]:-1});x--;this._blkParents.push(x);if(curParent){curParent.children.push(x)}this._blockStack.push(x);func.blocks.push(x)}_addImport(node){var src,local,o;src=node.source.value;if(!src.startsWith('ojs/')){return}o={src:src};if(node.specifiers.length){node.specifiers.forEach(s=>{if(!local)local=[];local.push(s.local.name)});if(local){o.local=local}}this._imports.push(o)}_getCurFunc(){return this._funcStack[this._funcStack.length-1]}_getCurBlock(){return this._blockStack[this._blockStack.length-1]}_addFuncArgs(node){var vt,curScope;if(node.params){curScope=this._fStack[this._getCurFunc()];node.params.forEach(function(n){if(n.type==='Identifier'){vt=this._getVarType(n);curScope.args[n.name]={type:vt}}else{if(n.type==='AssignmentPattern'){if(n.left&&n.left.name){curScope.args[n.left.name]={type:'???'}}else{console.log('scopes nt = n.type')}}}},this)}}_isNewScope(node){var type=node.type;return type==='FunctionDeclaration'||type==='MethodDefinition'||type==='FunctionExpression'&&!this._inClass||type==='ClassBody'||type==='Program'}_varDecl(node){var curScope,vt,name;function _declVar(vt,self){curScope=self._fStack[self._getCurFunc()];if(node.id){name=node.id.name}else{name=node.key.name}curScope.vars[name]={type:vt,node:node}};vt=this._getVarType(node);if(this._varKind==='let'||this._varKind==='const'){if(this._blockStack.length===0){this._varKind='var'}}if(this._varKind==='var'||node.type==='ClassProperty'){_declVar(vt,this)}else if(this._varKind==='let'||this._varKind==='const'){let b=this._getCurBlock();if(b>=0){let block=this._bStack[b];let br=block.node.range;let start=node.range;if(start[0]>=br[0]&&start[1]<=br[1]){block.lets[node.id.name]={type:vt,node:node}}}else{_declVar(vt,this)}}}_getVarType(node){var vt,ta,et,ty;if(node.type==='ClassProperty'){if(node.value){if(node.value.type==='ArrowFunctionExpression'){return'function'}else if(node.value.type==='CallExpression'){if(node.value.callee.object.name==='ko'){if(node.value.callee.property.name==='observable'){return'KO_Observable'}else if(node.value.callee.property.name==='computed'){return'KO_computed'}else{return'KO_Unknown'}}}}}ta=node.id&&node.id.typeAnnotation?node.id.typeAnnotation:node.typeAnnotation;if(!ta){ty=node.init?this._getInitType(node.init):ANY}else{vt=ta.typeAnnotation.type;if(vt===TS_TYPEREF){if(ta.typeAnnotation.typeName.name){ty=ta.typeAnnotation.typeName.name}else{if(ta.typeAnnotation.typeName.left){if(ta.typeAnnotation.typeName.left.name){ty=ta.typeAnnotation.typeName.left.name;if(ta.typeAnnotation.typeName.right&&ta.typeAnnotation.typeName.right.name){ty+='.'+ta.typeAnnotation.typeName.right.name}}else if(ta.typeAnnotation.typeName.left.left.name){ty+='.'+ta.typeAnnotation.typeName.left.left.name;if(ta.typeAnnotation.typeName.left.right.name){ty+='.'+ta.typeAnnotation.typeName.left.right.name}if(ta.typeAnnotation.typeName.right.name){ty+='.'+ta.typeAnnotation.typeName.right.name}}}}}else if(vt===TS_ARRAY){et=ta.typeAnnotation.elementType.type;if(et===TS_TYPEREF){ty=ta.typeAnnotation.elementType.typeName.name+'[]'}else{ty=et+'[]'}}else{ty=vt}}if(ty){ty=_transformType(ty)}if(!ty){console.log('[ASSERT]: scopes: ty not defined')}return ty}_getInitType(init){var vt,raw;if(init.type==='Literal'&&init.raw){raw=init.raw;if(raw.charAt(0)==='"'||raw.charAt(0)==='\''){vt=STRING}else if(raw==='true'||raw==='false'){vt=BOOLEAN}else if(!isNaN(raw)){vt=NUMBER}else if(raw==='null'){vt=NULL}else{console.log('[ASSERT]: SCOPES - UNKNOWN VAR INIT LITERAL = '+raw);vt=UNKNOWN}}else if(init.type==='ObjectExpression'){vt=OBJECT}else if(init.type==='NewExpression'){if(init.callee&&init.callee.name){vt=init.callee.name}}else if(init.type==='CallExpression'){if(init.callee&&init.callee.object){let o=init.callee.object;if(o.type==='Identifier'&&o.name==='document'){o=init.callee.property;if(o=DOCUMENT_METHODS[o.name]){return o}else{return'unknown document function'}}if(o.type==='MemberExpression'){vt=this._unravelCallME(o)}if(init.callee&&init.callee.object&&init.callee.object.type==='FunctionExpression'){vt='function'}}}else if(init.type==='MemberExpression'){if(init.object.type==='TSAsExpression'){vt=UNKNOWN}}else if(init.type==='TSAsExpression'){if(init.typeAnnotation&&init.typeAnnotation.type==='TSTypeReference'){vt=init.typeAnnotation.typeName.name}else{vt=UNKNOWN}}else if(init.type==='TSTypeAssertion'){if(init.typeAnnotation){vt=init.typeAnnotation.type}}else{vt=init.type}if(!vt){vt=UNKNOWN}return vt}_isMethodRange(n,node){return n.value&&n.value.body&&n.value.body.range===node.range}_unravelCallME(o){var prop;if(o.object.type==='ThisExpression'){prop=o.property.name;return this._getClassPropType(o,prop)}}_getClassPropType(o,prop){var c,ret;c=this._getContainingClass(o);if(c&&c.vars){ret=c.vars[prop];if(ret){ret=ret.type}}return ret}_getContainingClass(node){var c=this._getCurFunc(node);if(c<0){return}do{c=this._fStack[c];if(c.node.type==='ClassBody'){break}c=c.parent}while(c>=0);return c}_dumpEnter(node){let funcName=node.id?node.id.name:'anon';console.log(`ENTER=${funcName} ${node.type}`)}_dumpLeave(node){let funcName=node.id?node.id.name:'anon';console.log(`LEAVE=${funcName} ${node.type}`)}dumpStacks(){this.dumpFuncStack();this.dumpBlockStack()}dumpFuncStack(){var st,v,o,s,i,title;console.log('\n-------- Function/Class Scope Map --------');st=this._fStack;for(i=0;i<st.length;i++){o=st[i];s=(o.children.length?'children='+_dumpArrayIndices(o.children):'')+' blocks='+_dumpArrayIndices(o.blocks);console.log(`\n[${i}] "${o.func}" ${_dumpStackType(o)} parent=${o.parent} ${s}`);title=false;if(_hasProps(o.args)){for(v in o.args){console.log((!title?' Args: ':' ')+v+': '+o.args[v].type);title=true}}else{console.log(' Args: none')}title=false;if(_hasProps(o.vars)){for(v in o.vars){console.log((!title?' Vars: ':' ')+v+': '+o.vars[v].type+' ('+(o.vars[v].node.type==='ClassProperty'?'class prop':'var')+')');title=true}}else{console.log(' Vars: none')}}}dumpBlockStack(){var st,v,o,ch,i,title;console.log('\n-------- Internal Block Scope Map --------');st=this._bStack;if(!st.length){console.log('\nNo blocks.');return''}for(i=0;i<st.length;i++){o=st[i];ch=o.children.length?'children='+_dumpArrayIndices(o.children):'';console.log(`\n[${i}] ${this._dumpBlkOwner(o)}="${this._fStack[o.func].func}" parent=${o.parent} ${ch}`);title=false;if(_hasProps(o.lets)){for(v in o.lets){console.log((!title?' Lets: ':' ')+v+': '+o.lets[v].type);title=true}}else{console.log(' Lets: none')}}}_dumpBlkOwner(o){var f=this._fStack[o.func];return f.node.type==='FunctionDeclaration'?'func':'meth'}_getNextAnon(){return ANON+ ++this._nextAnonId}};function _hasProps(obj){var ret=false;for(var prop in obj){if(obj.hasOwnProperty(prop)){ret=true;break}}return ret};function _dumpArrayIndices(a){var ret='[';a.forEach(function(v,i){ret+=(i?', ':'')+v});return ret+']'}function _dumpStackType(o){var s='';switch(o.node.type){case'ClassBody':s='class';break;case'MethodDefinition':s='method';break;case'FunctionDeclaration':s='func';break;}return s.length?'('+s+')':s};function _transformType(ty){const list={TSStringKeyword:'string',TSNumberKeyword:'number',TSBooleanKeyword:'boolean',TSNullKeyword:'null',TSObjectKeyword:'object',TSUnknownKeyword:'unknown',TSAnyKeyword:'any'};return list[ty]||ty};class _scope{constructor(fs,bs){this._fstk=fs;this._bstk=bs}getVarType(node){var name,func,block,v;name=node.name;if(!node.name){return null}block=this.getContainingBlock(node);if(block){v=block.lets[name];if(v){return v.type}while(block.parent>=0){block=this._bstk[block.parent];if(block){v=block.lets[name];if(v){return v.type}}}}func=this.getContainingFunc(node);do{if(func.vars&&func.vars[name]){v=func.vars[name].type}else if(func.args&&func.args[name]){v=func.args[name].type}if(v){break}if(func.parent>=0){func=this._fstk[func.parent]}else{func=null}}while(func);return v}getContainingFunc(node){var start,fnRange,fnIndex,func,fr,i;start=node.range[0];for(i=0;i<this._fstk.length;i++){func=this._fstk[i];fr=func.node.range;if(start>=fr[0]&&start<=fr[1]){if(fnRange){if(fr[0]>=fnRange[0]&&fr[1]<=fnRange[1]){fnRange=fr;fnIndex=i}}else{fnRange=fr;fnIndex=i}}}return typeof fnIndex==='number'?this._fstk[fnIndex]:null}getContainingBlock(node){var nrange,brange,range,bindex,blocks,block,i;if(!this._bstk.length)return;var blocks=this.getContainingFunc(node).blocks;nrange=node.range;for(i=0;i<blocks.length;i++){block=this._bstk[i];brange=block.node.range;if(nrange[0]>=brange[0]&&nrange[1]<=brange[1]){if(range){if(brange[0]>=range[0]&&brange[1]<=range[1]){range=nrange;bindex=i}}else{range=brange;bindex=i}}}return typeof bindex==='number'?this._bstk[bindex]:null}getContainingClass(node){}getGlobals(){return this._fstk[0]}getFuncStack(){return this._fstk}getBlockStack(){return this._bstk}};module.exports=Scope;
6
+ var walker=require('./scopewalker');const TS_ANY='TSAnyKeyword';const TS_TYPEREF='TSTypeReference';const TS_ARRAY='TSArrayType';const STRING='string';const NUMBER='number';const BOOLEAN='boolean';const NULL='null';const OBJECT='Object';const FUNCTION='function';const ANY='any';const UNKNOWN='unknown';const PROGRAM='Program';const GLOBAL_SCOPE='_@global';const ANON='$anon';const DOCUMENT_METHODS={createElement:'Element',createTextNode:'Element',getElementById:'Element',getElementsByClassName:'HTMLCollection',getElementsByName:'HTMLCollection',getElementsByTagName:'HTMLCollection',getElementsByTagNameNS:'HTMLCollecion',hasFocus:'boolean',querySelector:'Element',querySelectorAll:'NodeList'};const DOCUMENT_MEMBERS={activeElement:'Element',anchors:'HTMLCollection',body:'Element',childElementCount:'number',dir:'string',documentElement:'Element',documentURI:'string',docType:'DTD',forms:'HTMLCollection',getElementById:'Element',head:'Element',hidden:'boolean',links:'HTMLCollection',scrollingElement:'Element',visibilityState:'string'};const INDENT=3;var _level=-INDENT;function _trace(t,n){function _rj(s,w){s=''+s;if(s.length<w){s=' '.repeat(w-s.length)+s}return s}_level+=t==='E'?INDENT:0;if(t==='E')console.log(`${_rj(n.loc.start.line,4)}] ${' '.repeat(_level)} ${n.type}`);else console.log(`${' '.repeat(4)} ${' '.repeat(_level)} ${n.type}`);_level-=t==='L'?INDENT:0};class Scope{constructor(msgCtx,config,file){this._msgCtx=msgCtx;this._config=config;this._file=file;this.reset()}reset(){this._fStack=[];this._bStack=[];this._imports=[];this._funcStack=[];this._idxStack=0;this._parents=[];this._blockStack=[];this._idxBlkStack=0;this._blkParents=[];this._nextAnonId=0;this._varKind;this._level=-INDENT}build(ast){this.reset();try{walker.traverse(ast,{enter:this._enter.bind(this),leave:this._leave.bind(this)})}catch(e){let stk=e.stack;let x=stk.indexOf('\n');stk=x>=0?stk.substring(x+1):stk;stk=`${'-'.repeat(10)}\n${stk}\n${'-'.repeat(10)}`;this._msgCtx.jafMsg('jaf-ts-walk',`TS walk exception: ${e.message} File: ${this._file}\n\n${stk}`)}return{funcs:this._fStack,blocks:this._bStack}}_buildFuncIndexesToBlocks(){var i,j;for(i=0;i<this._fStack.length;i++){for(j=0;j<this._bStack.length;j++){if(this._bStack[j].func==i){this._fStack[i].blocks.push(j)}}}}getAccessor(){return new _scope(this._fStack,this._bStack)}_enter(node){var type;if(this._msgCtx.isDebug){_trace('E',node)}type=node.type;if(this._isNewScope(node)){this._addNewFunc(node)}else if(type==='VariableDeclarator'||type==='ClassProperty'){this._varDecl(node)}else if(type==='VariableDeclaration'){this._varKind=node.kind}else if(type==='BlockStatement'){this._addNewBlock(node)}else if(type==='ClassDeclaration'){this._inClass=true;this._className=node.id.name}else if(type==='ImportDeclaration'){this._addImport(node)}}_leave(node){if(this._msgCtx.isDebug){_trace('L',node)}if(this._isNewScope(node)){if(this._parents.length){this._parents.pop()}this._funcStack.pop()}else if(node.type==='BlockStatement'){if(this._blkParents.length){this._blkParents.pop()}this._blockStack.pop()}else if(node.type==='ClassDeclaration'){this._inClass=false;this._className=null}}_addNewFunc(node){var type,func,curParent,x;type=node.type;if(type===PROGRAM){func=GLOBAL_SCOPE}else if(node.kind==='method'||node.kind==='constructor'){func=node.key.name}else if(node.id){func=node.id.name}else if(type==='ClassBody'){func=this._className}else{this._getNextAnon()}if(this._parents.length){curParent=this._fStack[this._parents[this._parents.length-1]]}x=this._fStack.push({func:func,node:node,vars:{},args:{},blocks:[],children:[],parent:this._parents.length?this._parents[this._parents.length-1]:-1});x--;this._parents.push(x);if(curParent){curParent.children.push(x)}this._funcStack.push(x);this._addFuncArgs(node)}_addNewBlock(node){var func,curParent,x;var func=this._fStack[this._getCurFunc()];let n=this._fStack[this._getCurFunc()].node;if((n.kind==='method'||n.kind==='constructor')&&this._isMethodRange(n,node)||n.kind!=='method'&&n.kind!=='constructor'&&node.range===n.body.range){return}if(this._blkParents.length){curParent=this._bStack[this._blkParents[this._blkParents.length-1]]}x=this._bStack.push({func:this._getCurFunc(),node:node,lets:{},children:[],parent:this._blkParents.length?this._blkParents[this._blkParents.length-1]:-1});x--;this._blkParents.push(x);if(curParent){curParent.children.push(x)}this._blockStack.push(x);func.blocks.push(x)}_addImport(node){var src,local,o;src=node.source.value;if(!src.startsWith('ojs/')){return}o={src:src};if(node.specifiers.length){node.specifiers.forEach(s=>{if(!local)local=[];local.push(s.local.name)});if(local){o.local=local}}this._imports.push(o)}_getCurFunc(){return this._funcStack[this._funcStack.length-1]}_getCurBlock(){return this._blockStack[this._blockStack.length-1]}_addFuncArgs(node){var vt,curScope;if(node.params){curScope=this._fStack[this._getCurFunc()];node.params.forEach(function(n){if(n.type==='Identifier'){vt=this._getVarType(n);curScope.args[n.name]={type:vt}}else{if(n.type==='AssignmentPattern'){if(n.left&&n.left.name){curScope.args[n.left.name]={type:'???'}}else{console.log('scopes nt = n.type')}}}},this)}}_isNewScope(node){var type=node.type;return type==='FunctionDeclaration'||type==='MethodDefinition'||type==='FunctionExpression'&&!this._inClass||type==='ClassBody'||type==='Program'}_varDecl(node){var curScope,vt,name;function _declVar(vt,self){curScope=self._fStack[self._getCurFunc()];if(node.id){name=node.id.name}else{name=node.key.name}curScope.vars[name]={type:vt,node:node}};vt=this._getVarType(node);if(this._varKind==='let'||this._varKind==='const'){if(this._blockStack.length===0){this._varKind='var'}}if(this._varKind==='var'||node.type==='ClassProperty'){_declVar(vt,this)}else if(this._varKind==='let'||this._varKind==='const'){let b=this._getCurBlock();if(b>=0){let block=this._bStack[b];let br=block.node.range;let start=node.range;if(start[0]>=br[0]&&start[1]<=br[1]){block.lets[node.id.name]={type:vt,node:node}}}else{_declVar(vt,this)}}}_getVarType(node){var vt,ta,et,ty;if(node.type==='ClassProperty'){if(node.value){if(node.value.type==='ArrowFunctionExpression'){return'function'}else if(node.value.type==='CallExpression'){if(node.value.callee.object.name==='ko'){if(node.value.callee.property.name==='observable'){return'KO_Observable'}else if(node.value.callee.property.name==='computed'){return'KO_computed'}else{return'KO_Unknown'}}}}}ta=node.id&&node.id.typeAnnotation?node.id.typeAnnotation:node.typeAnnotation;if(!ta){ty=node.init?this._getInitType(node.init):ANY}else{vt=ta.typeAnnotation.type;if(vt===TS_TYPEREF){if(ta.typeAnnotation.typeName.name){ty=ta.typeAnnotation.typeName.name}else{if(ta.typeAnnotation.typeName.left){if(ta.typeAnnotation.typeName.left.name){ty=ta.typeAnnotation.typeName.left.name;if(ta.typeAnnotation.typeName.right&&ta.typeAnnotation.typeName.right.name){ty+='.'+ta.typeAnnotation.typeName.right.name}}else if(ta.typeAnnotation.typeName.left.left.name){ty+='.'+ta.typeAnnotation.typeName.left.left.name;if(ta.typeAnnotation.typeName.left.right.name){ty+='.'+ta.typeAnnotation.typeName.left.right.name}if(ta.typeAnnotation.typeName.right.name){ty+='.'+ta.typeAnnotation.typeName.right.name}}}}}else if(vt===TS_ARRAY){et=ta.typeAnnotation.elementType.type;if(et===TS_TYPEREF){ty=ta.typeAnnotation.elementType.typeName.name+'[]'}else{ty=et+'[]'}}else{ty=vt}}if(ty){ty=_transformType(ty)}if(!ty){console.log('[ASSERT]: scopes: ty not defined')}return ty}_getInitType(init){var vt,raw;if(init.type==='Literal'&&init.raw){raw=init.raw;if(raw.charAt(0)==='"'||raw.charAt(0)==='\''){vt=STRING}else if(raw==='true'||raw==='false'){vt=BOOLEAN}else if(!isNaN(raw)){vt=NUMBER}else if(raw==='null'){vt=NULL}else{console.log('[ASSERT]: SCOPES - UNKNOWN VAR INIT LITERAL = '+raw);vt=UNKNOWN}}else if(init.type==='ObjectExpression'){vt=OBJECT}else if(init.type==='NewExpression'){if(init.callee&&init.callee.name){vt=init.callee.name}}else if(init.type==='CallExpression'){if(init.callee&&init.callee.object){let o=init.callee.object;if(o.type==='Identifier'&&o.name==='document'){o=init.callee.property;if(o=DOCUMENT_METHODS[o.name]){return o}else{return'unknown document function'}}if(o.type==='MemberExpression'){vt=this._unravelCallME(o)}if(init.callee&&init.callee.object&&init.callee.object.type==='FunctionExpression'){vt='function'}}}else if(init.type==='MemberExpression'){if(init.object.type==='TSAsExpression'){vt=UNKNOWN}}else if(init.type==='TSAsExpression'){if(init.typeAnnotation&&init.typeAnnotation.type==='TSTypeReference'){vt=init.typeAnnotation.typeName.name}else{vt=UNKNOWN}}else if(init.type==='TSTypeAssertion'){if(init.typeAnnotation){vt=init.typeAnnotation.type}}else{vt=init.type}if(!vt){vt=UNKNOWN}return vt}_isMethodRange(n,node){return n.value&&n.value.body&&n.value.body.range===node.range}_unravelCallME(o){var prop;if(o.object.type==='ThisExpression'){prop=o.property.name;return this._getClassPropType(o,prop)}}_getClassPropType(o,prop){var c,ret;c=this._getContainingClass(o);if(c&&c.vars){ret=c.vars[prop];if(ret){ret=ret.type}}return ret}_getContainingClass(node){var c=this._getCurFunc(node);if(c<0){return}do{c=this._fStack[c];if(c.node.type==='ClassBody'){break}c=c.parent}while(c>=0);return c}_dumpEnter(node){let funcName=node.id?node.id.name:'anon';console.log(`ENTER=${funcName} ${node.type}`)}_dumpLeave(node){let funcName=node.id?node.id.name:'anon';console.log(`LEAVE=${funcName} ${node.type}`)}dumpStacks(){this.dumpFuncStack();this.dumpBlockStack()}dumpFuncStack(){var st,v,o,s,i,title;console.log('\n-------- Function/Class Scope Map --------');st=this._fStack;for(i=0;i<st.length;i++){o=st[i];s=(o.children.length?'children='+_dumpArrayIndices(o.children):'')+' blocks='+_dumpArrayIndices(o.blocks);console.log(`\n[${i}] "${o.func}" ${_dumpStackType(o)} parent=${o.parent} ${s}`);title=false;if(_hasProps(o.args)){for(v in o.args){console.log((!title?' Args: ':' ')+v+': '+o.args[v].type);title=true}}else{console.log(' Args: none')}title=false;if(_hasProps(o.vars)){for(v in o.vars){console.log((!title?' Vars: ':' ')+v+': '+o.vars[v].type+' ('+(o.vars[v].node.type==='ClassProperty'?'class prop':'var')+')');title=true}}else{console.log(' Vars: none')}}}dumpBlockStack(){var st,v,o,ch,i,title;console.log('\n-------- Internal Block Scope Map --------');st=this._bStack;if(!st.length){console.log('\nNo blocks.');return''}for(i=0;i<st.length;i++){o=st[i];ch=o.children.length?'children='+_dumpArrayIndices(o.children):'';console.log(`\n[${i}] ${this._dumpBlkOwner(o)}="${this._fStack[o.func].func}" parent=${o.parent} ${ch}`);title=false;if(_hasProps(o.lets)){for(v in o.lets){console.log((!title?' Lets: ':' ')+v+': '+o.lets[v].type);title=true}}else{console.log(' Lets: none')}}}_dumpBlkOwner(o){var f=this._fStack[o.func];return f.node.type==='FunctionDeclaration'?'func':'meth'}_getNextAnon(){return ANON+ ++this._nextAnonId}};function _hasProps(obj){var ret=false;for(var prop in obj){if(obj.hasOwnProperty(prop)){ret=true;break}}return ret};function _dumpArrayIndices(a){var ret='[';a.forEach(function(v,i){ret+=(i?', ':'')+v});return ret+']'}function _dumpStackType(o){var s='';switch(o.node.type){case'ClassBody':s='class';break;case'MethodDefinition':s='method';break;case'FunctionDeclaration':s='func';break;}return s.length?'('+s+')':s};function _transformType(ty){const list={TSStringKeyword:'string',TSNumberKeyword:'number',TSBooleanKeyword:'boolean',TSNullKeyword:'null',TSObjectKeyword:'object',TSUnknownKeyword:'unknown',TSAnyKeyword:'any'};return list[ty]||ty};class _scope{constructor(fs,bs){this._fstk=fs;this._bstk=bs}getVarType(node){var name,func,block,v;name=node.name;if(!node.name){return null}block=this.getContainingBlock(node);if(block){v=block.lets[name];if(v){return v.type}while(block.parent>=0){block=this._bstk[block.parent];if(block){v=block.lets[name];if(v){return v.type}}}}func=this.getContainingFunc(node);do{if(func.vars&&func.vars[name]){v=func.vars[name].type}else if(func.args&&func.args[name]){v=func.args[name].type}if(v){break}if(func.parent>=0){func=this._fstk[func.parent]}else{func=null}}while(func);return v}getContainingFunc(node){var start,fnRange,fnIndex,func,fr,i;start=node.range[0];for(i=0;i<this._fstk.length;i++){func=this._fstk[i];fr=func.node.range;if(start>=fr[0]&&start<=fr[1]){if(fnRange){if(fr[0]>=fnRange[0]&&fr[1]<=fnRange[1]){fnRange=fr;fnIndex=i}}else{fnRange=fr;fnIndex=i}}}return typeof fnIndex==='number'?this._fstk[fnIndex]:null}getContainingBlock(node){var nrange,brange,range,bindex,blocks,block,i;if(!this._bstk.length)return;var blocks=this.getContainingFunc(node).blocks;nrange=node.range;for(i=0;i<blocks.length;i++){block=this._bstk[i];brange=block.node.range;if(nrange[0]>=brange[0]&&nrange[1]<=brange[1]){if(range){if(brange[0]>=range[0]&&brange[1]<=range[1]){range=nrange;bindex=i}}else{range=brange;bindex=i}}}return typeof bindex==='number'?this._bstk[bindex]:null}getContainingClass(node){}getGlobals(){return this._fstk[0]}getFuncStack(){return this._fstk}getBlockStack(){return this._bstk}};module.exports=Scope;
package/lib/defaults.js CHANGED
@@ -3,4 +3,4 @@
3
3
  * Licensed under The Universal Permissive License (UPL), Version 1.0
4
4
  * as shown at https://oss.oracle.com/licenses/upl/
5
5
  */
6
- const defaults={JETVER:'12.0.0'.replace(/(\d*\.\d*)(\.\d*)+$/g,'$1')+'.0',THEME:'Alta',ECMAVER:11};module.exports=defaults;
6
+ const defaults={JETVER:'12.0.1'.replace(/(\d*\.\d*)(\.\d*)+$/g,'$1')+'.0',THEME:'Alta',ECMAVER:11};module.exports=defaults;
package/lib/deflist.js CHANGED
@@ -3,4 +3,4 @@
3
3
  * Licensed under The Universal Permissive License (UPL), Version 1.0
4
4
  * as shown at https://oss.oracle.com/licenses/upl/
5
5
  */
6
- const defs=require("./defaults");const indent=" ";function _show(){console.log(`\nDefault JAF Values:\n\n${indent}jetVer : "${defs.JETVER}"\n${indent}theme : "${defs.THEME}"\n${indent}ecmaVer : ${defs.ECMAVER}`)};module.exports.showList=_show;
6
+ const defs=require("./defaults");const indent=" ";function _show(nd){var _clr=nd.colors;var s="\n"+_clr.BRIGHTGREEN("--- Default JAF Values ---")+"\n\n"+`${indent}${_clr.BRIGHTYELLOW("? jetVer ")}: ${_clr.CYAN(`${defs.JETVER}`)}\n`+`${indent}${_clr.BRIGHTYELLOW("? theme ")}: ${_clr.CYAN("'Redwood' if jetVer >= 12.0.0, else 'Alta'")}\n`+`${indent}${_clr.BRIGHTYELLOW("? ecmaVer ")}: ${_clr.CYAN(`${defs.ECMAVER}`)}\n\n`+`${indent}${_clr.BRIGHTYELLOW("? builtinJetRules ")}: ${_clr.CYAN(`true`)}\n`+`${indent}${_clr.BRIGHTYELLOW("? severity ")}: ${_clr.CYAN("'all'")}\n`+`${indent}${_clr.BRIGHTYELLOW("? groups ")}: ${_clr.CYAN("'all'")}\n`+`${indent}${_clr.BRIGHTYELLOW("? base ")}: ${_clr.CYAN("location of configuration file")}\n`+`${indent}${_clr.BRIGHTYELLOW("? files ")}: ${_clr.CYAN(".html files in the 'base' directory")}\n`+`${indent}${_clr.BRIGHTYELLOW("? format ")}: ${_clr.CYAN("`prose'")}\n`+`${indent}${_clr.BRIGHTYELLOW("? comments ")}: ${_clr.CYAN("false")}\n`+`${indent}${_clr.BRIGHTYELLOW("? followLinks ")}: ${_clr.CYAN("true")}\n`+`${indent}${_clr.BRIGHTYELLOW("? tempDir ")}: ${_clr.CYAN("the current working directory")}\n`;console.log(s)};module.exports.showList=_show;
package/lib/help.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 FLAGS=["\n Command line: %ojaf [flags] [ files/directory space separated list]%\n","\n Audit related flags:\n"," ~--config~ or ^-c^ : %followed by filepath to configuration file. If%"," %omitted, current directory is used.%"," ~--base~ or ^-b^ : %followed by filepath used to resolve relative paths. If%"," %omitted, current directory is used.%"," ~--jetver~ or ^-jv^ : %sets the JET version - must be followed by a version number x[.y[.z]]%"," ~--format~ or ^-t^ : %followed by output format 'prose' | 'json' | 'line'%"," ~--outPath~ or ^-o^ : %followed by output file path%"," ~--noout~ or ^-no^ : %do not write to output file path%"," ~--severity~ or ^-s^ : %report on this rule severity only%"," ~--groups~ or ^-g^ : %followed by group(s)%"," ~--groups=~ or ^-g=^ : %followed by group(s)%"," ~--followlinks~ or ^-fl^ : %follow stylesheet/script links%"," ~--nofollowlinks~ or ^-nfl^ : %do not follow stylesheet/script links%"," ~--extra~ or ^-e^ : %verbose - show extra details%"," ~--retcode~ or ^-rc^ : %followed by 'auto' | 'errors' | number, to override return code%"," ~--retcode=~ or ^-rc=^ : %followed by 'auto' | 'errors' | number, to override return code%"," ~--msgid~ or ^-id^ : %show audit message id's in the ouput if format 'prose'%"," ~--nocolor~ or ^-nc^ : %do not colorize output%"," ~--debug~ or ^-d^ : %debug mode%","\n Immediate command flags - display JAF info or scaffold files (no auditing involved)\n"," ~--help~ or ^-h^ : %show this help%"," ~--help~ or ^-h^ : %followed by messageID | rulename : show rule description%"," ~--version~ or ^-v^ : %show the ojaf version%"," ~--jetlist~ or ^-jl^ : %show the supported JET versions%"," ~--nslist~ or ^-nsl^ : %show the supported registered Namespaces%"," ~--grouplist~ or ^-gl^ : %show built-in rules by group. May be followed by an%"," %optional pack prefix.%"," ~--xgrouplist~ or ^-xgl^ : %show external pack rules by group. May be followed by an%"," %optional pack prefix.%"," ~--dislist~ or ^-dl^ : %show the JET built-in rules disabled by default. May be followed%"," %by an optional pack prefix.%"," ~--metahist~ or ^-mh^ : %show the renamed/deleted JET component history%\n"," ~--dac~ or ^-dac^ : %display active config and terminate (no audit performed)%"," ~--reg~ or ^-reg^ : %display rule listener types (debug)%"," ~--init~ or ^-i^ : %scaffold a JAF config file%"," ~--initrule~ or ^-ir^ : %followed by rulename (no file extension) - scaffold a rule file%\n"," ~--rules~ or ^-r^ : %display rule information%"," ~--rulessonar~ or ^-rs^ : %display rule information - sonar format%"," ~--rulesjson~ or ^-rj^ : %display rule information - json format%"," ~--dryrun~ or ^-dr^ : %dry run - show setup and files that would have been audited (no%"," %audit performed)%","\n1) Command line args override corresponding properties in the configuration file.","2) Command flags are case independent."];module.exports=function(fnShowVersion,color,msgContext){var console=msgContext.console;var by=color.BRIGHTYELLOW;var cy=color.CYAN;var x1,x2,x3,x4,x5,x6,msg;fnShowVersion();FLAGS.forEach(s=>{msg="";if((x1=s.indexOf("~"))>=0){x2=s.indexOf("~",x1+1);msg=s.substring(0,x1)+by(s.substring(x1+1,x2));if((x3=s.indexOf("^",x2+1))>=0){x4=s.indexOf("^",x3+1);msg+=s.substring(x2+1,x3)+by(s.substring(x3+1,x4));if((x5=s.indexOf("%",x4+1))>=0){x6=s.indexOf("%",x5+1);msg+=s.substring(x4+1,x5)+cy(s.substring(x5+1,x6))+s.substring(x6+1)}else{msg+=s.substring(x4+1)}}else{msg+=s.substring(x2+1)}}else if((x5=s.indexOf("%"))>=0){x6=s.indexOf("%",x5+1);msg+=s.substring(0,x5)+cy(s.substring(x5+1,x6))+s.substring(x6+1)}else{msg=s}console(msg)})};
6
+ const FLAGS=["\n Command line: %ojaf [flags] [ files/directory space separated list]%\n","\n Audit related flags:\n"," ~--config~ or ^-c^ : %followed by filepath to configuration file. If%"," %omitted, current directory is used.%"," ~--base~ or ^-b^ : %followed by filepath used to resolve relative paths. If%"," %omitted, current directory is used.%"," ~--jetver~ or ^-jv^ : %sets the JET version - must be followed by a version number x[.y[.z]]%"," ~--format~ or ^-t^ : %followed by output format 'prose' | 'json' | 'line'%"," ~--outPath~ or ^-o^ : %followed by output file path%"," ~--noout~ or ^-no^ : %do not write to output file path%"," ~--severity~ or ^-s^ : %report on this rule severity only%"," ~--groups~ or ^-g^ : %followed by group(s)%"," ~--groups=~ or ^-g=^ : %followed by group(s)%"," ~--followlinks~ or ^-fl^ : %follow stylesheet/script links%"," ~--nofollowlinks~ or ^-nfl^ : %do not follow stylesheet/script links%"," ~--extra~ or ^-e^ : %verbose - show extra details%"," ~--retcode~ or ^-rc^ : %followed by 'auto' | 'errors' | number, to override return code%"," ~--retcode=~ or ^-rc=^ : %followed by 'auto' | 'errors' | number, to override return code%"," ~--msgid~ or ^-id^ : %show audit message id's in the ouput if format 'prose'%"," ~--nocolor~ or ^-nc^ : %do not colorize output%"," ~--debug~ or ^-d^ : %debug mode%","\n Immediate command flags - display JAF info or scaffold files (no auditing involved)\n"," ~--help~ or ^-h^ : %show this help%"," ~--help~ or ^-h^ : %followed by messageID | rulename : show rule description%"," ~--version~ or ^-v^ : %show the ojaf version%"," ~--jetlist~ or ^-jl^ : %show the supported JET versions%"," ~--nslist~ or ^-nsl^ : %show the supported registered Namespaces%"," ~--grouplist~ or ^-gl^ : %show built-in rules by group. May be followed by an%"," %optional pack prefix.%"," ~--xgrouplist~ or ^-xgl^ : %show external pack rules by group. May be followed by an%"," %optional pack prefix.%"," ~--dislist~ or ^-dl^ : %show the JET built-in rules disabled by default. May be followed%"," %by an optional pack prefix.%"," ~--deflist~ or ^-def^ : %show the configuration default values.%"," ~--metahist~ or ^-mh^ : %show the renamed/deleted JET component history%\n"," ~--dac~ or ^-dac^ : %display active config and terminate (no audit performed)%"," ~--reg~ or ^-reg^ : %display rule listener types (debug)%"," ~--init~ or ^-i^ : %scaffold a JAF config file%"," ~--initrule~ or ^-ir^ : %followed by rulename (no file extension) - scaffold a rule file%\n"," ~--rules~ or ^-r^ : %display rule information%"," ~--rulessonar~ or ^-rs^ : %display rule information - sonar format%"," ~--rulesjson~ or ^-rj^ : %display rule information - json format%"," ~--dryrun~ or ^-dr^ : %dry run - show setup and files that would have been audited (no%"," %audit performed)%","\n1) Command line args override corresponding properties in the configuration file.","2) Command flags are case independent."];module.exports=function(fnShowVersion,color,msgContext){var console=msgContext.console;var by=color.BRIGHTYELLOW;var cy=color.CYAN;var x1,x2,x3,x4,x5,x6,msg;fnShowVersion();FLAGS.forEach(s=>{msg="";if((x1=s.indexOf("~"))>=0){x2=s.indexOf("~",x1+1);msg=s.substring(0,x1)+by(s.substring(x1+1,x2));if((x3=s.indexOf("^",x2+1))>=0){x4=s.indexOf("^",x3+1);msg+=s.substring(x2+1,x3)+by(s.substring(x3+1,x4));if((x5=s.indexOf("%",x4+1))>=0){x6=s.indexOf("%",x5+1);msg+=s.substring(x4+1,x5)+cy(s.substring(x5+1,x6))+s.substring(x6+1)}else{msg+=s.substring(x4+1)}}else{msg+=s.substring(x2+1)}}else if((x5=s.indexOf("%"))>=0){x6=s.indexOf("%",x5+1);msg+=s.substring(0,x5)+cy(s.substring(x5+1,x6))+s.substring(x6+1)}else{msg=s}console(msg)})};
package/lib/scaffold.js CHANGED
@@ -3,4 +3,4 @@
3
3
  * Licensed under The Universal Permissive License (UPL), Version 1.0
4
4
  * as shown at https://oss.oracle.com/licenses/upl/
5
5
  */
6
- const DEFAULTS=require("./defaults");const OJET_CONFIG="oraclejetconfig.json";const OJAF_CONFIG="oraclejafconfig.json";const OJAF_DEFAULT_CONFIG="jafconfig.json";const DEPENDENCIES_VER_PROP="@oracle/oraclejet";const COMPOSITES_FOLDER="jet-composites";const EXTENSION_FOLDER="extension";const RESOURCES_FOLDER="resources";const JS_FOLDER="js";const TS_FOLDER="ts";const COMP_JSON="component.json";const PACKAGE_JSON="package.json";const TSCONFIG="tsconfig.json";const SUFFIX_HTML="/**/*.html";const SUFFIX_JS="/**/*.js";const SUFFIX_TS="/**/*.ts";const SUFFIX_CSS="/**/*.css";const SUFFIX_COMPJSON="/**/component.json";const SUFFIX_ALL="/**/*.*";const OJET_COMMENT="OJET Based Configuration";const NON_OJET_COMMENT="Default Configuration";const SLASHIFY=/\\\\|\\/g;var ojetCommon;var cwd,appCtx,nd,ojet,jetConfig,jafConfig,initDone;var md5;function init(cwdir,nodeDeps,appContext){if(!initDone){cwd=_fwdSlashify(cwdir);nd=nodeDeps;appCtx=appContext;ojet=isOJET();initDone=true}return ojet}function isOJET(){return initDone?!!jetConfig:nd.fsUtils.fileExists(nd.path.join(cwd,OJET_CONFIG))};function handleOjetConfig(isScaffold){var ojetPath,ojafPath,doUpdate=false,temp,hash,tsHash,tsc,defaultExists,error=false;ojetPath=nd.path.join(cwd,OJET_CONFIG);jetConfig=nd.jsonLoader.load(ojetPath,nd,errMsg=>{appCtx.error(errMsg);error=true},false,appCtx.utils);if(isScaffold){if(error){appCtx.error("Cannot continue with --init");return"error"}else if(jetConfig){appCtx.msg(`Scaffolding JAF configuration in ${_getFolderName()} ...`)}else{appCtx.error("OJET CLI config not found - cannot continue with --init");return"error"}}ojafPath=nd.path.join(cwd,OJAF_CONFIG);if(nd.fsUtils.fileExists(ojafPath)){jafConfig=_readJAFConfig(ojafPath);if(jafConfig==="error"){return"error"}}if(isScaffold){defaultExists=_defaultConfigExists();if(jafConfig||defaultExists){appCtx.error("Pre-existing configuration found - '"+(defaultExists?OJAF_DEFAULT_CONFIG:OJAF_CONFIG)+"'");return"error"}}if(!isScaffold&&!jetConfig&&jafConfig){appCtx.warn(`JAF Configuration '${OJAF_CONFIG}' found, but OJET configuration '${OJET_CONFIG}' no longer exists.\n`)}if(jetConfig.paths){if(jetConfig.paths.source&&jetConfig.paths.source.common){ojetCommon="./"+jetConfig.paths.source.common;ojetComposites=ojetCommon+"/"+jetConfig.paths.source.javascript+"/"+COMPOSITES_FOLDER;if(jetConfig.paths.source.typescript)ojetCompositesTs=ojetCommon+"/"+jetConfig.paths.source.typescript+"/"+COMPOSITES_FOLDER}}hash=_isOjetFileChange(ojetPath,jafConfig);if(jafConfig){if(hash){if(jafConfig.ojet&&jafConfig.ojet.update){if(appCtx.verboseMode||appCtx.debugMode){if(hash){appCtx.info(`${OJET_CONFIG} change detected - updating ${OJAF_CONFIG}`)}if(tsHash){if(typeof tsHash==="string"){appCtx.info(`${TSCONFIG} change detected - updating ${OJAF_CONFIG}`)}else{appCtx.info(`${TSCONFIG} no longer found - updating ${OJAF_CONFIG}`)}}}jafConfig.files=_getFileSet();jafConfig.exclude=_getExcludes();jafConfig.components=_getComposites();if(tsc=_getTsConfigPath()){if(jafConfig.typescript){jafConfig.typescript.tsconfig=tsc}else{jafConfig.typescript={tsconfig:tsc}}}else if(jafConfig.typescript&&jafConfig.typescript.tsconfig){delete jafConfig.typescript}if(jafConfig.tsconfig){delete jafConfig.tsconfig}temp=_getJetVer();if(jafConfig.jetVer!==temp){jafConfig.jetVer=temp}temp=_getTheme();if(jafConfig.theme!==temp){jafConfig.theme=temp}if(!jafConfig.ojet){jafConfig.ojet={}}if(hash){jafConfig.ojet.md5=hash}if(typeof jafConfig.ojet.update!=="boolean"){jafConfig.ojet.update=true}if(typeof tsHash==="string"){jafConfig.ojet.tsmd5=tsHash}else if(tsHash&&jafConfig.ojet.tsmd5){delete jafConfig.ojet.tsmd5}doUpdate=true;_backupJAFConfig(ojafPath)}else{const changeMsg=" changes detected, but oraclejafconfig updates are disabled";if(hash){appCtx.warn(OJET_CONFIG+changeMsg)}if(tsHash){appCtx.warn(TSCONFIG+changeMsg)}}}}else if(isScaffold){jafConfig={base:"$jafcwd",files:_getFileSet(),exclude:_getExcludes(),components:_getComposites(),builtinJetRules:true,jetVer:_getJetVer(),ecmaVer:DEFAULTS.ECMAVER,theme:_getTheme(),format:"prose",severity:"all",groups:["all"]};if(tsc=_getTsConfigPath()){jafConfig.typescript={tsconfig:tsc}}if(tsHash){jafConfig.ojet.tsmd5=tsHash}jafConfig.options={verbose:false,color:true};jafConfig.title=["+---------------------------------------------------------------------+","| OJET Application Audit |","+---------------------------------------------------------------------+","JAF $jafver - Jet $jetver : ($jafdate, $jaftime)\n"];jafConfig.ojet={update:true,md5:hash};doUpdate=true}if(doUpdate&&!_writeJAFConfig(OJAF_CONFIG,true)){appCtx.error("Failed to "+(isScaffold?"scaffold":"update")+" OJAF config '"+nd.path.join(cwd,OJAF_CONFIG)+"'");return"error"}if(isScaffold){scaffoldSuccessful(OJAF_CONFIG)}if(appCtx.debugMode){appCtx.debug("JAFConfig :\n"+JSON.stringify(jafConfig,null,3))}return jafConfig};function getOjetConfig(){return jetConfig}function _getFileSet(){var source,src,files=[];if(jetConfig&&jetConfig.paths){if(source=jetConfig.paths.source){if(src=source.common){files.push("./"+src+SUFFIX_HTML);if(source.javascript){files.push("./"+src+SUFFIX_JS)}if(source.typescript){files.push("./"+src+SUFFIX_TS)}files.push("./"+src+SUFFIX_COMPJSON)}if(source.styles){files.push("./"+src+"/"+source.styles+SUFFIX_CSS)}}}return _fwdSlashify(files)};function createNonOjetConfig(){var oj;oj=_ojetJafConfigExists();if(oj||_defaultConfigExists()){appCtx.error("Default configuration '"+(oj?OJAF_CONFIG:OJAF_DEFAULT_CONFIG)+"' exists - terminating --init");return"'error"}jafConfig=_createDefaultNonOjetConfig();_setFileProps(jafConfig);if(!_writeJAFConfig(OJAF_DEFAULT_CONFIG,false)){appCtx.error("Failed to scaffold OJAF config '"+OJAF_DEFAULT_CONFIG+"'");return"error"}scaffoldSuccessful(OJAF_DEFAULT_CONFIG)};function _getExcludes(){var files=[],source;if(jetConfig.paths&&jetConfig.paths.source){source=jetConfig.paths.source.common;files.push("./"+nd.path.join(source,"**"+"/"+"*-min.js"));files.push("./"+nd.path.join(source,"**"+"/"+"*-min.css"));files.push("./**/node_modules/**/*.*")}return _fwdSlashify(files)};function _getComposites(){var a=[],dir;dir="./jet-components/**/component.json";a.push(dir);return _fwdSlashify(a)};function _getTsConfigPath(){return _tsConfigExists()?".":null};function _getJetVer(){var i,ojetPackage,ver,error;ojetPackage=nd.jsonLoader.load(nd.path.join(cwd,PACKAGE_JSON),nd,function(errMsg){appCtx.error(errMsg);appCtx.warn("Defaulting to "+appCtx.defaultJetVer);error=true});if(!error&&ojetPackage&&ojetPackage.dependencies){ver=ojetPackage.dependencies[DEPENDENCIES_VER_PROP];if(ver){for(i=0;i<ver.length;i++){if(!isNaN(ver.charAt(i))){ver=ver.substring(i);break}}ver=ver.replace(".tgz","");i=ver.lastIndexOf(".");ver=ver.substring(0,i)}}return ver?ver:appCtx.defaultJetVer};function _getTheme(){var dt=jetConfig.defaultTheme;if(dt){dt=dt.charAt(0).toUpperCase()+dt.substring(1)}else{dt=DEFAULTS.THEME}return dt};function _getFolderName(){return nd.path.basename(cwd)};function _readJAFConfig(path){var error;var json=nd.jsonLoader.load(path,nd,function(errMsg){appCtx.error(errMsg);error=true},true,appCtx.utils);if(error){appCtx.error(`JSON syntax error -> '${path}`)}return error?"error":json};function _writeJAFConfig(name,isOjet){var data,ret=false;try{data=`// JAF Generated ${isOjet?OJET_COMMENT:NON_OJET_COMMENT}\n// Updated: ${new Date().toString()}\n\n${JSON.stringify(jafConfig,null,3)}`;nd.fs.writeFileSync(nd.path.join(cwd,name),data);ret=true}catch(e){appCtx.error(e)}return ret};function _backupJAFConfig(fp){var data,ret=false;try{data=_readFile(fp);if(data){nd.fs.writeFileSync(fp+".bak",data);ret=true}}catch(e){appCtx.error(e)}return ret};function _isOjetFileChange(ojPath,jafConfig){if(!md5){md5=require("md5")}var ojetMd5,ojafMd5;ojetMd5=md5(_readFile(ojPath));ojafMd5=jafConfig&&jafConfig.ojet&&jafConfig.ojet.md5;return ojetMd5!==ojafMd5?ojetMd5:false};function _readFile(fp){var data;try{data=nd.fs.readFileSync(fp,"utf8")}catch(e){}return data};function _fwdSlashify(path){if(Array.isArray(path)){for(var i=0;i<path.length;i++){path[i]=path[i].replace(SLASHIFY,"/")}return path}else if(path){return path.replace(SLASHIFY,"/")}};function _createDefaultNonOjetConfig(){var o={"base":"$jafcwd","files":[],"exclude":[],"components":["./jet-components/**/component.json"],"builtinJetRules":true,"jetVer":appCtx.defaultJetVer,"ecmaVer":DEFAULTS.ECMAVER,"theme":DEFAULTS.THEME,"groups":["all"],"format":"prose","severity":"all","options":{verbose:false,color:true},"title":["+---------------------------------------------------------------------+","| Application Audit |","+---------------------------------------------------------------------+","JAF $jafver - Jet $jetver : ($jafdate, $jaftime)\n"]};if(_tsConfigExists()){o.typescript={tsconfig:cwd}}return o};function _setFileProps(obj){var path,folder;folder="src";path=_getPathTo(folder);if(path){obj.files.push(path+"/**/*.html");obj.files.push(path+"/**/*.js");obj.files.push(path+"/**/*.ts");obj.files.push(path+"/**/*.css");obj.exclude.push(path+"/**/*-min.js");obj.exclude.push(path+"/**/*-min.css")}folder="jet-composites";path=_getPathTo(folder);if(path){obj.components=[path];obj.exclude.push(path+"/**/extension/**/*.*");obj.exclude.push(path+"/**/resources/**/*.*")}obj.exclude.push("./**/node_modules/**/*.*")};function _getPathTo(folder){var path=nd.fsUtils.findFile(cwd,folder,function(dir,file){return file!=="node_modules"&&!dir.includes("node_modules")});if(path){path=nd.path.join(path,folder);path=_fwdSlashify(path);path="."+path.replace(cwd,"")}else{path=null}return path};function _defaultConfigExists(){var file=nd.path.join(cwd,OJAF_DEFAULT_CONFIG);return nd.fsUtils.fileExists(file)};function _ojetJafConfigExists(){var file=nd.path.join(cwd,OJAF_CONFIG);return nd.fsUtils.fileExists(file)};function _tsConfigExists(){var file=nd.path.join(cwd,TSCONFIG);return nd.fsUtils.fileExists(file)};function scaffoldSuccessful(configName){appCtx.msg(" __ ___");appCtx.msg(" __ / /___ _/ _/ Configuration generation successful");appCtx.msg(" / // // _ `/ _/ created: '@@'".replace("@@",configName));appCtx.msg(" \\___/ \\_,_/_/\n")};module.exports={init,isOJET,handleOjetConfig,createNonOjetConfig,getOjetConfig};
6
+ const DEFAULTS=require("./defaults");const OJET_CONFIG="oraclejetconfig.json";const OJAF_CONFIG="oraclejafconfig.json";const OJAF_DEFAULT_CONFIG="jafconfig.json";const DEPENDENCIES_VER_PROP="@oracle/oraclejet";const PACKAGE_JSON="package.json";const TSCONFIG="tsconfig.json";const SUFFIX_HTML="/**/*.html";const SUFFIX_JS="/**/*.js";const SUFFIX_TS="/**/*.ts";const SUFFIX_CSS="/**/*.css";const SUFFIX_COMPJSON="/**/component.json";const SUFFIX_ALL="/**/*.*";const OJET_COMMENT="OJET Based Configuration";const NON_OJET_COMMENT="Default Configuration";const SLASHIFY=/\\\\|\\/g;const STABLE="Stable";var cwd,appCtx,nd,ojet,jetConfig,jafConfig,initDone;var md5;function init(cwdir,nodeDeps,appContext){if(!initDone){cwd=_fwdSlashify(cwdir);nd=nodeDeps;appCtx=appContext;ojet=isOJET();initDone=true}return ojet}function isOJET(){return initDone?!!jetConfig:nd.fsUtils.fileExists(nd.path.join(cwd,OJET_CONFIG))};function handleOjetConfig(isScaffold){var ojetPath,ojafPath,doUpdate=false,temp,hash,tsHash,tsc,defaultExists,error=false;ojetPath=nd.path.join(cwd,OJET_CONFIG);jetConfig=nd.jsonLoader.load(ojetPath,nd,errMsg=>{appCtx.error(errMsg);error=true},false,appCtx.utils);if(isScaffold){if(error){appCtx.error("Cannot continue with --init");return"error"}else if(jetConfig){appCtx.msg(`Scaffolding JAF configuration in ${_getFolderName()} ...`)}else{appCtx.error("OJET CLI config not found - cannot continue with --init");return"error"}}ojafPath=nd.path.join(cwd,OJAF_CONFIG);if(nd.fsUtils.fileExists(ojafPath)){jafConfig=_readJAFConfig(ojafPath);if(jafConfig==="error"){return"error"}}if(isScaffold){defaultExists=_defaultConfigExists();if(jafConfig||defaultExists){appCtx.error("Pre-existing configuration found - '"+(defaultExists?OJAF_DEFAULT_CONFIG:OJAF_CONFIG)+"'");return"error"}}if(!isScaffold&&!jetConfig&&jafConfig){appCtx.warn(`JAF Configuration '${OJAF_CONFIG}' found, but OJET configuration '${OJET_CONFIG}' no longer exists.\n`)}hash=_isOjetFileChange(ojetPath,jafConfig);if(jafConfig){if(hash){if(jafConfig.ojet&&jafConfig.ojet.update){if(appCtx.verboseMode||appCtx.debugMode){if(hash){appCtx.info(`${OJET_CONFIG} change detected - updating ${OJAF_CONFIG}`)}if(tsHash){if(typeof tsHash==="string"){appCtx.info(`${TSCONFIG} change detected - updating ${OJAF_CONFIG}`)}else{appCtx.info(`${TSCONFIG} no longer found - updating ${OJAF_CONFIG}`)}}}jafConfig.files=_getFileSet();jafConfig.exclude=_getExcludes();jafConfig.components=_getComposites();if(tsc=_getTsConfigPath()){if(jafConfig.typescript){jafConfig.typescript.tsconfig=tsc}else{jafConfig.typescript={tsconfig:tsc}}}else if(jafConfig.typescript&&jafConfig.typescript.tsconfig){delete jafConfig.typescript}if(jafConfig.tsconfig){delete jafConfig.tsconfig}temp=_getJetVer();if(jafConfig.jetVer!==temp){jafConfig.jetVer=temp}if(temp=_getTheme()){if(jafConfig.theme!==temp){jafConfig.theme=temp}}else if(jafConfig.theme){delete jafConfig.theme}if(!jafConfig.ojet){jafConfig.ojet={}}if(hash){jafConfig.ojet.md5=hash}if(typeof jafConfig.ojet.update!=="boolean"){jafConfig.ojet.update=true}if(typeof tsHash==="string"){jafConfig.ojet.tsmd5=tsHash}else if(tsHash&&jafConfig.ojet.tsmd5){delete jafConfig.ojet.tsmd5}doUpdate=true;_backupJAFConfig(ojafPath)}else{const changeMsg=" changes detected, but oraclejafconfig updates are disabled";if(hash){appCtx.warn(OJET_CONFIG+changeMsg)}if(tsHash){appCtx.warn(TSCONFIG+changeMsg)}}}}else if(isScaffold){jafConfig={base:"$jafcwd",files:_getFileSet(),exclude:_getExcludes(),components:_getComposites(),builtinJetRules:true,jetVer:_getJetVer(),ecmaVer:DEFAULTS.ECMAVER,format:"prose",severity:"all",groups:["all"]};if(temp=_getTheme()){jafConfig.theme=temp}if(tsc=_getTsConfigPath()){jafConfig.typescript={tsconfig:tsc}}if(tsHash){jafConfig.ojet.tsmd5=tsHash}jafConfig.options={verbose:false,color:true};jafConfig.title=["+---------------------------------------------------------------------+","| OJET Application Audit |","+---------------------------------------------------------------------+","JAF $jafver - Jet $jetver : ($jafdate, $jaftime)\n"];jafConfig.ojet={update:true,md5:hash};doUpdate=true}if(doUpdate&&!_writeJAFConfig(OJAF_CONFIG,true)){appCtx.error("Failed to "+(isScaffold?"scaffold":"update")+" OJAF config '"+nd.path.join(cwd,OJAF_CONFIG)+"'");return"error"}if(isScaffold){scaffoldSuccessful(OJAF_CONFIG)}if(appCtx.debugMode){appCtx.debug("JAFConfig :\n"+JSON.stringify(jafConfig,null,3))}return jafConfig};function getOjetConfig(){return jetConfig}function _getFileSet(){var source,src,files=[];if(jetConfig&&jetConfig.paths){if(source=jetConfig.paths.source){if(src=source.common){files.push("./"+src+SUFFIX_HTML);if(source.javascript){files.push("./"+src+SUFFIX_JS)}if(source.typescript){files.push("./"+src+SUFFIX_TS)}files.push("./"+src+SUFFIX_COMPJSON)}if(source.styles){files.push("./"+src+"/"+source.styles+SUFFIX_CSS)}}}return _fwdSlashify(files)};function createNonOjetConfig(){var oj;oj=_ojetJafConfigExists();if(oj||_defaultConfigExists()){appCtx.error("Default configuration '"+(oj?OJAF_CONFIG:OJAF_DEFAULT_CONFIG)+"' exists - terminating --init");return"'error"}jafConfig=_createDefaultNonOjetConfig();_setFileProps(jafConfig);if(!_writeJAFConfig(OJAF_DEFAULT_CONFIG,false)){appCtx.error("Failed to scaffold OJAF config '"+OJAF_DEFAULT_CONFIG+"'");return"error"}scaffoldSuccessful(OJAF_DEFAULT_CONFIG)};function _getExcludes(){var files=[],source;if(jetConfig.paths&&jetConfig.paths.source){source=jetConfig.paths.source.common;files.push("./"+nd.path.join(source,"**"+"/"+"*-min.js"));files.push("./"+nd.path.join(source,"**"+"/"+"*-min.css"));files.push("./**/node_modules/**/*.*")}return _fwdSlashify(files)};function _getComposites(){var a=[],dir;if(jetConfig.paths&&jetConfig.paths.exchangeComponents){dir="./exchange_components/**/component.json"}else{dir="./jet_components/**/component.json"}a.push(dir);return _fwdSlashify(a)};function _getTsConfigPath(){return _tsConfigExists()?".":null};function _getJetVer(){var i,ojetPackage,ver,error;ojetPackage=nd.jsonLoader.load(nd.path.join(cwd,PACKAGE_JSON),nd,function(errMsg){appCtx.error(errMsg);appCtx.warn("Defaulting to "+appCtx.defaultJetVer);error=true});if(!error&&ojetPackage&&ojetPackage.dependencies){ver=ojetPackage.dependencies[DEPENDENCIES_VER_PROP];if(ver){for(i=0;i<ver.length;i++){if(!isNaN(ver.charAt(i))){ver=ver.substring(i);break}}ver=ver.replace(".tgz","");i=ver.lastIndexOf(".");ver=ver.substring(0,i)}}return ver?ver:appCtx.defaultJetVer};function _getTheme(){var dt=jetConfig.defaultTheme;if(dt){dt=dt.charAt(0).toUpperCase()+dt.substring(1);if(dt===STABLE){dt="Redwood"}}return dt};function _getFolderName(){return nd.path.basename(cwd)};function _readJAFConfig(path){var error;var json=nd.jsonLoader.load(path,nd,function(errMsg){appCtx.error(errMsg);error=true},true,appCtx.utils);if(error){appCtx.error(`JSON syntax error -> '${path}`)}return error?"error":json};function _writeJAFConfig(name,isOjet){var data,ret=false;try{data=`// JAF Generated ${isOjet?OJET_COMMENT:NON_OJET_COMMENT}\n// Updated: ${new Date().toString()}\n\n${JSON.stringify(jafConfig,null,3)}`;nd.fs.writeFileSync(nd.path.join(cwd,name),data);ret=true}catch(e){appCtx.error(e)}return ret};function _backupJAFConfig(fp){var data,ret=false;try{data=_readFile(fp);if(data){nd.fs.writeFileSync(fp+".bak",data);ret=true}}catch(e){appCtx.error(e)}return ret};function _isOjetFileChange(ojPath,jafConfig){if(!md5){md5=require("md5")}var ojetMd5,ojafMd5;ojetMd5=md5(_readFile(ojPath));ojafMd5=jafConfig&&jafConfig.ojet&&jafConfig.ojet.md5;return ojetMd5!==ojafMd5?ojetMd5:false};function _readFile(fp){var data;try{data=nd.fs.readFileSync(fp,"utf8")}catch(e){}return data};function _fwdSlashify(path){if(Array.isArray(path)){for(var i=0;i<path.length;i++){path[i]=path[i].replace(SLASHIFY,"/")}return path}else if(path){return path.replace(SLASHIFY,"/")}};function _createDefaultNonOjetConfig(){var o={"base":"$jafcwd","files":[],"exclude":[],"components":["./jet_components/**/component.json"],"builtinJetRules":true,"jetVer":appCtx.defaultJetVer,"ecmaVer":DEFAULTS.ECMAVER,"groups":["all"],"format":"prose","severity":"all","options":{verbose:false,color:true},"title":["+---------------------------------------------------------------------+","| Application Audit |","+---------------------------------------------------------------------+","JAF $jafver - Jet $jetver : ($jafdate, $jaftime)\n"]};if(_tsConfigExists()){o.typescript={tsconfig:cwd}}return o};function _setFileProps(obj){var path,folder;folder="src";path=_getPathTo(folder);if(path){obj.files.push(path+"/**/*.html");obj.files.push(path+"/**/*.js");obj.files.push(path+"/**/*.ts");obj.files.push(path+"/**/*.css");obj.exclude.push(path+"/**/*-min.js");obj.exclude.push(path+"/**/*-min.css")}folder="jet-composites";path=_getPathTo(folder);if(path){obj.components=[path];obj.exclude.push(path+"/**/extension/**/*.*");obj.exclude.push(path+"/**/resources/**/*.*")}obj.exclude.push("./**/node_modules/**/*.*")};function _getPathTo(folder){var path=nd.fsUtils.findFile(cwd,folder,function(dir,file){return file!=="node_modules"&&!dir.includes("node_modules")});if(path){path=nd.path.join(path,folder);path=_fwdSlashify(path);path="."+path.replace(cwd,"")}else{path=null}return path};function _defaultConfigExists(){var file=nd.path.join(cwd,OJAF_DEFAULT_CONFIG);return nd.fsUtils.fileExists(file)};function _ojetJafConfigExists(){var file=nd.path.join(cwd,OJAF_CONFIG);return nd.fsUtils.fileExists(file)};function _tsConfigExists(){var file=nd.path.join(cwd,TSCONFIG);return nd.fsUtils.fileExists(file)};function scaffoldSuccessful(configName){appCtx.msg(" __ ___");appCtx.msg(" __ / /___ _/ _/ Configuration generation successful");appCtx.msg(" / // // _ `/ _/ created: '@@'".replace("@@",configName));appCtx.msg(" \\___/ \\_,_/_/\n")};module.exports={init,isOJET,handleOjetConfig,createNonOjetConfig,getOjetConfig};
@@ -3,4 +3,4 @@
3
3
  * Licensed under The Universal Permissive License (UPL), Version 1.0
4
4
  * as shown at https://oss.oracle.com/licenses/upl/
5
5
  */
6
- (function clone(exports){'use strict';var Syntax,VisitorOption,VisitorKeys,BREAK,SKIP,REMOVE;function deepCopy(obj){var ret={},key,val;for(key in obj){if(obj.hasOwnProperty(key)){val=obj[key];if(typeof val==='object'&&val!==null){ret[key]=deepCopy(val)}else{ret[key]=val}}}return ret}function upperBound(array,func){var diff,len,i,current;len=array.length;i=0;while(len){diff=len>>>1;current=i+diff;if(func(array[current])){len=diff}else{i=current+1;len-=diff+1}}return i}Syntax={AssignmentExpression:'AssignmentExpression',AssignmentPattern:'AssignmentPattern',ArrayExpression:'ArrayExpression',ArrayPattern:'ArrayPattern',ArrowFunctionExpression:'ArrowFunctionExpression',AwaitExpression:'AwaitExpression',BlockStatement:'BlockStatement',BinaryExpression:'BinaryExpression',BreakStatement:'BreakStatement',CallExpression:'CallExpression',CatchClause:'CatchClause',ChainExpression:'ChainExpression',ClassBody:'ClassBody',ClassDeclaration:'ClassDeclaration',ClassExpression:'ClassExpression',ComprehensionBlock:'ComprehensionBlock',ComprehensionExpression:'ComprehensionExpression',ConditionalExpression:'ConditionalExpression',ContinueStatement:'ContinueStatement',DebuggerStatement:'DebuggerStatement',DirectiveStatement:'DirectiveStatement',DoWhileStatement:'DoWhileStatement',EmptyStatement:'EmptyStatement',ExportAllDeclaration:'ExportAllDeclaration',ExportDefaultDeclaration:'ExportDefaultDeclaration',ExportNamedDeclaration:'ExportNamedDeclaration',ExportSpecifier:'ExportSpecifier',ExpressionStatement:'ExpressionStatement',ForStatement:'ForStatement',ForInStatement:'ForInStatement',ForOfStatement:'ForOfStatement',FunctionDeclaration:'FunctionDeclaration',FunctionExpression:'FunctionExpression',GeneratorExpression:'GeneratorExpression',Identifier:'Identifier',IfStatement:'IfStatement',ImportExpression:'ImportExpression',ImportDeclaration:'ImportDeclaration',ImportDefaultSpecifier:'ImportDefaultSpecifier',ImportNamespaceSpecifier:'ImportNamespaceSpecifier',ImportSpecifier:'ImportSpecifier',Literal:'Literal',LabeledStatement:'LabeledStatement',LogicalExpression:'LogicalExpression',MemberExpression:'MemberExpression',MetaProperty:'MetaProperty',MethodDefinition:'MethodDefinition',ModuleSpecifier:'ModuleSpecifier',NewExpression:'NewExpression',ObjectExpression:'ObjectExpression',ObjectPattern:'ObjectPattern',Program:'Program',Property:'Property',RestElement:'RestElement',ReturnStatement:'ReturnStatement',SequenceExpression:'SequenceExpression',SpreadElement:'SpreadElement',Super:'Super',SwitchStatement:'SwitchStatement',SwitchCase:'SwitchCase',TaggedTemplateExpression:'TaggedTemplateExpression',TemplateElement:'TemplateElement',TemplateLiteral:'TemplateLiteral',ThisExpression:'ThisExpression',ThrowStatement:'ThrowStatement',TryStatement:'TryStatement',UnaryExpression:'UnaryExpression',UpdateExpression:'UpdateExpression',VariableDeclaration:'VariableDeclaration',VariableDeclarator:'VariableDeclarator',WhileStatement:'WhileStatement',WithStatement:'WithStatement',YieldExpression:'YieldExpression',ClassProperty:'ClassProperty',TSAsExpression:'TSAsExpression',TSImportEqualsDeclaration:'TSImportEqualsDeclaration',TSTypeAliasDeclaration:'TSTypeAliasDeclaration',TSInterfaceDeclaration:'TSInterfaceDeclaration',JSXElement:'JsxElement',JSXOpeningElement:'JSXOpeningElement'};VisitorKeys={AssignmentExpression:['left','right'],AssignmentPattern:['left','right'],ArrayExpression:['elements'],ArrayPattern:['elements'],ArrowFunctionExpression:['params','body'],AwaitExpression:['argument'],BlockStatement:['body'],BinaryExpression:['left','right'],BreakStatement:['label'],CallExpression:['callee','arguments'],CatchClause:['param','body'],ChainExpression:['expression'],ClassBody:['body'],ClassDeclaration:['id','superClass','body'],ClassExpression:['id','superClass','body'],ComprehensionBlock:['left','right'],ComprehensionExpression:['blocks','filter','body'],ConditionalExpression:['test','consequent','alternate'],ContinueStatement:['label'],DebuggerStatement:[],DirectiveStatement:[],DoWhileStatement:['body','test'],EmptyStatement:[],ExportAllDeclaration:['source'],ExportDefaultDeclaration:['declaration'],ExportNamedDeclaration:['declaration','specifiers','source'],ExportSpecifier:['exported','local'],ExpressionStatement:['expression'],ForStatement:['init','test','update','body'],ForInStatement:['left','right','body'],ForOfStatement:['left','right','body'],FunctionDeclaration:['id','params','body'],FunctionExpression:['id','params','body'],GeneratorExpression:['blocks','filter','body'],Identifier:[],IfStatement:['test','consequent','alternate'],ImportExpression:['source'],ImportDeclaration:['specifiers','source'],ImportDefaultSpecifier:['local'],ImportNamespaceSpecifier:['local'],ImportSpecifier:['imported','local'],Literal:[],LabeledStatement:['label','body'],LogicalExpression:['left','right'],MemberExpression:['object','property'],MetaProperty:['meta','property'],MethodDefinition:['key','value'],ModuleSpecifier:[],NewExpression:['callee','arguments'],ObjectExpression:['properties'],ObjectPattern:['properties'],Program:['body'],Property:['key','value'],RestElement:['argument'],ReturnStatement:['argument'],SequenceExpression:['expressions'],SpreadElement:['argument'],Super:[],SwitchStatement:['discriminant','cases'],SwitchCase:['test','consequent'],TaggedTemplateExpression:['tag','quasi'],TemplateElement:[],TemplateLiteral:['quasis','expressions'],ThisExpression:[],ThrowStatement:['argument'],TryStatement:['block','handler','finalizer'],UnaryExpression:['argument'],UpdateExpression:['argument'],VariableDeclaration:['declarations'],VariableDeclarator:['id','init'],WhileStatement:['test','body'],WithStatement:['object','body'],YieldExpression:['argument'],ClassProperty:[],TSAsExpression:[],TSImportEqualsDeclaration:[],TSTypeAliasDeclaration:[],TSInterfaceDeclaration:[],JSXElement:[],JSXOpeningElement:[]};BREAK={};SKIP={};REMOVE={};VisitorOption={Break:BREAK,Skip:SKIP,Remove:REMOVE};function Reference(parent,key){this.parent=parent;this.key=key}Reference.prototype.replace=function replace(node){this.parent[this.key]=node};Reference.prototype.remove=function remove(){if(Array.isArray(this.parent)){this.parent.splice(this.key,1);return true}else{this.replace(null);return false}};function Element(node,path,wrap,ref){this.node=node;this.path=path;this.wrap=wrap;this.ref=ref}function Controller(){}Controller.prototype.path=function path(){var i,iz,j,jz,result,element;function addToPath(result,path){if(Array.isArray(path)){for(j=0,jz=path.length;j<jz;++j){result.push(path[j])}}else{result.push(path)}}if(!this.__current.path){return null}result=[];for(i=2,iz=this.__leavelist.length;i<iz;++i){element=this.__leavelist[i];addToPath(result,element.path)}addToPath(result,this.__current.path);return result};Controller.prototype.type=function(){var node=this.current();return node.type||this.__current.wrap};Controller.prototype.parents=function parents(){var i,iz,result;result=[];for(i=1,iz=this.__leavelist.length;i<iz;++i){result.push(this.__leavelist[i].node)}return result};Controller.prototype.current=function current(){return this.__current.node};Controller.prototype.__execute=function __execute(callback,element){var previous,result;result=undefined;previous=this.__current;this.__current=element;this.__state=null;if(callback){result=callback.call(this,element.node,this.__leavelist[this.__leavelist.length-1].node)}this.__current=previous;return result};Controller.prototype.notify=function notify(flag){this.__state=flag};Controller.prototype.skip=function(){this.notify(SKIP)};Controller.prototype['break']=function(){this.notify(BREAK)};Controller.prototype.remove=function(){this.notify(REMOVE)};Controller.prototype.__initialize=function(root,visitor){this.visitor=visitor;this.root=root;this.__worklist=[];this.__leavelist=[];this.__current=null;this.__state=null;this.__fallback=null;if(visitor.fallback==='iteration'){this.__fallback=Object.keys}else if(typeof visitor.fallback==='function'){this.__fallback=visitor.fallback}this.__keys=VisitorKeys;if(visitor.keys){this.__keys=Object.assign(Object.create(this.__keys),visitor.keys)}};function isNode(node){if(node==null){return false}return typeof node==='object'&&typeof node.type==='string'}function isProperty(nodeType,key){return(nodeType===Syntax.ObjectExpression||nodeType===Syntax.ObjectPattern)&&'properties'===key}function candidateExistsInLeaveList(leavelist,candidate){for(var i=leavelist.length-1;i>=0;--i){if(leavelist[i].node===candidate){return true}}return false}Controller.prototype.traverse=function traverse(root,visitor){var worklist,leavelist,element,node,nodeType,ret,key,current,current2,candidates,candidate,sentinel;this.__initialize(root,visitor);sentinel={};worklist=this.__worklist;leavelist=this.__leavelist;worklist.push(new Element(root,null,null,null));leavelist.push(new Element(null,null,null,null));while(worklist.length){element=worklist.pop();if(element===sentinel){element=leavelist.pop();ret=this.__execute(visitor.leave,element);if(this.__state===BREAK||ret===BREAK){return}continue}if(element.node){ret=this.__execute(visitor.enter,element);if(this.__state===BREAK||ret===BREAK){return}worklist.push(sentinel);leavelist.push(element);if(this.__state===SKIP||ret===SKIP){continue}node=element.node;nodeType=node.type||element.wrap;candidates=this.__keys[nodeType];if(!candidates){if(this.__fallback){candidates=this.__fallback(node)}else{throw new Error('Unknown node type '+nodeType+'.')}}current=candidates.length;while((current-=1)>=0){key=candidates[current];candidate=node[key];if(!candidate){continue}if(Array.isArray(candidate)){current2=candidate.length;while((current2-=1)>=0){if(!candidate[current2]){continue}if(candidateExistsInLeaveList(leavelist,candidate[current2])){continue}if(isProperty(nodeType,candidates[current])){element=new Element(candidate[current2],[key,current2],'Property',null)}else if(isNode(candidate[current2])){element=new Element(candidate[current2],[key,current2],null,null)}else{continue}worklist.push(element)}}else if(isNode(candidate)){if(candidateExistsInLeaveList(leavelist,candidate)){continue}worklist.push(new Element(candidate,key,null,null))}}}}};Controller.prototype.replace=function replace(root,visitor){var worklist,leavelist,node,nodeType,target,element,current,current2,candidates,candidate,sentinel,outer,key;function removeElem(element){var i,key,nextElem,parent;if(element.ref.remove()){key=element.ref.key;parent=element.ref.parent;i=worklist.length;while(i--){nextElem=worklist[i];if(nextElem.ref&&nextElem.ref.parent===parent){if(nextElem.ref.key<key){break}--nextElem.ref.key}}}}this.__initialize(root,visitor);sentinel={};worklist=this.__worklist;leavelist=this.__leavelist;outer={root:root};element=new Element(root,null,null,new Reference(outer,'root'));worklist.push(element);leavelist.push(element);while(worklist.length){element=worklist.pop();if(element===sentinel){element=leavelist.pop();target=this.__execute(visitor.leave,element);if(target!==undefined&&target!==BREAK&&target!==SKIP&&target!==REMOVE){element.ref.replace(target)}if(this.__state===REMOVE||target===REMOVE){removeElem(element)}if(this.__state===BREAK||target===BREAK){return outer.root}continue}target=this.__execute(visitor.enter,element);if(target!==undefined&&target!==BREAK&&target!==SKIP&&target!==REMOVE){element.ref.replace(target);element.node=target}if(this.__state===REMOVE||target===REMOVE){removeElem(element);element.node=null}if(this.__state===BREAK||target===BREAK){return outer.root}node=element.node;if(!node){continue}worklist.push(sentinel);leavelist.push(element);if(this.__state===SKIP||target===SKIP){continue}nodeType=node.type||element.wrap;candidates=this.__keys[nodeType];if(!candidates){if(this.__fallback){candidates=this.__fallback(node)}else{throw new Error('Unknown node type '+nodeType+'.')}}current=candidates.length;while((current-=1)>=0){key=candidates[current];candidate=node[key];if(!candidate){continue}if(Array.isArray(candidate)){current2=candidate.length;while((current2-=1)>=0){if(!candidate[current2]){continue}if(isProperty(nodeType,candidates[current])){element=new Element(candidate[current2],[key,current2],'Property',new Reference(candidate,current2))}else if(isNode(candidate[current2])){element=new Element(candidate[current2],[key,current2],null,new Reference(candidate,current2))}else{continue}worklist.push(element)}}else if(isNode(candidate)){worklist.push(new Element(candidate,key,null,new Reference(node,key)))}}}return outer.root};function traverse(root,visitor){var controller=new Controller;return controller.traverse(root,visitor)}function replace(root,visitor){var controller=new Controller;return controller.replace(root,visitor)}function extendCommentRange(comment,tokens){var target;target=upperBound(tokens,function search(token){return token.range[0]>comment.range[0]});comment.extendedRange=[comment.range[0],comment.range[1]];if(target!==tokens.length){comment.extendedRange[1]=tokens[target].range[0]}target-=1;if(target>=0){comment.extendedRange[0]=tokens[target].range[1]}return comment}function attachComments(tree,providedComments,tokens){var comments=[],comment,len,i,cursor;if(!tree.range){throw new Error('attachComments needs range information')}if(!tokens.length){if(providedComments.length){for(i=0,len=providedComments.length;i<len;i+=1){comment=deepCopy(providedComments[i]);comment.extendedRange=[0,tree.range[0]];comments.push(comment)}tree.leadingComments=comments}return tree}for(i=0,len=providedComments.length;i<len;i+=1){comments.push(extendCommentRange(deepCopy(providedComments[i]),tokens))}cursor=0;traverse(tree,{enter:function(node){var comment;while(cursor<comments.length){comment=comments[cursor];if(comment.extendedRange[1]>node.range[0]){break}if(comment.extendedRange[1]===node.range[0]){if(!node.leadingComments){node.leadingComments=[]}node.leadingComments.push(comment);comments.splice(cursor,1)}else{cursor+=1}}if(cursor===comments.length){return VisitorOption.Break}if(comments[cursor].extendedRange[0]>node.range[1]){return VisitorOption.Skip}}});cursor=0;traverse(tree,{leave:function(node){var comment;while(cursor<comments.length){comment=comments[cursor];if(node.range[1]<comment.extendedRange[0]){break}if(node.range[1]===comment.extendedRange[0]){if(!node.trailingComments){node.trailingComments=[]}node.trailingComments.push(comment);comments.splice(cursor,1)}else{cursor+=1}}if(cursor===comments.length){return VisitorOption.Break}if(comments[cursor].extendedRange[0]>node.range[1]){return VisitorOption.Skip}}});return tree}exports.Syntax=Syntax;exports.traverse=traverse;exports.replace=replace;exports.attachComments=attachComments;exports.VisitorKeys=VisitorKeys;exports.VisitorOption=VisitorOption;exports.Controller=Controller;exports.cloneEnvironment=function(){return clone({})};return exports})(exports);
6
+ (function clone(exports){'use strict';var Syntax,VisitorOption,VisitorKeys,BREAK,SKIP,REMOVE;function deepCopy(obj){var ret={},key,val;for(key in obj){if(obj.hasOwnProperty(key)){val=obj[key];if(typeof val==='object'&&val!==null){ret[key]=deepCopy(val)}else{ret[key]=val}}}return ret}function upperBound(array,func){var diff,len,i,current;len=array.length;i=0;while(len){diff=len>>>1;current=i+diff;if(func(array[current])){len=diff}else{i=current+1;len-=diff+1}}return i}Syntax={AssignmentExpression:'AssignmentExpression',AssignmentPattern:'AssignmentPattern',ArrayExpression:'ArrayExpression',ArrayPattern:'ArrayPattern',ArrowFunctionExpression:'ArrowFunctionExpression',AwaitExpression:'AwaitExpression',BlockStatement:'BlockStatement',BinaryExpression:'BinaryExpression',BreakStatement:'BreakStatement',CallExpression:'CallExpression',CatchClause:'CatchClause',ChainExpression:'ChainExpression',ClassBody:'ClassBody',ClassDeclaration:'ClassDeclaration',ClassExpression:'ClassExpression',ComprehensionBlock:'ComprehensionBlock',ComprehensionExpression:'ComprehensionExpression',ConditionalExpression:'ConditionalExpression',ContinueStatement:'ContinueStatement',DebuggerStatement:'DebuggerStatement',DirectiveStatement:'DirectiveStatement',DoWhileStatement:'DoWhileStatement',EmptyStatement:'EmptyStatement',ExportAllDeclaration:'ExportAllDeclaration',ExportDefaultDeclaration:'ExportDefaultDeclaration',ExportNamedDeclaration:'ExportNamedDeclaration',ExportSpecifier:'ExportSpecifier',ExpressionStatement:'ExpressionStatement',ForStatement:'ForStatement',ForInStatement:'ForInStatement',ForOfStatement:'ForOfStatement',FunctionDeclaration:'FunctionDeclaration',FunctionExpression:'FunctionExpression',GeneratorExpression:'GeneratorExpression',Identifier:'Identifier',IfStatement:'IfStatement',ImportExpression:'ImportExpression',ImportDeclaration:'ImportDeclaration',ImportDefaultSpecifier:'ImportDefaultSpecifier',ImportNamespaceSpecifier:'ImportNamespaceSpecifier',ImportSpecifier:'ImportSpecifier',Literal:'Literal',LabeledStatement:'LabeledStatement',LogicalExpression:'LogicalExpression',MemberExpression:'MemberExpression',MetaProperty:'MetaProperty',MethodDefinition:'MethodDefinition',ModuleSpecifier:'ModuleSpecifier',NewExpression:'NewExpression',ObjectExpression:'ObjectExpression',ObjectPattern:'ObjectPattern',Program:'Program',Property:'Property',RestElement:'RestElement',ReturnStatement:'ReturnStatement',SequenceExpression:'SequenceExpression',SpreadElement:'SpreadElement',Super:'Super',SwitchStatement:'SwitchStatement',SwitchCase:'SwitchCase',TaggedTemplateExpression:'TaggedTemplateExpression',TemplateElement:'TemplateElement',TemplateLiteral:'TemplateLiteral',ThisExpression:'ThisExpression',ThrowStatement:'ThrowStatement',TryStatement:'TryStatement',UnaryExpression:'UnaryExpression',UpdateExpression:'UpdateExpression',VariableDeclaration:'VariableDeclaration',VariableDeclarator:'VariableDeclarator',WhileStatement:'WhileStatement',WithStatement:'WithStatement',YieldExpression:'YieldExpression',ClassProperty:'ClassProperty',TSAsExpression:'TSAsExpression',TSImportEqualsDeclaration:'TSImportEqualsDeclaration',TSTypeAliasDeclaration:'TSTypeAliasDeclaration',TSInterfaceDeclaration:'TSInterfaceDeclaration',JSXElement:'JsxElement',JSXOpeningElement:'JSXOpeningElement'};VisitorKeys={AssignmentExpression:['left','right'],AssignmentPattern:['left','right'],ArrayExpression:['elements'],ArrayPattern:['elements'],ArrowFunctionExpression:['params','body'],AwaitExpression:['argument'],BlockStatement:['body'],BinaryExpression:['left','right'],BreakStatement:['label'],CallExpression:['callee','arguments'],CatchClause:['param','body'],ChainExpression:['expression'],ClassBody:['body'],ClassDeclaration:['id','superClass','body'],ClassExpression:['id','superClass','body'],ComprehensionBlock:['left','right'],ComprehensionExpression:['blocks','filter','body'],ConditionalExpression:['test','consequent','alternate'],ContinueStatement:['label'],DebuggerStatement:[],DirectiveStatement:[],DoWhileStatement:['body','test'],EmptyStatement:[],ExportAllDeclaration:['source'],ExportDefaultDeclaration:['declaration'],ExportNamedDeclaration:['declaration','specifiers','source'],ExportSpecifier:['exported','local'],ExpressionStatement:['expression'],ForStatement:['init','test','update','body'],ForInStatement:['left','right','body'],ForOfStatement:['left','right','body'],FunctionDeclaration:['id','params','body'],FunctionExpression:['id','params','body'],GeneratorExpression:['blocks','filter','body'],Identifier:[],IfStatement:['test','consequent','alternate'],ImportExpression:['source'],ImportDeclaration:['specifiers','source'],ImportDefaultSpecifier:['local'],ImportNamespaceSpecifier:['local'],ImportSpecifier:['imported','local'],Literal:[],LabeledStatement:['label','body'],LogicalExpression:['left','right'],MemberExpression:['object','property'],MetaProperty:['meta','property'],MethodDefinition:['key','value'],ModuleSpecifier:[],NewExpression:['callee','arguments'],ObjectExpression:['properties'],ObjectPattern:['properties'],Program:['body'],Property:['key','value'],RestElement:['argument'],ReturnStatement:['argument'],SequenceExpression:['expressions'],SpreadElement:['argument'],Super:[],SwitchStatement:['discriminant','cases'],SwitchCase:['test','consequent'],TaggedTemplateExpression:['tag','quasi'],TemplateElement:[],TemplateLiteral:['quasis','expressions'],ThisExpression:[],ThrowStatement:['argument'],TryStatement:['block','handler','finalizer'],UnaryExpression:['argument'],UpdateExpression:['argument'],VariableDeclaration:['declarations'],VariableDeclarator:['id','init'],WhileStatement:['test','body'],WithStatement:['object','body'],YieldExpression:['argument'],ClassProperty:[],TSAsExpression:[],TSEnumDeclaration:[],TSImportEqualsDeclaration:[],TSTypeAliasDeclaration:[],TSInterfaceDeclaration:[],JSXElement:[],JSXOpeningElement:[]};BREAK={};SKIP={};REMOVE={};VisitorOption={Break:BREAK,Skip:SKIP,Remove:REMOVE};function Reference(parent,key){this.parent=parent;this.key=key}Reference.prototype.replace=function replace(node){this.parent[this.key]=node};Reference.prototype.remove=function remove(){if(Array.isArray(this.parent)){this.parent.splice(this.key,1);return true}else{this.replace(null);return false}};function Element(node,path,wrap,ref){this.node=node;this.path=path;this.wrap=wrap;this.ref=ref}function Controller(){}Controller.prototype.path=function path(){var i,iz,j,jz,result,element;function addToPath(result,path){if(Array.isArray(path)){for(j=0,jz=path.length;j<jz;++j){result.push(path[j])}}else{result.push(path)}}if(!this.__current.path){return null}result=[];for(i=2,iz=this.__leavelist.length;i<iz;++i){element=this.__leavelist[i];addToPath(result,element.path)}addToPath(result,this.__current.path);return result};Controller.prototype.type=function(){var node=this.current();return node.type||this.__current.wrap};Controller.prototype.parents=function parents(){var i,iz,result;result=[];for(i=1,iz=this.__leavelist.length;i<iz;++i){result.push(this.__leavelist[i].node)}return result};Controller.prototype.current=function current(){return this.__current.node};Controller.prototype.__execute=function __execute(callback,element){var previous,result;result=undefined;previous=this.__current;this.__current=element;this.__state=null;if(callback){result=callback.call(this,element.node,this.__leavelist[this.__leavelist.length-1].node)}this.__current=previous;return result};Controller.prototype.notify=function notify(flag){this.__state=flag};Controller.prototype.skip=function(){this.notify(SKIP)};Controller.prototype['break']=function(){this.notify(BREAK)};Controller.prototype.remove=function(){this.notify(REMOVE)};Controller.prototype.__initialize=function(root,visitor){this.visitor=visitor;this.root=root;this.__worklist=[];this.__leavelist=[];this.__current=null;this.__state=null;this.__fallback=null;if(visitor.fallback==='iteration'){this.__fallback=Object.keys}else if(typeof visitor.fallback==='function'){this.__fallback=visitor.fallback}this.__keys=VisitorKeys;if(visitor.keys){this.__keys=Object.assign(Object.create(this.__keys),visitor.keys)}};function isNode(node){if(node==null){return false}return typeof node==='object'&&typeof node.type==='string'}function isProperty(nodeType,key){return(nodeType===Syntax.ObjectExpression||nodeType===Syntax.ObjectPattern)&&'properties'===key}function candidateExistsInLeaveList(leavelist,candidate){for(var i=leavelist.length-1;i>=0;--i){if(leavelist[i].node===candidate){return true}}return false}Controller.prototype.traverse=function traverse(root,visitor){var worklist,leavelist,element,node,nodeType,ret,key,current,current2,candidates,candidate,sentinel;this.__initialize(root,visitor);sentinel={};worklist=this.__worklist;leavelist=this.__leavelist;worklist.push(new Element(root,null,null,null));leavelist.push(new Element(null,null,null,null));while(worklist.length){element=worklist.pop();if(element===sentinel){element=leavelist.pop();ret=this.__execute(visitor.leave,element);if(this.__state===BREAK||ret===BREAK){return}continue}if(element.node){ret=this.__execute(visitor.enter,element);if(this.__state===BREAK||ret===BREAK){return}worklist.push(sentinel);leavelist.push(element);if(this.__state===SKIP||ret===SKIP){continue}node=element.node;nodeType=node.type||element.wrap;candidates=this.__keys[nodeType];if(!candidates){if(this.__fallback){candidates=this.__fallback(node)}else{throw new Error('Unknown node type '+nodeType+'.')}}current=candidates.length;while((current-=1)>=0){key=candidates[current];candidate=node[key];if(!candidate){continue}if(Array.isArray(candidate)){current2=candidate.length;while((current2-=1)>=0){if(!candidate[current2]){continue}if(candidateExistsInLeaveList(leavelist,candidate[current2])){continue}if(isProperty(nodeType,candidates[current])){element=new Element(candidate[current2],[key,current2],'Property',null)}else if(isNode(candidate[current2])){element=new Element(candidate[current2],[key,current2],null,null)}else{continue}worklist.push(element)}}else if(isNode(candidate)){if(candidateExistsInLeaveList(leavelist,candidate)){continue}worklist.push(new Element(candidate,key,null,null))}}}}};Controller.prototype.replace=function replace(root,visitor){var worklist,leavelist,node,nodeType,target,element,current,current2,candidates,candidate,sentinel,outer,key;function removeElem(element){var i,key,nextElem,parent;if(element.ref.remove()){key=element.ref.key;parent=element.ref.parent;i=worklist.length;while(i--){nextElem=worklist[i];if(nextElem.ref&&nextElem.ref.parent===parent){if(nextElem.ref.key<key){break}--nextElem.ref.key}}}}this.__initialize(root,visitor);sentinel={};worklist=this.__worklist;leavelist=this.__leavelist;outer={root:root};element=new Element(root,null,null,new Reference(outer,'root'));worklist.push(element);leavelist.push(element);while(worklist.length){element=worklist.pop();if(element===sentinel){element=leavelist.pop();target=this.__execute(visitor.leave,element);if(target!==undefined&&target!==BREAK&&target!==SKIP&&target!==REMOVE){element.ref.replace(target)}if(this.__state===REMOVE||target===REMOVE){removeElem(element)}if(this.__state===BREAK||target===BREAK){return outer.root}continue}target=this.__execute(visitor.enter,element);if(target!==undefined&&target!==BREAK&&target!==SKIP&&target!==REMOVE){element.ref.replace(target);element.node=target}if(this.__state===REMOVE||target===REMOVE){removeElem(element);element.node=null}if(this.__state===BREAK||target===BREAK){return outer.root}node=element.node;if(!node){continue}worklist.push(sentinel);leavelist.push(element);if(this.__state===SKIP||target===SKIP){continue}nodeType=node.type||element.wrap;candidates=this.__keys[nodeType];if(!candidates){if(this.__fallback){candidates=this.__fallback(node)}else{throw new Error('Unknown node type '+nodeType+'.')}}current=candidates.length;while((current-=1)>=0){key=candidates[current];candidate=node[key];if(!candidate){continue}if(Array.isArray(candidate)){current2=candidate.length;while((current2-=1)>=0){if(!candidate[current2]){continue}if(isProperty(nodeType,candidates[current])){element=new Element(candidate[current2],[key,current2],'Property',new Reference(candidate,current2))}else if(isNode(candidate[current2])){element=new Element(candidate[current2],[key,current2],null,new Reference(candidate,current2))}else{continue}worklist.push(element)}}else if(isNode(candidate)){worklist.push(new Element(candidate,key,null,new Reference(node,key)))}}}return outer.root};function traverse(root,visitor){var controller=new Controller;return controller.traverse(root,visitor)}function replace(root,visitor){var controller=new Controller;return controller.replace(root,visitor)}function extendCommentRange(comment,tokens){var target;target=upperBound(tokens,function search(token){return token.range[0]>comment.range[0]});comment.extendedRange=[comment.range[0],comment.range[1]];if(target!==tokens.length){comment.extendedRange[1]=tokens[target].range[0]}target-=1;if(target>=0){comment.extendedRange[0]=tokens[target].range[1]}return comment}function attachComments(tree,providedComments,tokens){var comments=[],comment,len,i,cursor;if(!tree.range){throw new Error('attachComments needs range information')}if(!tokens.length){if(providedComments.length){for(i=0,len=providedComments.length;i<len;i+=1){comment=deepCopy(providedComments[i]);comment.extendedRange=[0,tree.range[0]];comments.push(comment)}tree.leadingComments=comments}return tree}for(i=0,len=providedComments.length;i<len;i+=1){comments.push(extendCommentRange(deepCopy(providedComments[i]),tokens))}cursor=0;traverse(tree,{enter:function(node){var comment;while(cursor<comments.length){comment=comments[cursor];if(comment.extendedRange[1]>node.range[0]){break}if(comment.extendedRange[1]===node.range[0]){if(!node.leadingComments){node.leadingComments=[]}node.leadingComments.push(comment);comments.splice(cursor,1)}else{cursor+=1}}if(cursor===comments.length){return VisitorOption.Break}if(comments[cursor].extendedRange[0]>node.range[1]){return VisitorOption.Skip}}});cursor=0;traverse(tree,{leave:function(node){var comment;while(cursor<comments.length){comment=comments[cursor];if(node.range[1]<comment.extendedRange[0]){break}if(node.range[1]===comment.extendedRange[0]){if(!node.trailingComments){node.trailingComments=[]}node.trailingComments.push(comment);comments.splice(cursor,1)}else{cursor+=1}}if(cursor===comments.length){return VisitorOption.Break}if(comments[cursor].extendedRange[0]>node.range[1]){return VisitorOption.Skip}}});return tree}exports.Syntax=Syntax;exports.traverse=traverse;exports.replace=replace;exports.attachComments=attachComments;exports.VisitorKeys=VisitorKeys;exports.VisitorOption=VisitorOption;exports.Controller=Controller;exports.cloneEnvironment=function(){return clone({})};return exports})(exports);