Skip to content

Instantly share code, notes, and snippets.

@bholloway
Created November 7, 2019 01:46
Show Gist options
  • Save bholloway/51c31c04c027d6add32a1b4b549e6b45 to your computer and use it in GitHub Desktop.
Save bholloway/51c31c04c027d6add32a1b4b549e6b45 to your computer and use it in GitHub Desktop.
babel plugin to instrument promises with performance marks
const { relative } = require('path');
module.exports = babel => {
const {
types: {
stringLiteral,
callExpression,
identifier,
isMemberExpression,
isCallExpression,
isIdentifier,
},
} = babel;
return {
name: 'babel-plugin-instrument-promises',
visitor: {
CallExpression(path, state) {
try {
const { node } = path;
if (isMemberExpression(node.callee)) {
const { name } = node.callee.property;
const decorator = state.opts[name];
const isRelevant =
['then', 'catch', 'finally'].includes(name) &&
typeof decorator === 'string' &&
node.arguments.length === 1 &&
node.arguments[0].loc;
if (isRelevant) {
const [arg] = node.arguments;
const isAlreadyInstrumented =
isCallExpression(arg) &&
isIdentifier(arg.callee) &&
arg.callee.name === decorator;
if (!isAlreadyInstrumented) {
const { sourceFileName, root } = state.file.opts;
const { line, column } = arg.loc.start;
const source = relative(root, sourceFileName);
node.arguments = [
callExpression(identifier(decorator), [
stringLiteral(`${source}:${line}:${column}`),
arg,
]),
];
}
}
}
} catch (error) {
console.error(error);
}
},
},
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment