Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

babel-plugin-catch-logger

Package Overview
Dependencies
Maintainers
1
Versions
10
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

babel-plugin-catch-logger - npm Package Compare versions

Comparing version 0.1.6 to 0.1.7

58

lib/arguments.js

@@ -1,3 +0,55 @@

"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getArgs=getArgs;var types=_interopRequireWildcard(require("@babel/types")),_constants=require("./constants");function _getRequireWildcardCache(){if("function"!=typeof WeakMap)return null;var cache=new WeakMap;return _getRequireWildcardCache=function(){return cache},cache}function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache();if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if(Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}function getSceneInfo(knownData){const sceneInfo=`[${knownData.source}:${knownData.line}:${knownData.column}]`;return types.stringLiteral(sceneInfo)}function getFunctionArguments(path){const _path$node=path.node,_path$node2=void 0===_path$node?{}:_path$node,_path$node2$params=_path$node2.params,params=void 0===_path$node2$params?[]:_path$node2$params;return params.filter(param=>types.isIdentifier(param)).map(param=>param.name)}function getFunction(path,_,knownData){const argumentsToAdd=[],isCatchClause=types.isCatchClause(path);isCatchClause?(!path.node.param&&(path.node.param=types.identifier("e")),argumentsToAdd.push(path.node.param.name)):knownData.name===_constants.MEMBER_EXPRESSION_CATCH&&argumentsToAdd.push(...getFunctionArguments(path));const identifierArgs=argumentsToAdd.map(identifierName=>types.identifier(identifierName));return identifierArgs}function getArgs(path,state,knownData){// ignore for now:
// const sceneInfo = getSceneInfo(knownData)
const fnArgs=getFunction(path,state,knownData);return[...fnArgs]}
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getArgs = getArgs;
var types = _interopRequireWildcard(require("@babel/types"));
var _constants = require("./constants");
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function getSceneInfo(knownData) {
const sceneInfo = `[${knownData.source}:${knownData.line}:${knownData.column}]`;
return types.stringLiteral(sceneInfo);
}
function getFunctionArguments(path) {
const _path$node = path.node,
_path$node2 = _path$node === void 0 ? {} : _path$node,
_path$node2$params = _path$node2.params,
params = _path$node2$params === void 0 ? [] : _path$node2$params;
return params.filter(param => types.isIdentifier(param)).map(param => param.name);
}
function getFunction(path, _, knownData) {
const argumentsToAdd = [];
const isCatchClause = types.isCatchClause(path);
if (isCatchClause) {
if (!path.node.param) {
path.node.param = types.identifier('e');
}
argumentsToAdd.push(path.node.param.name);
} else if (knownData.name === _constants.MEMBER_EXPRESSION_CATCH) {
argumentsToAdd.push(...getFunctionArguments(path));
}
const identifierArgs = argumentsToAdd.map(identifierName => {
return types.identifier(identifierName);
});
return identifierArgs;
}
function getArgs(path, state, knownData) {
// ignore for now:
// const sceneInfo = getSceneInfo(knownData)
const fnArgs = getFunction(path, state, knownData);
return [...fnArgs];
}

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

"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.LOGGER_API=exports.MEMBER_EXPRESSION_CATCH=void 0;const MEMBER_EXPRESSION_CATCH="memberExpressionCatch";exports.MEMBER_EXPRESSION_CATCH="memberExpressionCatch";const LOGGER_API="console";exports.LOGGER_API="console";
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.LOGGER_API = exports.MEMBER_EXPRESSION_CATCH = void 0;
const MEMBER_EXPRESSION_CATCH = 'memberExpressionCatch';
exports.MEMBER_EXPRESSION_CATCH = MEMBER_EXPRESSION_CATCH;
const LOGGER_API = 'console';
exports.LOGGER_API = LOGGER_API;

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

