parserHooks.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Alexander Akait @alexander-akait
  4. */
  5. "use strict";
  6. const { SyncBailHook } = require("tapable");
  7. /** @import JavascriptParser from "../javascript/JavascriptParser" */
  8. /** @import { CallExpression, Expression, SpreadElement } from "estree" */
  9. /** @typedef {string[]} Requests */
  10. /**
  11. * Defines the hmr javascript parser hooks type used by this module.
  12. * @typedef {object} HMRJavascriptParserHooks
  13. * @property {SyncBailHook<[Expression | SpreadElement, Requests], void>} hotAcceptCallback
  14. * @property {SyncBailHook<[CallExpression, Requests], void>} hotAcceptWithoutCallback
  15. */
  16. /** @type {WeakMap<JavascriptParser, HMRJavascriptParserHooks>} */
  17. const parserHooksMap = new WeakMap();
  18. /**
  19. * Returns the attached hooks.
  20. * @param {JavascriptParser} parser the parser
  21. * @returns {HMRJavascriptParserHooks} the attached hooks
  22. */
  23. const getParserHooks = (parser) => {
  24. // matched by class name, as `createHooksRegistry` does: a parser from another
  25. // webpack copy has to pass, and requiring the parser here loads it eagerly
  26. const candidate = /** @type {{ constructor?: { name: string } } | null} */ (
  27. parser
  28. );
  29. if (
  30. !candidate ||
  31. !candidate.constructor ||
  32. candidate.constructor.name !== "JavascriptParser"
  33. ) {
  34. throw new TypeError(
  35. "The 'parser' argument must be an instance of JavascriptParser"
  36. );
  37. }
  38. let hooks = parserHooksMap.get(parser);
  39. if (hooks === undefined) {
  40. hooks = {
  41. hotAcceptCallback: new SyncBailHook(["expression", "requests"]),
  42. hotAcceptWithoutCallback: new SyncBailHook(["expression", "requests"])
  43. };
  44. parserHooksMap.set(parser, hooks);
  45. }
  46. return hooks;
  47. };
  48. module.exports = getParserHooks;