index.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. const TRACE_ID = "__self";
  9. function getThisFunctionParent(path) {
  10. let scope = path.scope;
  11. do {
  12. const {
  13. path
  14. } = scope;
  15. if (path.isFunctionParent() && !path.isArrowFunctionExpression()) {
  16. return path;
  17. }
  18. } while (scope = scope.parent);
  19. return null;
  20. }
  21. function isDerivedClass(classPath) {
  22. return classPath.node.superClass !== null;
  23. }
  24. function isThisAllowed(path) {
  25. const parentMethodOrFunction = getThisFunctionParent(path);
  26. if (parentMethodOrFunction === null) {
  27. return true;
  28. }
  29. if (!parentMethodOrFunction.isMethod()) {
  30. return true;
  31. }
  32. if (parentMethodOrFunction.node.kind !== "constructor") {
  33. return true;
  34. }
  35. return !isDerivedClass(parentMethodOrFunction.parentPath.parentPath);
  36. }
  37. var _default = exports.default = (0, _helperPluginUtils.declare)(api => {
  38. api.assertVersion(7);
  39. const visitor = {
  40. JSXOpeningElement(path) {
  41. if (!isThisAllowed(path)) {
  42. return;
  43. }
  44. const node = path.node;
  45. const id = _core.types.jsxIdentifier(TRACE_ID);
  46. const trace = _core.types.thisExpression();
  47. node.attributes.push(_core.types.jsxAttribute(id, _core.types.jsxExpressionContainer(trace)));
  48. }
  49. };
  50. return {
  51. name: "transform-react-jsx-self",
  52. visitor: {
  53. Program(path) {
  54. path.traverse(visitor);
  55. }
  56. }
  57. };
  58. });
  59. //# sourceMappingURL=index.js.map