index.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _helperPluginUtils = require("@babel/helper-plugin-utils");
  7. var _pluginSyntaxClassStaticBlock = require("@babel/plugin-syntax-class-static-block");
  8. var _helperCreateClassFeaturesPlugin = require("@babel/helper-create-class-features-plugin");
  9. function generateUid(scope, denyList) {
  10. const name = "";
  11. let uid;
  12. let i = 1;
  13. do {
  14. uid = scope._generateUid(name, i);
  15. i++;
  16. } while (denyList.has(uid));
  17. return uid;
  18. }
  19. var _default = (0, _helperPluginUtils.declare)(({
  20. types: t,
  21. template,
  22. assertVersion
  23. }) => {
  24. assertVersion("^7.12.0");
  25. return {
  26. name: "proposal-class-static-block",
  27. inherits: _pluginSyntaxClassStaticBlock.default,
  28. pre() {
  29. (0, _helperCreateClassFeaturesPlugin.enableFeature)(this.file, _helperCreateClassFeaturesPlugin.FEATURES.staticBlocks, false);
  30. },
  31. visitor: {
  32. ClassBody(classBody) {
  33. const {
  34. scope
  35. } = classBody;
  36. const privateNames = new Set();
  37. const body = classBody.get("body");
  38. for (const path of body) {
  39. if (path.isPrivate()) {
  40. privateNames.add(path.get("key.id").node.name);
  41. }
  42. }
  43. for (const path of body) {
  44. if (!path.isStaticBlock()) continue;
  45. const staticBlockPrivateId = generateUid(scope, privateNames);
  46. privateNames.add(staticBlockPrivateId);
  47. const staticBlockRef = t.privateName(t.identifier(staticBlockPrivateId));
  48. let replacement;
  49. const blockBody = path.node.body;
  50. if (blockBody.length === 1 && t.isExpressionStatement(blockBody[0])) {
  51. replacement = blockBody[0].expression;
  52. } else {
  53. replacement = template.expression.ast`(() => { ${blockBody} })()`;
  54. }
  55. path.replaceWith(t.classPrivateProperty(staticBlockRef, replacement, [], true));
  56. }
  57. }
  58. }
  59. };
  60. });
  61. exports.default = _default;