index.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 _pluginSyntaxFunctionSent = _interopRequireDefault(require("@babel/plugin-syntax-function-sent"));
  8. var _helperWrapFunction = _interopRequireDefault(require("@babel/helper-wrap-function"));
  9. var _core = require("@babel/core");
  10. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11. var _default = (0, _helperPluginUtils.declare)(api => {
  12. api.assertVersion(7);
  13. const isFunctionSent = node => _core.types.isIdentifier(node.meta, {
  14. name: "function"
  15. }) && _core.types.isIdentifier(node.property, {
  16. name: "sent"
  17. });
  18. const hasBeenReplaced = (node, sentId) => _core.types.isAssignmentExpression(node) && _core.types.isIdentifier(node.left, {
  19. name: sentId
  20. });
  21. const yieldVisitor = {
  22. Function(path) {
  23. path.skip();
  24. },
  25. YieldExpression(path) {
  26. if (!hasBeenReplaced(path.parent, this.sentId)) {
  27. path.replaceWith(_core.types.assignmentExpression("=", _core.types.identifier(this.sentId), path.node));
  28. }
  29. },
  30. MetaProperty(path) {
  31. if (isFunctionSent(path.node)) {
  32. path.replaceWith(_core.types.identifier(this.sentId));
  33. }
  34. }
  35. };
  36. return {
  37. name: "proposal-function-sent",
  38. inherits: _pluginSyntaxFunctionSent.default,
  39. visitor: {
  40. MetaProperty(path, state) {
  41. if (!isFunctionSent(path.node)) return;
  42. const fnPath = path.getFunctionParent();
  43. if (!fnPath.node.generator) {
  44. throw new Error("Parent generator function not found");
  45. }
  46. const sentId = path.scope.generateUid("function.sent");
  47. fnPath.traverse(yieldVisitor, {
  48. sentId
  49. });
  50. fnPath.node.body.body.unshift(_core.types.variableDeclaration("let", [_core.types.variableDeclarator(_core.types.identifier(sentId), _core.types.yieldExpression())]));
  51. (0, _helperWrapFunction.default)(fnPath, state.addHelper("skipFirstGeneratorNext"));
  52. }
  53. }
  54. };
  55. });
  56. exports.default = _default;