index.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. var sourceMap = require('source-map')
  2. var SourceMapConsumer = sourceMap.SourceMapConsumer
  3. var SourceMapGenerator = sourceMap.SourceMapGenerator
  4. module.exports = merge
  5. /**
  6. * Merge old source map and new source map and return merged.
  7. * If old or new source map value is falsy, return another one as it is.
  8. *
  9. * @param {object|string} [oldMap] old source map object
  10. * @param {object|string} [newmap] new source map object
  11. * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
  12. */
  13. function merge(oldMap, newMap) {
  14. if (!oldMap) return newMap
  15. if (!newMap) return oldMap
  16. var oldMapConsumer = new SourceMapConsumer(oldMap)
  17. var newMapConsumer = new SourceMapConsumer(newMap)
  18. var mergedMapGenerator = new SourceMapGenerator()
  19. // iterate on new map and overwrite original position of new map with one of old map
  20. newMapConsumer.eachMapping(function(m) {
  21. // pass when `originalLine` is null.
  22. // It occurs in case that the node does not have origin in original code.
  23. if (m.originalLine == null) return
  24. var origPosInOldMap = oldMapConsumer.originalPositionFor({
  25. line: m.originalLine,
  26. column: m.originalColumn
  27. })
  28. if (origPosInOldMap.source == null) return
  29. mergedMapGenerator.addMapping({
  30. original: {
  31. line: origPosInOldMap.line,
  32. column: origPosInOldMap.column
  33. },
  34. generated: {
  35. line: m.generatedLine,
  36. column: m.generatedColumn
  37. },
  38. source: origPosInOldMap.source,
  39. name: origPosInOldMap.name
  40. })
  41. })
  42. var consumers = [oldMapConsumer, newMapConsumer]
  43. consumers.forEach(function(consumer) {
  44. consumer.sources.forEach(function(sourceFile) {
  45. mergedMapGenerator._sources.add(sourceFile)
  46. var sourceContent = consumer.sourceContentFor(sourceFile)
  47. if (sourceContent != null) {
  48. mergedMapGenerator.setSourceContent(sourceFile, sourceContent)
  49. }
  50. })
  51. })
  52. mergedMapGenerator._sourceRoot = oldMap.sourceRoot
  53. mergedMapGenerator._file = oldMap.file
  54. return JSON.parse(mergedMapGenerator.toString())
  55. }