All files logging-espree.js

95.58% Statements 65/68
91.66% Branches 11/12
100% Functions 4/4
95.58% Lines 65/68

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 60 61 62 63 64 65 66 67 68 691x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x       4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 205x 205x 205x 8x 8x 205x 4x 4x 4x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
#!/usr/bin/env node
import * as escodegen from "escodegen";
import * as espree from "espree";
import * as estraverse from "estraverse";
import * as fs from "fs/promises";
//const fs = require('fs');
 
/**
  * @desc Transpile the code in the input file and write the result to the output file.
  * @param {string} inputFile - The name of the file containing the original code.
  * @param {string} outputFile - The name of the file in which to write the output.
*/
export async function transpile(inputFile, outputFile) {
  let input = await fs.readFile(inputFile, 'utf-8');
  let output = addLogging(input);
  if (outputFile === undefined) {
      console.log(output);
      return;
  }
  await fs.writeFile(outputFile, output);
 
  console.log(`input:\n${inputFile}\n---`);
  console.log(`output:\n${outputFile}\n---`);
}
 
/** 
 * @desc Builds the AST and Traverses it searching for function nodes and call as addBeforeNode to transform the AST
 * @param {string} code -the source code 
 * @returns -- The transformed AST 
 */
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);
}
 
/**
 * @desc Add logging code before the given function node in the AST.
 * @param {Object} node - The function node to add logging before.
 */
export function addBeforeCode(node) {
  debugger;
  var name = node.id ? node.id.name : '<anonymous function>';
  const parameters = node.params.map(param => `\$\{ ${param.name}\ }`);
  var beforeCode = "console.log(`Entering " + name + "(" + parameters + ") at line " + node.loc.start.line +  "`);";
  var beforeNodes = espree.parse(beforeCode, {ecmaVersion: 12, loc: true}).body; // Array de ASTs
  node.body.body = beforeNodes.concat(node.body.body);
}
 
/*
console.log(addLogging(`
  function foo(a, b, c) {
    let x = 'tutu';
    let y = (function (x) { return x*x })(2);
    let z = (e => { return e +1 })(4);
    console.log(x,y,z);
  }
  foo(1, 'wut', 3);
`));*/