You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
1.9 KiB

4 years ago
  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 _core = require("@babel/core");
  8. var _default = (0, _helperPluginUtils.declare)(api => {
  9. api.assertVersion(7);
  10. return {
  11. name: "transform-new-target",
  12. visitor: {
  13. MetaProperty(path) {
  14. const meta = path.get("meta");
  15. const property = path.get("property");
  16. const {
  17. scope
  18. } = path;
  19. if (meta.isIdentifier({
  20. name: "new"
  21. }) && property.isIdentifier({
  22. name: "target"
  23. })) {
  24. const func = path.findParent(path => {
  25. if (path.isClass()) return true;
  26. if (path.isFunction() && !path.isArrowFunctionExpression()) {
  27. if (path.isClassMethod({
  28. kind: "constructor"
  29. })) {
  30. return false;
  31. }
  32. return true;
  33. }
  34. return false;
  35. });
  36. if (!func) {
  37. throw path.buildCodeFrameError("new.target must be under a (non-arrow) function or a class.");
  38. }
  39. const {
  40. node
  41. } = func;
  42. if (!node.id) {
  43. if (func.isMethod()) {
  44. path.replaceWith(scope.buildUndefinedNode());
  45. return;
  46. }
  47. node.id = scope.generateUidIdentifier("target");
  48. }
  49. const constructor = _core.types.memberExpression(_core.types.thisExpression(), _core.types.identifier("constructor"));
  50. if (func.isClass()) {
  51. path.replaceWith(constructor);
  52. return;
  53. }
  54. path.replaceWith(_core.types.conditionalExpression(_core.types.binaryExpression("instanceof", _core.types.thisExpression(), _core.types.cloneNode(node.id)), constructor, scope.buildUndefinedNode()));
  55. }
  56. }
  57. }
  58. };
  59. });
  60. exports.default = _default;