You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
2.6 KiB

4 years ago
  1. var SourceMapGenerator = require('source-map/lib/source-map-generator').SourceMapGenerator;
  2. var trackNodes = {
  3. Atrule: true,
  4. Selector: true,
  5. Declaration: true
  6. };
  7. module.exports = function generateSourceMap(handlers) {
  8. var map = new SourceMapGenerator();
  9. var line = 1;
  10. var column = 0;
  11. var generated = {
  12. line: 1,
  13. column: 0
  14. };
  15. var original = {
  16. line: 0, // should be zero to add first mapping
  17. column: 0
  18. };
  19. var sourceMappingActive = false;
  20. var activatedGenerated = {
  21. line: 1,
  22. column: 0
  23. };
  24. var activatedMapping = {
  25. generated: activatedGenerated
  26. };
  27. var handlersNode = handlers.node;
  28. handlers.node = function(node) {
  29. if (node.loc && node.loc.start && trackNodes.hasOwnProperty(node.type)) {
  30. var nodeLine = node.loc.start.line;
  31. var nodeColumn = node.loc.start.column - 1;
  32. if (original.line !== nodeLine ||
  33. original.column !== nodeColumn) {
  34. original.line = nodeLine;
  35. original.column = nodeColumn;
  36. generated.line = line;
  37. generated.column = column;
  38. if (sourceMappingActive) {
  39. sourceMappingActive = false;
  40. if (generated.line !== activatedGenerated.line ||
  41. generated.column !== activatedGenerated.column) {
  42. map.addMapping(activatedMapping);
  43. }
  44. }
  45. sourceMappingActive = true;
  46. map.addMapping({
  47. source: node.loc.source,
  48. original: original,
  49. generated: generated
  50. });
  51. }
  52. }
  53. handlersNode.call(this, node);
  54. if (sourceMappingActive && trackNodes.hasOwnProperty(node.type)) {
  55. activatedGenerated.line = line;
  56. activatedGenerated.column = column;
  57. }
  58. };
  59. var handlersChunk = handlers.chunk;
  60. handlers.chunk = function(chunk) {
  61. for (var i = 0; i < chunk.length; i++) {
  62. if (chunk.charCodeAt(i) === 10) { // \n
  63. line++;
  64. column = 0;
  65. } else {
  66. column++;
  67. }
  68. }
  69. handlersChunk(chunk);
  70. };
  71. var handlersResult = handlers.result;
  72. handlers.result = function() {
  73. if (sourceMappingActive) {
  74. map.addMapping(activatedMapping);
  75. }
  76. return {
  77. css: handlersResult(),
  78. map: map
  79. };
  80. };
  81. return handlers;
  82. };