CachedSource.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const Source = require("./Source");
  7. class CachedSource extends Source {
  8. constructor(source) {
  9. super();
  10. this._source = source;
  11. this._cachedSource = undefined;
  12. this._cachedSize = undefined;
  13. this._cachedMaps = {};
  14. if(source.node) this.node = function(options) {
  15. return this._source.node(options);
  16. };
  17. if(source.listMap) this.listMap = function(options) {
  18. return this._source.listMap(options);
  19. };
  20. }
  21. source() {
  22. if(typeof this._cachedSource !== "undefined") return this._cachedSource;
  23. return this._cachedSource = this._source.source();
  24. }
  25. size() {
  26. if(typeof this._cachedSize !== "undefined") return this._cachedSize;
  27. if(typeof this._cachedSource !== "undefined") {
  28. if(Buffer.from.length === 1) return new Buffer(this._cachedSource).length;
  29. return this._cachedSize = Buffer.byteLength(this._cachedSource);
  30. }
  31. return this._cachedSize = this._source.size();
  32. }
  33. sourceAndMap(options) {
  34. const key = JSON.stringify(options);
  35. if(typeof this._cachedSource !== "undefined" && key in this._cachedMaps)
  36. return {
  37. source: this._cachedSource,
  38. map: this._cachedMaps[key]
  39. };
  40. else if(typeof this._cachedSource !== "undefined") {
  41. return {
  42. source: this._cachedSource,
  43. map: this._cachedMaps[key] = this._source.map(options)
  44. };
  45. } else if(key in this._cachedMaps) {
  46. return {
  47. source: this._cachedSource = this._source.source(),
  48. map: this._cachedMaps[key]
  49. };
  50. }
  51. const result = this._source.sourceAndMap(options);
  52. this._cachedSource = result.source;
  53. this._cachedMaps[key] = result.map;
  54. return {
  55. source: this._cachedSource,
  56. map: this._cachedMaps[key]
  57. };
  58. }
  59. map(options) {
  60. if(!options) options = {};
  61. const key = JSON.stringify(options);
  62. if(key in this._cachedMaps)
  63. return this._cachedMaps[key];
  64. return this._cachedMaps[key] = this._source.map();
  65. }
  66. updateHash(hash) {
  67. this._source.updateHash(hash);
  68. }
  69. }
  70. module.exports = CachedSource;