PrefixSource.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. var Source = require("./Source");
  7. var SourceNode = require("source-map").SourceNode;
  8. var REPLACE_REGEX = /\n(?=.|\s)/g;
  9. function cloneAndPrefix(node, prefix, append) {
  10. if(typeof node === "string") {
  11. var result = node.replace(REPLACE_REGEX, "\n" + prefix);
  12. if(append.length > 0) result = append.pop() + result;
  13. if(/\n$/.test(node)) append.push(prefix);
  14. return result;
  15. } else {
  16. var newNode = new SourceNode(
  17. node.line,
  18. node.column,
  19. node.source,
  20. node.children.map(function(node) {
  21. return cloneAndPrefix(node, prefix, append);
  22. }),
  23. node.name
  24. );
  25. newNode.sourceContents = node.sourceContents;
  26. return newNode;
  27. }
  28. };
  29. class PrefixSource extends Source {
  30. constructor(prefix, source) {
  31. super();
  32. this._source = source;
  33. this._prefix = prefix;
  34. }
  35. source() {
  36. var node = typeof this._source === "string" ? this._source : this._source.source();
  37. var prefix = this._prefix;
  38. return prefix + node.replace(REPLACE_REGEX, "\n" + prefix);
  39. }
  40. node(options) {
  41. var node = this._source.node(options);
  42. var append = [this._prefix];
  43. return new SourceNode(null, null, null, [
  44. cloneAndPrefix(node, this._prefix, append)
  45. ]);
  46. }
  47. listMap(options) {
  48. var prefix = this._prefix;
  49. var map = this._source.listMap(options);
  50. return map.mapGeneratedCode(function(code) {
  51. return prefix + code.replace(REPLACE_REGEX, "\n" + prefix);
  52. });
  53. }
  54. updateHash(hash) {
  55. if(typeof this._source === "string")
  56. hash.update(this._source);
  57. else
  58. this._source.updateHash(hash);
  59. if(typeof this._prefix === "string")
  60. hash.update(this._prefix);
  61. else
  62. this._prefix.updateHash(hash);
  63. }
  64. }
  65. require("./SourceAndMapMixin")(PrefixSource.prototype);
  66. module.exports = PrefixSource;