istanbul.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict'
  2. var convertSourceMap = require('convert-source-map')
  3. var mergeSourceMap = require('merge-source-map')
  4. function InstrumenterIstanbul (cwd, options) {
  5. var istanbul = InstrumenterIstanbul.istanbul()
  6. var instrumenter = istanbul.createInstrumenter({
  7. autoWrap: true,
  8. coverageVariable: '__coverage__',
  9. embedSource: true,
  10. compact: options.compact,
  11. preserveComments: options.preserveComments,
  12. produceSourceMap: options.produceSourceMap,
  13. ignoreClassMethods: options.ignoreClassMethods,
  14. esModules: true
  15. })
  16. return {
  17. instrumentSync: function (code, filename, sourceMap) {
  18. var instrumented = instrumenter.instrumentSync(code, filename)
  19. // the instrumenter can optionally produce source maps,
  20. // this is useful for features like remapping stack-traces.
  21. // TODO: test source-map merging logic.
  22. if (options.produceSourceMap) {
  23. var lastSourceMap = instrumenter.lastSourceMap()
  24. if (lastSourceMap) {
  25. if (sourceMap) {
  26. lastSourceMap = mergeSourceMap(
  27. sourceMap.toObject(),
  28. lastSourceMap
  29. )
  30. }
  31. instrumented += '\n' + convertSourceMap.fromObject(lastSourceMap).toComment()
  32. }
  33. }
  34. return instrumented
  35. },
  36. lastFileCoverage: function () {
  37. return instrumenter.lastFileCoverage()
  38. }
  39. }
  40. }
  41. InstrumenterIstanbul.istanbul = function () {
  42. InstrumenterIstanbul._istanbul || (InstrumenterIstanbul._istanbul = require('istanbul-lib-instrument'))
  43. return InstrumenterIstanbul._istanbul || (InstrumenterIstanbul._istanbul = require('istanbul'))
  44. }
  45. module.exports = InstrumenterIstanbul