"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _helperPluginUtils=require("@babel/helper-plugin-utils"),_setup=require("./setup"),_visitors=require("./visitors");function babelPluginAutoReportError(api){return api.assertVersion(7),{name:"babel-plugin-catch-logger",post:_setup.post,pre:_setup.pre,visitor:{CatchClause:_visitors.CatchClause,Program:{exit:_visitors.Program},CallExpression:_visitors.CallExpression}}}var _default=(0,_helperPluginUtils.declare)(babelPluginAutoReportError);exports.default=_default;
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _helperPluginUtils = require("@babel/helper-plugin-utils");
var _setup = require("./setup");
var _visitors = require("./visitors");
function babelPluginAutoReportError(api) {
api.assertVersion(7);
return {
name: 'babel-plugin-catch-logger',
post: _setup.post,
pre: _setup.pre,
visitor: {
CatchClause: _visitors.CatchClause,
Program: {
exit: _visitors.Program
},
CallExpression: _visitors.CallExpression
}
};
}
var _default = (0, _helperPluginUtils.declare)(babelPluginAutoReportError);
exports.default = _default;

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

"use strict";var _constants=require("./constants");Object.defineProperty(exports,"__esModule",{value:!0}),exports.getOptions=getOptions,exports.prepare=prepare;function getMatcher(matcher,matcherName,defaultMatcher=[]){let matcherForRegExp;if(matcher){const matcherAsArray=Array.isArray(matcher);if(matcherAsArray){const validMatcher=matcher.filter(Boolean).map(stringMatcher=>`(${stringMatcher})`);matcherForRegExp=validMatcher.join("|")}else if("string"==typeof matcher)matcherForRegExp=matcher;else throw new Error(`[babel-plugin-catch-logger] '${matcherName}' can be string or array with strings`)}else matcherForRegExp=defaultMatcher.map(stringMatcher=>`(${stringMatcher})`).join("|");return new RegExp(matcherForRegExp)}function getSourceMatcher(){return[".*js(x)?$"]}function getSourceExcludeMatcher(){return["__fixtures__","__mocks__","__tests__","__snapshots__","node_modules"]}function getOutput(settings){const options={argsAsObject:!1,type:"simple"};if(settings&&"object"==typeof settings){const useType=settings.type,isValidType=["simple","object"].includes(useType);isValidType&&(options.type=useType,options.argsAsObject=!0===settings.argsAsObject,"object"===useType&&(options.source=settings.source||"source",options.name=settings.name||"name",options.args=settings.args||"args"))}return options}function getOptions(loggingData){const options={},_ref=loggingData||{},name=_ref.name,source=_ref.source,methodName=_ref.methodName;return options.name=name||_constants.LOGGER_API,options.source=options.name===_constants.LOGGER_API?"":source||"",options.methodName=methodName||"log",{...loggingData,...options}}function prepare(receivedOptions){const options={sourceMatcher:getMatcher(receivedOptions.sourceMatcher,"sourceMatcher",getSourceMatcher()),sourceExcludeMatcher:getMatcher(receivedOptions.sourceExcludeMatcher,"sourceExcludeMatcher",getSourceExcludeMatcher()),output:getOutput(receivedOptions.output)};return{...options,...getOptions(receivedOptions)}}
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getOptions = getOptions;
exports.prepare = prepare;
var _constants = require("./constants");
function getMatcher(matcher, matcherName, defaultMatcher = []) {
let matcherForRegExp;
if (matcher) {
const matcherAsArray = Array.isArray(matcher);
if (matcherAsArray) {
const validMatcher = matcher.filter(Boolean).map(stringMatcher => `(${stringMatcher})`);
matcherForRegExp = validMatcher.join('|');
} else if (typeof matcher === 'string') {
matcherForRegExp = matcher;
} else {
throw new Error(`[babel-plugin-catch-logger] '${matcherName}' can be string or array with strings`);
}
} else {
matcherForRegExp = defaultMatcher.map(stringMatcher => `(${stringMatcher})`).join('|');
}
return new RegExp(matcherForRegExp);
}
function getSourceMatcher() {
return ['.*js(x)?$'];
}
function getSourceExcludeMatcher() {
return ['__fixtures__', '__mocks__', '__tests__', '__snapshots__', 'node_modules'];
}
function getOutput(settings) {
const validTypes = ['simple', 'object'];
const options = {
argsAsObject: false,
type: 'simple'
};
if (settings && typeof settings === 'object') {
const useType = settings.type;
const isValidType = validTypes.includes(useType);
if (isValidType) {
options.type = useType;
options.argsAsObject = settings.argsAsObject === true;
if (useType === 'object') {
options.source = settings.source || 'source';
options.name = settings.name || 'name';
options.args = settings.args || 'args';
}
}
}
return options;
}
function getOptions(loggingData) {
const options = {};
const _ref = loggingData || {},
name = _ref.name,
source = _ref.source,
methodName = _ref.methodName;
options.name = name || _constants.LOGGER_API;
if (options.name === _constants.LOGGER_API) {
options.source = '';
} else {
options.source = source || '';
}
options.methodName = methodName || 'log';
return { ...loggingData,
...options
};
}
function prepare(receivedOptions) {
const options = {};
options.sourceMatcher = getMatcher(receivedOptions.sourceMatcher, 'sourceMatcher', getSourceMatcher());
options.sourceExcludeMatcher = getMatcher(receivedOptions.sourceExcludeMatcher, 'sourceExcludeMatcher', getSourceExcludeMatcher());
options.output = getOutput(receivedOptions.output);
return { ...options,
...getOptions(receivedOptions)
};
}

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

