source.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. /** @typedef {import("webpack-sources").Source} Source */
  7. /** @type {WeakMap<Source, WeakMap<Source, boolean>>} */
  8. const equalityCache = new WeakMap();
  9. /**
  10. * @param {Source} a a source
  11. * @param {Source} b another source
  12. * @returns {boolean} true, when both sources are equal
  13. */
  14. const _isSourceEqual = (a, b) => {
  15. // prefer .buffer(), it's called anyway during emit
  16. /** @type {Buffer|string} */
  17. let aSource = typeof a.buffer === "function" ? a.buffer() : a.source();
  18. /** @type {Buffer|string} */
  19. let bSource = typeof b.buffer === "function" ? b.buffer() : b.source();
  20. if (aSource === bSource) return true;
  21. if (typeof aSource === "string" && typeof bSource === "string") return false;
  22. if (!Buffer.isBuffer(aSource)) aSource = Buffer.from(aSource, "utf-8");
  23. if (!Buffer.isBuffer(bSource)) bSource = Buffer.from(bSource, "utf-8");
  24. return aSource.equals(bSource);
  25. };
  26. /**
  27. * @param {Source} a a source
  28. * @param {Source} b another source
  29. * @returns {boolean} true, when both sources are equal
  30. */
  31. const isSourceEqual = (a, b) => {
  32. if (a === b) return true;
  33. const cache1 = equalityCache.get(a);
  34. if (cache1 !== undefined) {
  35. const result = cache1.get(b);
  36. if (result !== undefined) return result;
  37. }
  38. const result = _isSourceEqual(a, b);
  39. if (cache1 !== undefined) {
  40. cache1.set(b, result);
  41. } else {
  42. const map = new WeakMap();
  43. map.set(b, result);
  44. equalityCache.set(a, map);
  45. }
  46. const cache2 = equalityCache.get(b);
  47. if (cache2 !== undefined) {
  48. cache2.set(a, result);
  49. } else {
  50. const map = new WeakMap();
  51. map.set(a, result);
  52. equalityCache.set(b, map);
  53. }
  54. return result;
  55. };
  56. exports.isSourceEqual = isSourceEqual;