getRefreshGlobal.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. const Template = require('webpack/lib/Template');
  2. const { refreshGlobal } = require('../globals');
  3. /**
  4. * @typedef {Object} RuntimeTemplate
  5. * @property {function(string, string[]): string} basicFunction
  6. * @property {function(): boolean} supportsConst
  7. * @property {function(string, string=): string} returningFunction
  8. */
  9. /** @type {RuntimeTemplate} */
  10. const FALLBACK_RUNTIME_TEMPLATE = {
  11. basicFunction(args, body) {
  12. return `function(${args}) {\n${Template.indent(body)}\n}`;
  13. },
  14. supportsConst() {
  15. return false;
  16. },
  17. returningFunction(returnValue, args = '') {
  18. return `function(${args}) { return ${returnValue}; }`;
  19. },
  20. };
  21. /**
  22. * Generates the refresh global runtime template.
  23. * @param {RuntimeTemplate} [runtimeTemplate] The runtime template helpers.
  24. * @returns {string} The refresh global runtime template.
  25. */
  26. function getRefreshGlobal(runtimeTemplate = FALLBACK_RUNTIME_TEMPLATE) {
  27. const declaration = runtimeTemplate.supportsConst() ? 'const' : 'var';
  28. return Template.asString([
  29. `${refreshGlobal} = {`,
  30. Template.indent([
  31. `init: ${runtimeTemplate.basicFunction('', [
  32. `${refreshGlobal}.cleanup = ${runtimeTemplate.returningFunction('undefined')};`,
  33. `${refreshGlobal}.register = ${runtimeTemplate.returningFunction('undefined')};`,
  34. `${refreshGlobal}.runtime = {};`,
  35. `${refreshGlobal}.signature = ${runtimeTemplate.returningFunction(
  36. runtimeTemplate.returningFunction('type', 'type')
  37. )};`,
  38. ])},`,
  39. `setup: ${runtimeTemplate.basicFunction('currentModuleId', [
  40. `${declaration} prevCleanup = ${refreshGlobal}.cleanup;`,
  41. `${declaration} prevReg = ${refreshGlobal}.register;`,
  42. `${declaration} prevSig = ${refreshGlobal}.signature;`,
  43. '',
  44. `${refreshGlobal}.register = ${runtimeTemplate.basicFunction('type, id', [
  45. `${declaration} typeId = currentModuleId + " " + id;`,
  46. `${refreshGlobal}.runtime.register(type, typeId);`,
  47. ])}`,
  48. '',
  49. `${refreshGlobal}.signature = ${refreshGlobal}.runtime.createSignatureFunctionForTransform;`,
  50. '',
  51. `${refreshGlobal}.cleanup = ${runtimeTemplate.basicFunction('cleanupModuleId', [
  52. 'if (currentModuleId === cleanupModuleId) {',
  53. Template.indent([
  54. `${refreshGlobal}.register = prevReg;`,
  55. `${refreshGlobal}.signature = prevSig;`,
  56. `${refreshGlobal}.cleanup = prevCleanup;`,
  57. ]),
  58. '}',
  59. ])}`,
  60. ])},`,
  61. ]),
  62. '};',
  63. ]);
  64. }
  65. module.exports = getRefreshGlobal;