"use strict";var _options=require("./options");Object.defineProperty(exports,"__esModule",{value:!0}),exports.pre=pre,exports.post=post;function pre(){this.babelPluginLoggerSettings=(0,_options.prepare)(this.opts)}function post(){this.babelPluginLoggerSettings=void 0}
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.pre = pre;
exports.post = post;
var _options = require("./options");
function pre() {
this.babelPluginLoggerSettings = (0, _options.prepare)(this.opts);
}
function post() {
this.babelPluginLoggerSettings = undefined;
}

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

"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getSrc=getSrc;function getSrc(state){const _state$file$opts=state.file.opts,parserOpts=_state$file$opts.parserOpts,root=_state$file$opts.root,sourceFileName=_state$file$opts.sourceFileName,sourceMapTarget=_state$file$opts.sourceMapTarget;let sourceFile=sourceMapTarget||sourceFileName||parserOpts&&(parserOpts.sourceMapTarget||parserOpts.sourceFileName);return sourceFile&&root&&(sourceFile=sourceFile.replace(root,"")),sourceFile||""}
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getSrc = getSrc;
function getSrc(state) {
const _state$file$opts = state.file.opts,
parserOpts = _state$file$opts.parserOpts,
root = _state$file$opts.root,
sourceFileName = _state$file$opts.sourceFileName,
sourceMapTarget = _state$file$opts.sourceMapTarget;
let sourceFile = sourceMapTarget || sourceFileName || parserOpts && (parserOpts.sourceMapTarget || parserOpts.sourceFileName);
if (sourceFile && root) {
sourceFile = sourceFile.replace(root, '');
}
return sourceFile || '';
}

@@ -1,9 +0,25 @@

"use strict";var _babelTemplate=_interopRequireDefault(require("babel-template"));Object.defineProperty(exports,"__esModule",{value:!0}),exports.returnStatement=exports.promiseCatchEnhancer=exports.promiseCatchStatement=void 0;function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}const promiseCatchStatement=(0,_babelTemplate.default)(`
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.returnStatement = exports.promiseCatchEnhancer = exports.promiseCatchStatement = void 0;
var _babelTemplate = _interopRequireDefault(require("babel-template"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const promiseCatchStatement = (0, _babelTemplate.default)(`
BODY.catch(function(ERR){
HANDLER(ERR)
})`);exports.promiseCatchStatement=promiseCatchStatement;const promiseCatchEnhancer=(0,_babelTemplate.default)(`{
})`);
exports.promiseCatchStatement = promiseCatchStatement;
const promiseCatchEnhancer = (0, _babelTemplate.default)(`{
HANDLER(ARGUMENTS)
BODY
}`);exports.promiseCatchEnhancer=promiseCatchEnhancer;const returnStatement=(0,_babelTemplate.default)(`{
}`);
exports.promiseCatchEnhancer = promiseCatchEnhancer;
const returnStatement = (0, _babelTemplate.default)(`{
return STATEMENT
}`);exports.returnStatement=returnStatement;
}`);
exports.returnStatement = returnStatement;

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

