All files logging-espree.js

100% Statements 59/59
100% Branches 15/15
100% Functions 4/4
100% Lines 59/59

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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 601x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 4x 4x 4x 1x 1x 1x 3x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 212x 212x 212x 9x 9x 212x 4x 4x 4x 1x 1x 1x 1x 1x 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";
 
/**
 * Read the file with the js program, calls addLogin to add the login messages and writes the output
 * @param {string} inputFile - The name of the input file
 * @param {string} outputFile - The name of the output file
 */
 
export async function transpile(inputFile, outputFile) {
 
  if (inputFile) {
    let input = await fs.readFile(inputFile, 'utf-8');
    const output = addLogging(input);
    if (outputFile === undefined) {
      console.log(output);
      return;
    }
    await fs.writeFile(outputFile, output);
  } else program.help();
}
 
 
/** 
 * Builds the AST and
 * Traverses it searching for function nodes and callas addBeforeNode to transform the AST
 * @param {string} code -the source code 
 * @returns -- The transformed AST 
 */
 
export function addLogging(code) {
  let ast = espree.parse(code, {ecmaVersion:6, 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);
}
 
/**
 * AST transformation
 * add a console.log to each node
 * @param {AST function type node} node 
 */
function addBeforeCode(node) {
  //debugger;
  const name = node.id ? node.id.name : '<anonymous function>';
  const parameters = node.params.map(param => `\$\{${param.name}\}`);
  const beforeCode = `console.log(\`Entering ${name}(${parameters}) at line ${node.loc.start.line}\`);`;
  const beforeNodes = espree.parse(beforeCode,{ecmaVersion:6}).body;
  node.body.body = beforeNodes.concat(node.body.body);
}