index.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. 'use strict';
  2. var SourceMapGenerator = require('source-map').SourceMapGenerator;
  3. var SourceMapConsumer = require('source-map').SourceMapConsumer;
  4. module.exports = function applySourceMap(file, sourceMap) {
  5. if (typeof sourceMap === 'string' || sourceMap instanceof String) {
  6. sourceMap = JSON.parse(sourceMap);
  7. }
  8. if (file.sourceMap && (typeof file.sourceMap === 'string' || file.sourceMap instanceof String)) {
  9. file.sourceMap = JSON.parse(file.sourceMap);
  10. }
  11. // check source map properties
  12. assertProperty(sourceMap, "file");
  13. assertProperty(sourceMap, "mappings");
  14. assertProperty(sourceMap, "sources");
  15. // fix paths if Windows style paths
  16. sourceMap.file = sourceMap.file.replace(/\\/g, '/');
  17. sourceMap.sources = sourceMap.sources.map(function(filePath) {
  18. return filePath.replace(/\\/g, '/');
  19. });
  20. if (file.sourceMap && file.sourceMap.mappings !== '') {
  21. var generator = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(sourceMap));
  22. generator.applySourceMap(new SourceMapConsumer(file.sourceMap));
  23. file.sourceMap = JSON.parse(generator.toString());
  24. } else {
  25. file.sourceMap = sourceMap;
  26. }
  27. };
  28. function assertProperty(sourceMap, propertyName) {
  29. if (!sourceMap.hasOwnProperty(propertyName)) {
  30. var e = new Error('Source map to be applied is missing the \"' + propertyName + '\" property');
  31. throw e;
  32. }
  33. }