index.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = _default;
  6. var t = require("@babel/types");
  7. function getObjRef(node, nodes, scope) {
  8. let ref;
  9. if (t.isIdentifier(node)) {
  10. if (scope.hasBinding(node.name)) {
  11. return node;
  12. } else {
  13. ref = node;
  14. }
  15. } else if (t.isMemberExpression(node)) {
  16. ref = node.object;
  17. if (t.isSuper(ref) || t.isIdentifier(ref) && scope.hasBinding(ref.name)) {
  18. return ref;
  19. }
  20. } else {
  21. throw new Error(`We can't explode this node type ${node["type"]}`);
  22. }
  23. const temp = scope.generateUidIdentifierBasedOnNode(ref);
  24. scope.push({
  25. id: temp
  26. });
  27. nodes.push(t.assignmentExpression("=", t.cloneNode(temp), t.cloneNode(ref)));
  28. return temp;
  29. }
  30. function getPropRef(node, nodes, scope) {
  31. const prop = node.property;
  32. if (t.isPrivateName(prop)) {
  33. throw new Error("We can't generate property ref for private name, please install `@babel/plugin-proposal-class-properties`");
  34. }
  35. const key = t.toComputedKey(node, prop);
  36. if (t.isLiteral(key) && t.isPureish(key)) return key;
  37. const temp = scope.generateUidIdentifierBasedOnNode(prop);
  38. scope.push({
  39. id: temp
  40. });
  41. nodes.push(t.assignmentExpression("=", t.cloneNode(temp), t.cloneNode(prop)));
  42. return temp;
  43. }
  44. function _default(node, nodes, file, scope, allowedSingleIdent) {
  45. let obj;
  46. if (t.isIdentifier(node) && allowedSingleIdent) {
  47. obj = node;
  48. } else {
  49. obj = getObjRef(node, nodes, scope);
  50. }
  51. let ref, uid;
  52. if (t.isIdentifier(node)) {
  53. ref = t.cloneNode(node);
  54. uid = obj;
  55. } else {
  56. const prop = getPropRef(node, nodes, scope);
  57. const computed = node.computed || t.isLiteral(prop);
  58. uid = t.memberExpression(t.cloneNode(obj), t.cloneNode(prop), computed);
  59. ref = t.memberExpression(t.cloneNode(obj), t.cloneNode(prop), computed);
  60. }
  61. return {
  62. uid: uid,
  63. ref: ref
  64. };
  65. }