npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@enriqueam/espree-logging-enrique-alvarez-mesa-alu0101142104

v1.0.0

Published

Adds logs to javascript code

Downloads

3

Readme

Open in Codespaces

Práctica Espree logging

Resumen de lo aprendido

En esta práctica se va a relizar una transformación árbol, insertando console log a las entradas de las funciones que se analizan. Además de aprender a como extraer información del árbol generado.

Indicar los valores de los argumentos

Se ha modificado el código de logging-espree.js para que el log también indique los valores de los argumentos que se pasaron a la función. Ejemplo:

function foo(a, b) {
  var x = 'blah';
  var y = (function (z) {
    return z+3;
  })(2);
}
foo(1, 'wut', 3);
function foo(a, b) {
    console.log(`Entering foo(${ a }, ${ b })`);
    var x = 'blah';
    var y = function (z) {
        console.log(`Entering <anonymous function>(${ z })`);
        return z + 3;
    }(2);
}
foo(1, 'wut', 3);

CLI con Commander.js

Commander es una herramienta que se ocupa de analizar los argumentos de opciones y argumentos de comando, muestra errores de uso e implementa un sistema de ayuda. Está implementada en el ejecutable anterior, donde se define la interfaz a mostar, con la descripción deseada.

  • Se ha añadido la opción -o, --output para indicar el nombre del fichero de salida.
  • Se ha añadido la opción -h, --help para mostrar la ayuda.
  • Con la opción -v, --version se muestra la versión del programa.
#!/usr/bin/env node

import { program } from "commander";
import { createRequire } from "module";
const require = createRequire(import.meta.url);
const { version } = require("../package.json");
import { transpile } from "../src/logging-espree.js";

program
  .version(version)
  .argument("<filename>", 'file with the original code')
  .option("-o, --output <filename>", "file in which to write the output")
  .helpOption("-h, --help", "display this help message")
  .action((filename, options) => {
    transpile(filename, options.output);
  });
 
program.parse(process.argv);

Reto 1: Soportar funciones flecha

Para soportar las funciones flecha es necesario que la función sea capaz de reconcer ese tipo de nodos, para ello además se añade la opción ecmaVersion:6 en el espree.parse() para que el árbol generado sea compatible con las funciones flecha. Además se añade el tipo de nodo ArrowFunctionExpression en el if de la función addLogging().

function addLogging(code) {
  const ast = espree.parse(code);
  estraverse.traverse(ast, {
    enter: function (node, parent) {
      if (node.type === 'FunctionDeclaration' ||
          node.type === 'FunctionExpression' ||
          node.type === 'ArrowFunctionExpression') {
        addBeforeCode(node);
      }
    }
  });
  return escodegen.generate(ast);
}

Reto 2: Añadir el número de línea

Para añadir el número de línea en la que aparece la función, primeramente es necesario modificar la función addLogging y añadir como parámetro en el espree.parse "loc:true" que son las siglas de Line Of Code, pues ahora se puede utilizar el método node.loc.start.line y por tanto se añade al console.log() de beforeCode de la función addBeforeCode.

function addLogging(code) {
  const ast = espree.parse(code, {ecmaVersion:6, loc:true});
  estraverse.traverse(ast, {
    enter: function (node, parent) {  // estraverse siempre pasa el nodo y el padre del nodo por si es necesario, aunque puede ser null. En este caso no se usa.
      if (node.type === 'FunctionDeclaration' ||
          node.type === 'FunctionExpression') {  // FunctionDeclaration son las funciones ordinarias, FunctionExpression son las funciones que se declaran en una expresion 
        addBeforeCode(node);
      }
    }
  });
  return escodegen.generate(ast);
}
 function addBeforeCode(node) {
  const name = node.id ? node.id.name : '<anonymous function>';
  const parameters = node.params.map(param => `\$\{${param.name}\}`);  // Obtiene los parametros de la funcion.
  const beforeCode = `console.log(\`Entering ${name}(${parameters}) at line ${node.loc.start.line}\`);`;
  const beforeNodes = espree.parse(beforeCode, {ecmaVersion: 6}).body;  // Es una array de ATSs.
  node.body.body = beforeNodes.concat(node.body.body);
}

Tests and Covering

Para la ejecución de los test creamos un atajo en el package.json para poder ejecutarlos con el comando npm test. Dicho utiliza el módulo mocha para ejecutar los test y el módulo c8 para la cobertura.

  ...
  "scripts": {
    "fill": "your scripts here",
    "test": "mocha test/test.mjs",
    "cov": "c8 npm run test",
    "doc": "c8 --reporter=html --reporter=text --report-dir=docs mocha"
  },
  ...