All files logging-espree.js

92.1% Statements 35/38
91.66% Branches 11/12
100% Functions 4/4
92.1% Lines 35/38

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 401x 1x 1x 1x 1x 1x 4x 4x 4x       4x 4x 4x 1x 1x 4x 4x 4x 212x 212x 212x 9x 9x 212x 4x 4x 4x 1x 9x 9x 9x 9x 9x 9x 9x 9x    
import * as escodegen from "escodegen";
import * as espree from "espree";
import * as estraverse from "estraverse";
import * as fs from "fs/promises";
 
export async function transpile(inputFile, outputFile) {
  let input = await fs.readFile(inputFile, 'utf-8');
  const output = addLogging(input);
  if (outputFile === undefined) {
    console.log(output);
    return;
  }
  console.log(`Output in file: ${outputFile}`)
  await fs.writeFile(outputFile, output);
}
 
export function addLogging(code) {
  const ast = espree.parse(code, { ecmaVersion: 12, loc: true });
  estraverse.traverse(ast, {
    enter: function(node, parent) {
      if (node.type === 'FunctionDeclaration' ||
        node.type === 'FunctionExpression' ||
        node.type === 'ArrowFunctionExpression') {
        addBeforeCode(node);
      }
    }
  });
  return escodegen.generate(ast);
}
 
function addBeforeCode(node) {
  const name = node.id ? node.id.name : '<anonymous function>';
  const parameters = node.params.map(p => '${ ' + p.name + ' }').join(', ');
  const line = node.loc.start.line;
  const beforeCode = "console.log(`Entering " + name + `(` + parameters + ") at line " + line + "`);";
  const beforeNodes = espree.parse(beforeCode, { ecmaVersion: 12}).body;
  node.body.body = beforeNodes.concat(node.body.body);
}