index.js 2.2 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 _pluginSyntaxFunctionBind = _interopRequireDefault(require("@babel/plugin-syntax-function-bind"));
  8. var _core = require("@babel/core");
  9. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  10. var _default = (0, _helperPluginUtils.declare)(api => {
  11. api.assertVersion(7);
  12. function getTempId(scope) {
  13. let id = scope.path.getData("functionBind");
  14. if (id) return _core.types.cloneNode(id);
  15. id = scope.generateDeclaredUidIdentifier("context");
  16. return scope.path.setData("functionBind", id);
  17. }
  18. function getStaticContext(bind, scope) {
  19. const object = bind.object || bind.callee.object;
  20. return scope.isStatic(object) && object;
  21. }
  22. function inferBindContext(bind, scope) {
  23. const staticContext = getStaticContext(bind, scope);
  24. if (staticContext) return _core.types.cloneNode(staticContext);
  25. const tempId = getTempId(scope);
  26. if (bind.object) {
  27. bind.callee = _core.types.sequenceExpression([_core.types.assignmentExpression("=", tempId, bind.object), bind.callee]);
  28. } else {
  29. bind.callee.object = _core.types.assignmentExpression("=", tempId, bind.callee.object);
  30. }
  31. return _core.types.cloneNode(tempId);
  32. }
  33. return {
  34. name: "proposal-function-bind",
  35. inherits: _pluginSyntaxFunctionBind.default,
  36. visitor: {
  37. CallExpression({
  38. node,
  39. scope
  40. }) {
  41. const bind = node.callee;
  42. if (!_core.types.isBindExpression(bind)) return;
  43. const context = inferBindContext(bind, scope);
  44. node.callee = _core.types.memberExpression(bind.callee, _core.types.identifier("call"));
  45. node.arguments.unshift(context);
  46. },
  47. BindExpression(path) {
  48. const {
  49. node,
  50. scope
  51. } = path;
  52. const context = inferBindContext(node, scope);
  53. path.replaceWith(_core.types.callExpression(_core.types.memberExpression(node.callee, _core.types.identifier("bind")), [context]));
  54. }
  55. }
  56. };
  57. });
  58. exports.default = _default;