source-maps.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. const convertSourceMap = require('convert-source-map')
  2. const libCoverage = require('istanbul-lib-coverage')
  3. const libSourceMaps = require('istanbul-lib-source-maps')
  4. const fs = require('fs')
  5. const path = require('path')
  6. // TODO: write some unit tests for this class.
  7. function SourceMaps (opts) {
  8. this.cache = opts.cache
  9. this.cacheDirectory = opts.cacheDirectory
  10. this.sourceMapCache = libSourceMaps.createSourceMapStore()
  11. this.loadedMaps = {}
  12. }
  13. SourceMaps.prototype.extractAndRegister = function (code, filename, hash) {
  14. var sourceMap = convertSourceMap.fromSource(code) || convertSourceMap.fromMapFileSource(code, path.dirname(filename))
  15. if (sourceMap) {
  16. if (this.cache && hash) {
  17. var mapPath = path.join(this.cacheDirectory, hash + '.map')
  18. fs.writeFileSync(mapPath, sourceMap.toJSON())
  19. } else {
  20. this.sourceMapCache.registerMap(filename, sourceMap.sourcemap)
  21. }
  22. }
  23. return sourceMap
  24. }
  25. SourceMaps.prototype.remapCoverage = function (obj) {
  26. var transformed = this.sourceMapCache.transformCoverage(
  27. libCoverage.createCoverageMap(obj)
  28. )
  29. return transformed.map.data
  30. }
  31. SourceMaps.prototype.reloadCachedSourceMaps = function (report) {
  32. var _this = this
  33. Object.keys(report).forEach(function (absFile) {
  34. var fileReport = report[absFile]
  35. if (fileReport && fileReport.contentHash) {
  36. var hash = fileReport.contentHash
  37. if (!(hash in _this.loadedMaps)) {
  38. try {
  39. var mapPath = path.join(_this.cacheDirectory, hash + '.map')
  40. _this.loadedMaps[hash] = JSON.parse(fs.readFileSync(mapPath, 'utf8'))
  41. } catch (e) {
  42. // set to false to avoid repeatedly trying to load the map
  43. _this.loadedMaps[hash] = false
  44. }
  45. }
  46. if (_this.loadedMaps[hash]) {
  47. _this.sourceMapCache.registerMap(absFile, _this.loadedMaps[hash])
  48. }
  49. }
  50. })
  51. }
  52. module.exports = SourceMaps