createHooksRegistry.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. */
  4. "use strict";
  5. /**
  6. * @template T
  7. * @param {() => T} createHooks factory that returns a fresh hooks object
  8. * @returns {(compilation: import("../Compilation")) => T} getter that returns (or creates) hooks for the compilation
  9. */
  10. const createHooksRegistry = (createHooks) => {
  11. /** @type {WeakMap<import("../Compilation"), T>} */
  12. const map = new WeakMap();
  13. return (compilation) => {
  14. let hooks = map.get(compilation);
  15. if (hooks === undefined) {
  16. // validated once per compilation — this runs on every render and
  17. // codegen. Matched by class name, not `instanceof`: a compilation from
  18. // another webpack copy has to pass too, and importing `Compilation`
  19. // here cycles.
  20. const candidate =
  21. /** @type {{ constructor?: { name: string } } | null} */
  22. (compilation);
  23. if (
  24. !candidate ||
  25. !candidate.constructor ||
  26. candidate.constructor.name !== "Compilation"
  27. ) {
  28. throw new TypeError(
  29. "The 'compilation' argument must be an instance of Compilation"
  30. );
  31. }
  32. hooks = createHooks();
  33. map.set(compilation, hooks);
  34. }
  35. return hooks;
  36. };
  37. };
  38. module.exports = createHooksRegistry;