{"_id":"@alu0101431079/espree-logging-solution","_rev":"1-07cf5c7bc618e134c156885dd53bef25","name":"@alu0101431079/espree-logging-solution","dist-tags":{"latest":"1.1.0"},"versions":{"1.0.0":{"name":"@alu0101431079/espree-logging-solution","author":{"name":"Gines Cruz Chavez","email":"gines.cruz.30@ull.edu.es","url":"https://github.com/gcruz174"},"description":"Adds logs to javascript code","type":"module","bin":{"funlog":"bin/log.js"},"scripts":{"test":"mocha test/test.mjs","cov":"c8 mocha test/test.mjs"},"dependencies":{"acorn":"^8.8.2","commander":"^10.0.0","escodegen":"^2.0.0","espree":"^9.4.1","estraverse":"^5.2.0","underscore":"^1.12.0"},"version":"1.0.0","devDependencies":{"c8":"^7.13.0","mocha":"^10.2.0"},"gitHead":"aaebdcb08358675d2b559755d446c0bf3debf681","_id":"@alu0101431079/espree-logging-solution@1.0.0","_nodeVersion":"19.6.0","_npmVersion":"9.4.0","dist":{"integrity":"sha512-ZC7rAd6jqtbkTmw2Q+phsqYKyIScxoRcOwhaSS5gQW0CCnB2sJNkA07qJEpLBcV+MWolWo/YVpf43/+QTwfgBg==","shasum":"cd42b931045d58773a4e2e6859cf08bfa4f2a0c1","tarball":"https://registry.npmjs.org/@alu0101431079/espree-logging-solution/-/espree-logging-solution-1.0.0.tgz","fileCount":43,"unpackedSize":1505941,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCpFOZeRrAk71wE0ShFTgL4o80ofUbtd3vmf6Q/WwErpAIgRAnYufEFoe7QzE7CaP0DyRXSrKJU9TJzonIdYESNYYg="}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJkAPW4ACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmqAoA/+I2Ov1zcqkp2rVaA4N9nZWX+j7L18kdjxQWogFHl4FURt6dMJ\r\nqadK4eZhg78qHucuj10HHw2o9Mqi4pgf/pI+CGUxnIzWgH4fkI2gL4z6SBZR\r\nailpgO+bOSn8DTKmp4sL45Ae6p5b5XKh2QgO2FlpuADW+d4eZVlWp2tdJfwl\r\nrXfCAptmGn9HUUuj7wrhDoqMPG/pF3j61ICV3Nf2+X37ekFjDDH/+1gB2QVO\r\nadKopwpshkYlN00IFPUELeIni22TdYqJjOZKI7fWmD5zTNVs+00S6AgSNXfV\r\nNOomX3uuO89PWclohexkDKuAswBHuOMyrGSgd4xNSjEKwc99yd6f2Wi44Dhk\r\np9qXT4egKXJgwq4eyMWrMJsA1IXzoI7dD7+nS7nwU8LKFO6feJGOqQW+bnck\r\nE7dXrhMSEZ7AP/O6Rj0ClD7Ugq9yvmY4C7tEhnVTeUZvRjtvSsN5pWy8q8jj\r\nGT4VJ80lpjxzBZ6UQLS4aIo815SN7PxCwiOM0dU9bWDnQrkn09kTyf3pH269\r\nj7jnUf6b9mgOPIrBDEOmFa4t5LWYJgHDnHAWEScubFhix9PnsyPvWNhMp83R\r\nU4jAG8birQmYTesM3s+XbkXI/i4wJ10/LMOYktBRelKtQWz4EPG0ukO3s2pP\r\nei8+CozqASyIOR3641QDb9XOZcj1yLorNtM=\r\n=vKrF\r\n-----END PGP SIGNATURE-----\r\n"},"_npmUser":{"name":"alu0101431079","email":"alu0101431079@ull.edu.es"},"directories":{},"maintainers":[{"name":"alu0101431079","email":"alu0101431079@ull.edu.es"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/espree-logging-solution_1.0.0_1677784504420_0.3156797286446358"},"_hasShrinkwrap":false},"1.1.0":{"name":"@alu0101431079/espree-logging-solution","author":{"name":"Gines Cruz Chavez","email":"gines.cruz.30@ull.edu.es","url":"https://github.com/gcruz174"},"description":"Adds logs to javascript code","type":"module","bin":{"funlog":"bin/log.js"},"scripts":{"test":"mocha test/test.mjs","cov":"c8 mocha test/test.mjs"},"dependencies":{"acorn":"^8.8.2","commander":"^10.0.0","escodegen":"^2.0.0","espree":"^9.4.1","estraverse":"^5.2.0","underscore":"^1.12.0"},"version":"1.1.0","devDependencies":{"c8":"^7.13.0","mocha":"^10.2.0"},"gitHead":"7af425cc01c6eaae57295ba9be1b0449e2e98016","_id":"@alu0101431079/espree-logging-solution@1.1.0","_nodeVersion":"19.6.0","_npmVersion":"9.4.0","dist":{"integrity":"sha512-/UfMlY0VuvcGDgiqB1JjQi/4wKgwML3FmwOv9zAk8cbjUkmWwjJzl7JC6vvgBp7X19uKKEykFBEb8ks211oZPA==","shasum":"420bf6f37b6d551761e0c51d2ddac0d212772d61","tarball":"https://registry.npmjs.org/@alu0101431079/espree-logging-solution/-/espree-logging-solution-1.1.0.tgz","fileCount":48,"unpackedSize":1723979,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDKcZWODpNf9qIy2t9VAY+VDVrXhxKRVPS55FoH+9ePRAIhAPZS73226u/MGR/meshUmz5GxncTlfzQhJWaSw9aTr6A"}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJkAQ39ACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmpSkBAAnjz26L57sbJQg52FDJ32A+2l3oB2eHGETYGKPri3VMgJJYdG\r\n653yia8iV9XRx4axhpBig5BuUv0xsg7TItz6vu0esqnCPhMMDt983jKAA2pQ\r\nfiIGfysqC7KgYVIZ9t8UtTsUNOYqh4hypR56cH3NAysHAVknsoMo3Dz7HFdP\r\nEjq7rBE3g6PF9TmtjyoRNMqGAYeB2/eJBscrrieG2zu0e8K/fAGSczwq2dwG\r\nOUcISV+PLaHiHPA8iKX9NL5WYaFPnG28Pbw+E13l+rZfK2lN6ZsJ7D8Oopza\r\nGR1201bJ1C3041xtcnCInop0lLa2zVvRvnEkkAwAvvxGQu83nEiNfP0YoBPR\r\nI05XXa/v7cAm9+9AvfrlROIjArARMg92yyxVAS/5Wgmi7pnI65x5ql9erpvf\r\nZvX4rBLA/Y86pcE6ltd/eIJrmbT7o1L5kw0JKCKPEm8A6WZ8cJHqM9OWAgsg\r\nwxCW31dF+Fly8j72phd53w6sKC36BDGGUcAMyV1i7SEugi5Gu3CMk2uOD+b9\r\nnyX/cxr/fXZ+sErScVYlXze0TQKOKJVY2KoKNdzoW0kd1yEr6YVSA3S172z4\r\nolC6P+IdHhoB6H5aZjEccOMHAJrOiVlresSIj0fmw9SeKZiaZK1DgSQGtWw0\r\nF4SJMQ8xeHANDFdXXwE4Jfj6rABSpyK8QMU=\r\n=VXqK\r\n-----END PGP SIGNATURE-----\r\n"},"_npmUser":{"name":"alu0101431079","email":"alu0101431079@ull.edu.es"},"directories":{},"maintainers":[{"name":"alu0101431079","email":"alu0101431079@ull.edu.es"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/espree-logging-solution_1.1.0_1677790717268_0.6210707758478715"},"_hasShrinkwrap":false}},"time":{"created":"2023-03-02T19:15:04.332Z","1.0.0":"2023-03-02T19:15:04.646Z","modified":"2023-03-02T20:58:37.565Z","1.1.0":"2023-03-02T20:58:37.478Z"},"maintainers":[{"name":"alu0101431079","email":"alu0101431079@ull.edu.es"}],"description":"Adds logs to javascript code","author":{"name":"Gines Cruz Chavez","email":"gines.cruz.30@ull.edu.es","url":"https://github.com/gcruz174"},"readme":"[![Open in Codespaces](https://classroom.github.com/assets/launch-codespace-f4981d0f882b2a3f0472912d15f9806d57e124e0fc890972558857b51b24a6f9.svg)](https://classroom.github.com/open-in-codespaces?assignment_repo_id=10325032)\n# Práctica Espree logging\n\nGinés Cruz Chávez\n\n## Indicar los valores de los argumentos\n\nSe 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. \nEjemplo:\n\n```javascript\nfunction foo(a, b) {\n  var x = 'blah';\n  var y = (function (z) {\n    return z+3;\n  })(2);\n}\nfoo(1, 'wut', 3);\n```\n\n```javascript\nfunction foo(a, b) {\n    console.log(`Entering foo(${ a }, ${ b })`);\n    var x = 'blah';\n    var y = function (z) {\n        console.log(`Entering <anonymous function>(${ z })`);\n        return z + 3;\n    }(2);\n}\nfoo(1, 'wut', 3);\n```\n\n## CLI con [Commander.js](https://www.npmjs.com/package/commander)\n\nLa plantilla que se nos proporciona para la práctica viene implementada con la librería [Commander.js](https://www.npmjs.com/package/commander) para la gestión de la CLI. Esta librería nos permite definir los argumentos que se le pasan al programa, así como las opciones que se pueden pasar a la CLI. Se permite especificar el nombre del fichero de entrada, y el nombre del fichero de salida, si este último no se especifica, se imprime por pantalla la salida del programa.\n\n![opciones](./docs/commander.png)\n\n## Reto 1: Soportar funciones flecha\n\nSe ha modificado el fichero `logging-espree.js` para que el log también se añada a aquellas funciones que se declaran como 'flecha gorda'. Para ello, hay que indicarle a la función `addLogging` que también debe añadir el log a las funciones de tipo 'ArrowFunctionExpression'.\n\n```js\n/**\n * @desc Given a string of JavaScript code, return a string of JavaScript code\n * that logs the name of each function and its parameters before the\n * function is called.\n * @param {string} code JavaScript code.\n * @returns {string} JavaScript code with logging.\n */\nexport function addLogging(code) {\n  const ast = espree.parse(code, { ecmaVersion: 6, loc: true });\n  estraverse.traverse(ast, {\n    enter: function(node, parent) {\n      if (node.type === 'FunctionDeclaration' ||\n          node.type === 'FunctionExpression' ||\n          node.type === 'ArrowFunctionExpression') {\n        addBeforeCode(node);\n      }\n    }\n  });\n  return escodegen.generate(ast);\n}\n```\n\n## Reto 2: Añadir el número de línea\n\nEn la función `addBeforeCode`, se ha modificado para que el log también indique el número de línea en el que se encuentra la función. El parser espree ya nos proporciona la información de la línea en la que se encuentra la función, por lo que no es necesario calcularlo. Simplemente debemos habilitar esta funcionalidad especificando el parámetro `loc` en el parser.\n\n```js\n/**\n * @desc Given a function node, add a console.log statement before the\n * function that logs the name of the function and its parameters.\n * @param {object} node A function node.\n */\nfunction addBeforeCode(node) {\n  const name = node.id ? node.id.name : '<anonymous function>';\n  const params = node.params.map(param => '${' +param.name + '}').join(', ');\n  const beforeCode = 'console.log(\\`Entering ' + name + '(' + params + ') at line ' + node.loc.start.line + '\\`);';\n  const beforeNodes = espree.parse(beforeCode, { ecmaVersion: 6 }).body;\n  node.body.body = beforeNodes.concat(node.body.body);\n}\n```\n\n## Tests y cubrimiento\n\nAdemás de los 3 tests que venían proporcionados en la plantilla de esta práctica, se han añadido 3 tests más para comprobar que el programa funciona correctamente. Para ello, debemos añadirlos en el fichero `test-description.mjs` y crear los ficheros de salida correctos.\n\n```js\nexport default [\n  {\n    input: 'test1.js',\n    output: 'logged1.js',\n    correctLogged: 'correct-logged1.js',\n    correctOut: 'logged-out1.txt'\n  },\n  {\n    input: 'test2.js',\n    output: 'logged2.js',\n    correctLogged: 'correct-logged2.js',\n    correctOut: 'logged-out2.txt'\n  },\n  {\n    input: 'test3.js',\n    output: 'logged3.js',\n    correctLogged: 'correct-logged3.js',\n    correctOut: 'logged-out3.txt'\n  },\n  {\n    input: 'test4.js',\n    output: 'logged4.js',\n    correctLogged: 'correct-logged4.js',\n    correctOut: 'logged-out4.txt'\n  },\n  {\n    input: 'test5.js',\n    output: 'logged5.js',\n    correctLogged: 'correct-logged5.js',\n    correctOut: 'logged-out5.txt'\n  },\n  {\n    input: 'test6.js',\n    output: 'logged6.js',\n    correctLogged: 'correct-logged6.js',\n    correctOut: 'logged-out6.txt'\n  }\n]\n```\n\nPara comprobar que en los tests tanto la salida como los mensajes generados por el log son correctos, ha sido necesario añadir el siguiente fragmento de código en el fichero `test.mjs`:\n\n```javascript\nfor (let i = 0; i < Test.length; i++) {\n  it(`transpile(${Tst[i].input}, ${Tst[i].output})`, async () => {\n    // First transpile the input file to the output file.\n    await transpile(Test[i].input, Test[i].output);\n    // Compare the output file with the correct output file.\n    const transpileOutput = await fs.readFile(Test[i].output, 'utf8');\n    const correctTranspileOutput = await fs.readFile(Test[i].correctLogged, 'utf8');\n    assert.equal(removeSpaces(transpileOutput), removeSpaces(correctTranspileOutput));\n    // Compare the console.log output with the correct console.log output.\n    let outputs = [];\n    let oldLog = console.log;\n    console.log = function (...args) {\n      outputs.push(args.join(' '));\n    }\n    // Evaluate the output file.\n    await import(Test[i].output);\n    // Add a blank line at the end.\n    outputs.push('');\n    console.log = oldLog;\n    const correctOut = await fs.readFile(Test[i].correctOut, 'utf8');\n    assert.equal(outputs.join('\\n'), correctOut);\n  });\n}\n```\n\nPara obtener los mensajes impresos en pantalla por console.log, ha sido necesario reemplazar la función mediante stubbing para que los mensajes se almacenen en un array. Al final de la ejecución del test, se combina el array de mensajes en una sola cadena y se compara con la salida esperada del programa.\n\nLos test se ejecutan con el comando `npm test` y se obtiene el siguiente resultado:\n\n![tests](./docs/tests.png)\n\nPara lograr realizar un estudio de cubrimiento de los test utilizando módulos de ES6, se ha utilizado la herramienta `c8`. Para instalarla, se ha ejecutado el siguiente comando:\n\n```bash\nnpm install --save-dev c8\n```\n\nSu uso es muy similar al de la herramienta `nyc` posteriormente utilizada. Se ha definido un script en el fichero `package.json` para ejecutar los test con c8:\n\n```json\n\"scripts\": {\n    \"test\": \"mocha test/test.mjs\",\n    \"cov\": \"c8 mocha test/test.mjs\"\n},\n```\n\nPara generar el informe de cubrimiento en formato HTML es necesario ejecutar el comando `npx c8 report --reporter=html`. El resultado obtenido se puede encontrar en la carpeta `docs` del repositorio y en este enlace: [coverage](https://ull-esit-pl-2223.github.io/espree-logging-gines-cruz-chavez-alu0101431079/).\n\n![coverage](./docs/coverage.png)\n\n## GitHub Actions\n\nSe ha hecho uso de la integración continua de GitHub Actions de manera que por cada confirmación que se haga en el repositorio, se ejecuten los test y se compruebe que el programa funciona correctamente. Para ello, se ha creado un fichero de configuración de GitHub Actions en la carpeta `.github/workflows` con el siguiente contenido:\n\n```yaml\n# Write your workflow for CI here\nname: CI\n\n# Controls when the workflow will run\non:\n  # Triggers the workflow on push or pull request events but only for the $default-branch branch\n  push:\n    branches: [ main ]\n  pull_request:\n    branches: [ main ]\n\n  # Allows you to run this workflow manually from the Actions tab\n  workflow_dispatch:\n\n# A workflow run is made up of one or more jobs that can run sequentially or in parallel\njobs:\n  # This workflow contains a single job called \"build\"\n  build:\n    # The type of runner that the job will run on\n    runs-on: ubuntu-latest\n\n    # Steps represent a sequence of tasks that will be executed as part of the job\n    steps:\n      # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it\n      - uses: actions/checkout@v2\n\n      # Runs a single command using the runners shell\n      - name: Run tests\n        run: npm ci && npm test\n```\n\nEl resultado de la ejecución de los test se puede ver en la pestaña de Actions de GitHub:\n\n![github-ci](./docs/github-ci.png)\n\n## NPM\n\nComo requisito de la práctica, se ha publicado el paquete en el registro de NPM. Para ello, primero ha sido necesario crear una cuenta en NPM y ejecutar el siguiente comando para iniciar sesión mediante la herramienta de línea de comandos:\n\n```bash\nnpm login\n```\n\nUna vez iniciada la sesión, se ha publicado el paquete con acceso público con el siguiente comando:\n\n```bash\nnpm publish --access=public\n```\n\nEl paquete se encuentra alojado en el siguiente enlace: [npm](https://www.npmjs.com/package/@alu0101431079/espree-logging-solution).\n\n![npm](./docs/npm.png)","readmeFilename":"README.md"}