"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getLoggerName=getLoggerName,exports.getLoggerSource=getLoggerSource,exports.isValidPathAndState=isValidPathAndState,exports.addLogger=addLogger;var types=_interopRequireWildcard(require("@babel/types")),_arguments=require("./arguments"),_sourceFile=require("./source-file"),_constants=require("./constants");function _getRequireWildcardCache(){if("function"!=typeof WeakMap)return null;var cache=new WeakMap;return _getRequireWildcardCache=function(){return cache},cache}function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache();if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if(Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}function hasLogging(bodyNode,state){const isExpressionStatement=types.isExpressionStatement(bodyNode);if(!isExpressionStatement)return!1;const expression=bodyNode.expression,isCallExpression=types.isCallExpression(expression);if(!isCallExpression)return!1;const callee=expression.callee,isMemberExpression=types.isMemberExpression(callee);if(!isMemberExpression)return!1;const calleeObject=callee.object,isIdentifier=types.isIdentifier(calleeObject);if(!isIdentifier)return!1;const loggerName=getLoggerName(state);return calleeObject.name===loggerName}function canBeAdded(path,state){const isBlockStatement=types.isBlockStatement(path);if(!isBlockStatement)return!1;const blockBody=path.node.body,foundLogger=blockBody.find(bodyNode=>hasLogging(bodyNode,state));return!foundLogger}function getPathForInsert(path){const insertPath=path.get("body"),isBlockStatement=types.isBlockStatement(insertPath);if(isBlockStatement)return insertPath;const isArrowFunctionExpression=types.isArrowFunctionExpression(insertPath);return isArrowFunctionExpression?getPathForInsert(insertPath):void 0}function getLocation(path){const _ref=path.node||{},_ref$loc=_ref.loc,_ref$loc2=void 0===_ref$loc?{}:_ref$loc,_ref$loc2$start=_ref$loc2.start,_ref$loc2$start2=void 0===_ref$loc2$start?{}:_ref$loc2$start,column=_ref$loc2$start2.column,line=_ref$loc2$start2.line;return{column,line}}function getName(path){var _NumberisInteger=Number.isInteger;const isCatchClause=types.isCatchClause(path);if(isCatchClause)return"catchClause";const _path$container=path.container,container=void 0===_path$container?{}:_path$container,_path$node=path.node,node=void 0===_path$node?{}:_path$node,_path$parent=path.parent,parent=void 0===_path$parent?{}:_path$parent;if(node.id)return node.id.name;if(container.id)return container.id.name;if(parent.left&&parent.left.property)return parent.left.property.name;if(parent.left&&parent.left.name)return parent.left.name;const _node$key=node.key,nodeKey=void 0===_node$key?{}:_node$key;if(nodeKey&&nodeKey.name)return nodeKey.name;const _parent$key=parent.key,parentKey=void 0===_parent$key?{}:_parent$key;if(parentKey&&parentKey.name)return parentKey.name;const _parent$callee=parent.callee,_parent$callee2=void 0===_parent$callee?{}:_parent$callee,property=_parent$callee2.property;return property&&"catch"===property.name?_constants.MEMBER_EXPRESSION_CATCH:path.inList&&_NumberisInteger(path.key)?`array-item-${path.key}`:void 0}function insertLogging(path,insertPath,state,partialData){const source=(0,_sourceFile.getSrc)(state),knownData={column:partialData.column,line:partialData.line,name:partialData.name,source},methodName=state.babelPluginLoggerSettings.methodName;methodName&&insertPath.unshiftContainer("body",types.expressionStatement(types.callExpression(types.memberExpression(types.identifier(getLoggerName(state)),types.identifier(methodName)),(0,_arguments.getArgs)(path,state,knownData))))}function getLoggerName(state){return state.babelPluginLoggerSettings.name}function getLoggerSource(state){return state.babelPluginLoggerSettings.source}function isValidPathAndState(path,state){if(path.node._generated)return!1;const filename=state.file.opts.filename,_state$babelPluginLog=state.babelPluginLoggerSettings,sourceMatcher=_state$babelPluginLog.sourceMatcher,sourceExcludeMatcher=_state$babelPluginLog.sourceExcludeMatcher,allowFromSource=sourceMatcher.test(filename);if(!allowFromSource)return!1;const excludeFromSource=sourceExcludeMatcher.test(filename);return!excludeFromSource}function addLogger(path,state){const name=getName(path);if(!name)return!1;const insertPath=getPathForInsert(path);if(!insertPath)return!1;const _getLocation=getLocation(insertPath),column=_getLocation.column,line=_getLocation.line;if(!(column!==void 0&&line!==void 0))return!1;const loggerCanBeAdded=canBeAdded(insertPath,state);return!!loggerCanBeAdded&&(insertLogging(path,insertPath,state,{column,line,name}),state.caught=!0,!0)}
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getLoggerName = getLoggerName;
exports.getLoggerSource = getLoggerSource;
exports.isValidPathAndState = isValidPathAndState;
exports.addLogger = addLogger;
var types = _interopRequireWildcard(require("@babel/types"));
var _arguments = require("./arguments");
var _sourceFile = require("./source-file");
var _constants = require("./constants");
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function hasLogging(bodyNode, state) {
const isExpressionStatement = types.isExpressionStatement(bodyNode);
if (!isExpressionStatement) {
return false;
}
const expression = bodyNode.expression;
const isCallExpression = types.isCallExpression(expression);
if (!isCallExpression) {
return false;
}
const callee = expression.callee;
const isMemberExpression = types.isMemberExpression(callee);
if (!isMemberExpression) {
return false;
}
const calleeObject = callee.object;
const isIdentifier = types.isIdentifier(calleeObject);
if (!isIdentifier) {
return false;
}
const loggerName = getLoggerName(state);
return calleeObject.name === loggerName;
}
function canBeAdded(path, state) {
const isBlockStatement = types.isBlockStatement(path);
if (!isBlockStatement) {
return false;
}
const blockBody = path.node.body;
const foundLogger = blockBody.find(bodyNode => hasLogging(bodyNode, state));
return !foundLogger;
}
function getPathForInsert(path) {
const insertPath = path.get('body');
const isBlockStatement = types.isBlockStatement(insertPath);
if (isBlockStatement) {
return insertPath;
}
const isArrowFunctionExpression = types.isArrowFunctionExpression(insertPath);
if (isArrowFunctionExpression) {
return getPathForInsert(insertPath);
}
return undefined;
}
function getLocation(path) {
const _ref = path.node || {},
_ref$loc = _ref.loc,
_ref$loc2 = _ref$loc === void 0 ? {} : _ref$loc,
_ref$loc2$start = _ref$loc2.start,
_ref$loc2$start2 = _ref$loc2$start === void 0 ? {} : _ref$loc2$start,
column = _ref$loc2$start2.column,
line = _ref$loc2$start2.line;
return {
column,
line
};
}
function getName(path) {
const isCatchClause = types.isCatchClause(path);
if (isCatchClause) {
return 'catchClause';
}
const _path$container = path.container,
container = _path$container === void 0 ? {} : _path$container,
_path$node = path.node,
node = _path$node === void 0 ? {} : _path$node,
_path$parent = path.parent,
parent = _path$parent === void 0 ? {} : _path$parent;
if (node.id) {
return node.id.name;
}
if (container.id) {
return container.id.name;
}
if (parent.left && parent.left.property) {
return parent.left.property.name;
}
if (parent.left && parent.left.name) {
return parent.left.name;
}
const _node$key = node.key,
nodeKey = _node$key === void 0 ? {} : _node$key;
if (nodeKey && nodeKey.name) {
return nodeKey.name;
}
const _parent$key = parent.key,
parentKey = _parent$key === void 0 ? {} : _parent$key;
if (parentKey && parentKey.name) {
return parentKey.name;
}
const _parent$callee = parent.callee,
_parent$callee2 = _parent$callee === void 0 ? {} : _parent$callee,
property = _parent$callee2.property;
if (property && property.name === 'catch') {
return _constants.MEMBER_EXPRESSION_CATCH;
}
if (path.inList && Number.isInteger(path.key)) {
return `array-item-${path.key}`;
}
return undefined;
}
function insertLogging(path, insertPath, state, partialData) {
const source = (0, _sourceFile.getSrc)(state);
const knownData = {
column: partialData.column,
line: partialData.line,
name: partialData.name,
source
};
const methodName = state.babelPluginLoggerSettings.methodName;
if (methodName) {
insertPath.unshiftContainer('body', types.expressionStatement(types.callExpression(types.memberExpression(types.identifier(getLoggerName(state)), types.identifier(methodName)), (0, _arguments.getArgs)(path, state, knownData))));
}
}
function getLoggerName(state) {
return state.babelPluginLoggerSettings.name;
}
function getLoggerSource(state) {
return state.babelPluginLoggerSettings.source;
}
function isValidPathAndState(path, state) {
if (path.node._generated) {
return false;
}
const filename = state.file.opts.filename;
const _state$babelPluginLog = state.babelPluginLoggerSettings,
sourceMatcher = _state$babelPluginLog.sourceMatcher,
sourceExcludeMatcher = _state$babelPluginLog.sourceExcludeMatcher;
const allowFromSource = sourceMatcher.test(filename);
if (!allowFromSource) {
return false;
}
const excludeFromSource = sourceExcludeMatcher.test(filename);
return !excludeFromSource;
}
function addLogger(path, state) {
const name = getName(path);
if (!name) {
return false;
}
const insertPath = getPathForInsert(path);
if (!insertPath) {
return false;
}
const _getLocation = getLocation(insertPath),
column = _getLocation.column,
line = _getLocation.line;
const sourceCode = column !== undefined && line !== undefined;
if (!sourceCode) {
return false;
}
const loggerCanBeAdded = canBeAdded(insertPath, state);
if (loggerCanBeAdded) {
insertLogging(path, insertPath, state, {
column,
line,
name
});
state.caught = true;
return true;
}
return false;
}

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

