source.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. * Checks whether source equal true, when both sources are equal.
  11. * @param {Source} a a source
  12. * @param {Source} b another source
  13. * @returns {boolean} true, when both sources are equal
  14. */
  15. const _isSourceEqual = (a, b) => {
  16. // prefer .buffer(), it's called anyway during emit
  17. /** @type {Buffer | string} */
  18. let aSource = typeof a.buffer === "function" ? a.buffer() : a.source();
  19. /** @type {Buffer | string} */
  20. let bSource = typeof b.buffer === "function" ? b.buffer() : b.source();
  21. if (aSource === bSource) return true;
  22. if (typeof aSource === "string" && typeof bSource === "string") return false;
  23. if (!Buffer.isBuffer(aSource)) aSource = Buffer.from(aSource, "utf8");
  24. if (!Buffer.isBuffer(bSource)) bSource = Buffer.from(bSource, "utf8");
  25. return aSource.equals(bSource);
  26. };
  27. /**
  28. * Checks whether this object is source equal.
  29. * @param {Source} a a source
  30. * @param {Source} b another source
  31. * @returns {boolean} true, when both sources are equal
  32. */
  33. const isSourceEqual = (a, b) => {
  34. if (a === b) return true;
  35. const cache1 = equalityCache.get(a);
  36. if (cache1 !== undefined) {
  37. const result = cache1.get(b);
  38. if (result !== undefined) return result;
  39. }
  40. const result = _isSourceEqual(a, b);
  41. if (cache1 !== undefined) {
  42. cache1.set(b, result);
  43. } else {
  44. const map = new WeakMap();
  45. map.set(b, result);
  46. equalityCache.set(a, map);
  47. }
  48. const cache2 = equalityCache.get(b);
  49. if (cache2 !== undefined) {
  50. cache2.set(a, result);
  51. } else {
  52. const map = new WeakMap();
  53. map.set(a, result);
  54. equalityCache.set(b, map);
  55. }
  56. return result;
  57. };
  58. module.exports.isSourceEqual = isSourceEqual;