"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Program=Program,exports.CatchClause=CatchClause,exports.CallExpression=CallExpression;var types=_interopRequireWildcard(require("@babel/types")),_utils=require("./utils"),_template=require("./template"),_constants=require("./constants");function _getRequireWildcardCache(){if("function"!=typeof WeakMap)return null;var cache=new WeakMap;return _getRequireWildcardCache=function(){return cache},cache}function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;if(null===obj||"object"!=typeof obj&&"function"!=typeof obj)return{default:obj};var cache=_getRequireWildcardCache();if(cache&&cache.has(obj))return cache.get(obj);var newObj={},hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj)if(Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;desc&&(desc.get||desc.set)?Object.defineProperty(newObj,key,desc):newObj[key]=obj[key]}return newObj.default=obj,cache&&cache.set(obj,newObj),newObj}const expressionCache=new Set;function Program(path,state){if(state.caught){const validPathAndState=(0,_utils.isValidPathAndState)(path,state);if(validPathAndState){const loggerName=(0,_utils.getLoggerName)(state),isDefaultLoggerName=loggerName===_constants.LOGGER_API,loggerWasImported=!!path.scope.bindings[loggerName];isDefaultLoggerName||loggerWasImported||path.unshiftContainer("body",types.importDeclaration([state.babelPluginLoggerSettings.namespaced?types.importNamespaceSpecifier(types.identifier(loggerName)):types.ImportDefaultSpecifier(types.identifier(loggerName))],types.stringLiteral((0,_utils.getLoggerSource)(state))))}}}function CatchClause(path,state){const validPathAndState=(0,_utils.isValidPathAndState)(path,state);validPathAndState&&(0,_utils.addLogger)(path,state)}function getCalleeName(callee){return callee?callee.computed?callee.property.value:(callee.property||{}).name:void 0}function findOutmostCallExp(path){let depth=0;const p=path.findParent(p=>(depth++,types.isCallExpression(p)||2<depth));return 2==depth&&p?.isCallExpression()?findOutmostCallExp(p):path}function CallExpression(path,state){if(path.node.loc&&state.babelPluginLoggerSettings.catchPromise){let methodName=getCalleeName(path.node.callee);if("then"===methodName||"catch"===methodName){state.caught=!0;const callExpressionOutermost=findOutmostCallExp(path);if(expressionCache.has(callExpressionOutermost.node))return;const outermostName=getCalleeName(callExpressionOutermost.node.callee);if("catch"===outermostName){const catchFn=callExpressionOutermost.node.arguments[0];if(!catchFn)return;let argName;catchFn.params.length?argName=types.identifier(catchFn.params[0].name):(argName=path.scope.generateUidIdentifier("e"),catchFn.params.push(argName));let fnBody=catchFn.body.body;fnBody||(callExpressionOutermost.get("arguments.0.body").replaceWith((0,_template.returnStatement)({STATEMENT:catchFn.body})),fnBody=catchFn.body.body),callExpressionOutermost.get("arguments.0.body").replaceWith((0,_template.promiseCatchEnhancer)({BODY:fnBody,ARGUMENTS:argName,HANDLER:types.memberExpression(types.identifier(state.babelPluginLoggerSettings.name),types.identifier(state.babelPluginLoggerSettings.methodName))})),expressionCache.add(callExpressionOutermost.node)}else{const errorVariableName=path.scope.generateUidIdentifier("e");callExpressionOutermost.replaceWith((0,_template.promiseCatchStatement)({BODY:callExpressionOutermost.node,ERR:errorVariableName,HANDLER:types.memberExpression(types.identifier(state.babelPluginLoggerSettings.name),types.identifier(state.babelPluginLoggerSettings.methodName))})),expressionCache.add(callExpressionOutermost.node)}}}}
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Program = Program;
exports.CatchClause = CatchClause;
exports.CallExpression = CallExpression;
var types = _interopRequireWildcard(require("@babel/types"));
var _utils = require("./utils");
var _template = require("./template");
var _constants = require("./constants");
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
const expressionCache = new Set();
function Program(path, state) {
if (!state.caught) return;
const validPathAndState = (0, _utils.isValidPathAndState)(path, state);
if (validPathAndState) {
const loggerName = (0, _utils.getLoggerName)(state);
const isDefaultLoggerName = loggerName === _constants.LOGGER_API;
const loggerWasImported = Boolean(path.scope.bindings[loggerName]);
if (!isDefaultLoggerName && !loggerWasImported) {
path.unshiftContainer('body', types.importDeclaration([state.babelPluginLoggerSettings.namespaced ? types.importNamespaceSpecifier(types.identifier(loggerName)) : types.ImportDefaultSpecifier(types.identifier(loggerName))], types.stringLiteral((0, _utils.getLoggerSource)(state))));
}
}
}
function CatchClause(path, state) {
const validPathAndState = (0, _utils.isValidPathAndState)(path, state);
if (validPathAndState) {
(0, _utils.addLogger)(path, state);
}
}
function getCalleeName(callee) {
if (!callee) return;
if (callee.computed) {
return callee.property.value;
}
return (callee.property || {}).name;
}
function findOutmostCallExp(path) {
let depth = 0;
const p = path.findParent(p => {
depth++;
return types.isCallExpression(p) || depth > 2;
});
if (depth === 2 && p?.isCallExpression()) {
return findOutmostCallExp(p);
}
return path;
}
function CallExpression(path, state) {
if (!path.node.loc || !state.babelPluginLoggerSettings.catchPromise) return;
let methodName = getCalleeName(path.node.callee);
if (methodName === 'then' || methodName === 'catch') {
state.caught = true;
const callExpressionOutermost = findOutmostCallExp(path);
if (expressionCache.has(callExpressionOutermost.node)) return;
const outermostName = getCalleeName(callExpressionOutermost.node.callee);
if (outermostName === 'catch') {
const catchFn = callExpressionOutermost.node.arguments[0];
if (!catchFn) return;
let argName;
if (!catchFn.params.length) {
argName = path.scope.generateUidIdentifier('e');
catchFn.params.push(argName);
} else {
argName = types.identifier(catchFn.params[0].name);
}
let fnBody = catchFn.body.body;
if (!fnBody) {
callExpressionOutermost.get('arguments.0.body').replaceWith((0, _template.returnStatement)({
STATEMENT: catchFn.body
}));
fnBody = catchFn.body.body;
}
callExpressionOutermost.get('arguments.0.body').replaceWith((0, _template.promiseCatchEnhancer)({
BODY: fnBody,
ARGUMENTS: argName,
HANDLER: types.memberExpression(types.identifier(state.babelPluginLoggerSettings.name), types.identifier(state.babelPluginLoggerSettings.methodName))
}));
expressionCache.add(callExpressionOutermost.node);
} else {
const errorVariableName = path.scope.generateUidIdentifier('e');
callExpressionOutermost.replaceWith((0, _template.promiseCatchStatement)({
BODY: callExpressionOutermost.node,
ERR: errorVariableName,
HANDLER: types.memberExpression(types.identifier(state.babelPluginLoggerSettings.name), types.identifier(state.babelPluginLoggerSettings.methodName))
}));
expressionCache.add(callExpressionOutermost.node);
}
}
}

2

package.json
{
"name": "babel-plugin-catch-logger",
"version": "0.1.6",
"version": "0.1.7",
"description": "A babel plugin that automatically reports errors in your program",

@@ -5,0 +5,0 @@ "main": "lib/index.js",

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc