index.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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 _pluginSyntaxObjectRestSpread = _interopRequireDefault(require("@babel/plugin-syntax-object-rest-spread"));
  8. var _core = require("@babel/core");
  9. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  10. const ZERO_REFS = (() => {
  11. const node = _core.types.identifier("a");
  12. const property = _core.types.objectProperty(_core.types.identifier("key"), node);
  13. const pattern = _core.types.objectPattern([property]);
  14. return _core.types.isReferenced(node, property, pattern) ? 1 : 0;
  15. })();
  16. var _default = (0, _helperPluginUtils.declare)((api, opts) => {
  17. api.assertVersion(7);
  18. const {
  19. useBuiltIns = false,
  20. loose = false
  21. } = opts;
  22. if (typeof loose !== "boolean") {
  23. throw new Error(".loose must be a boolean, or undefined");
  24. }
  25. function getExtendsHelper(file) {
  26. return useBuiltIns ? _core.types.memberExpression(_core.types.identifier("Object"), _core.types.identifier("assign")) : file.addHelper("extends");
  27. }
  28. function hasRestElement(path) {
  29. let foundRestElement = false;
  30. visitRestElements(path, restElement => {
  31. foundRestElement = true;
  32. restElement.stop();
  33. });
  34. return foundRestElement;
  35. }
  36. function hasObjectPatternRestElement(path) {
  37. let foundRestElement = false;
  38. visitRestElements(path, restElement => {
  39. if (restElement.parentPath.isObjectPattern()) {
  40. foundRestElement = true;
  41. restElement.stop();
  42. }
  43. });
  44. return foundRestElement;
  45. }
  46. function visitRestElements(path, visitor) {
  47. path.traverse({
  48. Expression(path) {
  49. const parentType = path.parent.type;
  50. if (parentType === "AssignmentPattern" && path.key === "right" || parentType === "ObjectProperty" && path.parent.computed && path.key === "key") {
  51. path.skip();
  52. }
  53. },
  54. RestElement: visitor
  55. });
  56. }
  57. function hasSpread(node) {
  58. for (const prop of node.properties) {
  59. if (_core.types.isSpreadElement(prop)) {
  60. return true;
  61. }
  62. }
  63. return false;
  64. }
  65. function extractNormalizedKeys(path) {
  66. const props = path.node.properties;
  67. const keys = [];
  68. let allLiteral = true;
  69. for (const prop of props) {
  70. if (_core.types.isIdentifier(prop.key) && !prop.computed) {
  71. keys.push(_core.types.stringLiteral(prop.key.name));
  72. } else if (_core.types.isTemplateLiteral(prop.key)) {
  73. keys.push(_core.types.cloneNode(prop.key));
  74. } else if (_core.types.isLiteral(prop.key)) {
  75. keys.push(_core.types.stringLiteral(String(prop.key.value)));
  76. } else {
  77. keys.push(_core.types.cloneNode(prop.key));
  78. allLiteral = false;
  79. }
  80. }
  81. return {
  82. keys,
  83. allLiteral
  84. };
  85. }
  86. function replaceImpureComputedKeys(properties, scope) {
  87. const impureComputedPropertyDeclarators = [];
  88. for (const propPath of properties) {
  89. const key = propPath.get("key");
  90. if (propPath.node.computed && !key.isPure()) {
  91. const name = scope.generateUidBasedOnNode(key.node);
  92. const declarator = _core.types.variableDeclarator(_core.types.identifier(name), key.node);
  93. impureComputedPropertyDeclarators.push(declarator);
  94. key.replaceWith(_core.types.identifier(name));
  95. }
  96. }
  97. return impureComputedPropertyDeclarators;
  98. }
  99. function removeUnusedExcludedKeys(path) {
  100. const bindings = path.getOuterBindingIdentifierPaths();
  101. Object.keys(bindings).forEach(bindingName => {
  102. const bindingParentPath = bindings[bindingName].parentPath;
  103. if (path.scope.getBinding(bindingName).references > ZERO_REFS || !bindingParentPath.isObjectProperty()) {
  104. return;
  105. }
  106. bindingParentPath.remove();
  107. });
  108. }
  109. function createObjectSpread(path, file, objRef) {
  110. const props = path.get("properties");
  111. const last = props[props.length - 1];
  112. _core.types.assertRestElement(last.node);
  113. const restElement = _core.types.cloneNode(last.node);
  114. last.remove();
  115. const impureComputedPropertyDeclarators = replaceImpureComputedKeys(path.get("properties"), path.scope);
  116. const {
  117. keys,
  118. allLiteral
  119. } = extractNormalizedKeys(path);
  120. if (keys.length === 0) {
  121. return [impureComputedPropertyDeclarators, restElement.argument, _core.types.callExpression(getExtendsHelper(file), [_core.types.objectExpression([]), _core.types.cloneNode(objRef)])];
  122. }
  123. let keyExpression;
  124. if (!allLiteral) {
  125. keyExpression = _core.types.callExpression(_core.types.memberExpression(_core.types.arrayExpression(keys), _core.types.identifier("map")), [file.addHelper("toPropertyKey")]);
  126. } else {
  127. keyExpression = _core.types.arrayExpression(keys);
  128. }
  129. return [impureComputedPropertyDeclarators, restElement.argument, _core.types.callExpression(file.addHelper(`objectWithoutProperties${loose ? "Loose" : ""}`), [_core.types.cloneNode(objRef), keyExpression])];
  130. }
  131. function replaceRestElement(parentPath, paramPath) {
  132. if (paramPath.isAssignmentPattern()) {
  133. replaceRestElement(parentPath, paramPath.get("left"));
  134. return;
  135. }
  136. if (paramPath.isArrayPattern() && hasRestElement(paramPath)) {
  137. const elements = paramPath.get("elements");
  138. for (let i = 0; i < elements.length; i++) {
  139. replaceRestElement(parentPath, elements[i]);
  140. }
  141. }
  142. if (paramPath.isObjectPattern() && hasRestElement(paramPath)) {
  143. const uid = parentPath.scope.generateUidIdentifier("ref");
  144. const declar = _core.types.variableDeclaration("let", [_core.types.variableDeclarator(paramPath.node, uid)]);
  145. parentPath.ensureBlock();
  146. parentPath.get("body").unshiftContainer("body", declar);
  147. paramPath.replaceWith(_core.types.cloneNode(uid));
  148. }
  149. }
  150. return {
  151. name: "proposal-object-rest-spread",
  152. inherits: _pluginSyntaxObjectRestSpread.default,
  153. visitor: {
  154. Function(path) {
  155. const params = path.get("params");
  156. for (let i = params.length - 1; i >= 0; i--) {
  157. replaceRestElement(params[i].parentPath, params[i]);
  158. }
  159. },
  160. VariableDeclarator(path, file) {
  161. if (!path.get("id").isObjectPattern()) {
  162. return;
  163. }
  164. let insertionPath = path;
  165. const originalPath = path;
  166. visitRestElements(path.get("id"), path => {
  167. if (!path.parentPath.isObjectPattern()) {
  168. return;
  169. }
  170. if (originalPath.node.id.properties.length > 1 && !_core.types.isIdentifier(originalPath.node.init)) {
  171. const initRef = path.scope.generateUidIdentifierBasedOnNode(originalPath.node.init, "ref");
  172. originalPath.insertBefore(_core.types.variableDeclarator(initRef, originalPath.node.init));
  173. originalPath.replaceWith(_core.types.variableDeclarator(originalPath.node.id, _core.types.cloneNode(initRef)));
  174. return;
  175. }
  176. let ref = originalPath.node.init;
  177. const refPropertyPath = [];
  178. let kind;
  179. path.findParent(path => {
  180. if (path.isObjectProperty()) {
  181. refPropertyPath.unshift(path);
  182. } else if (path.isVariableDeclarator()) {
  183. kind = path.parentPath.node.kind;
  184. return true;
  185. }
  186. });
  187. const impureObjRefComputedDeclarators = replaceImpureComputedKeys(refPropertyPath, path.scope);
  188. refPropertyPath.forEach(prop => {
  189. const {
  190. node
  191. } = prop;
  192. ref = _core.types.memberExpression(ref, _core.types.cloneNode(node.key), node.computed);
  193. });
  194. const objectPatternPath = path.findParent(path => path.isObjectPattern());
  195. const [impureComputedPropertyDeclarators, argument, callExpression] = createObjectSpread(objectPatternPath, file, ref);
  196. if (loose) {
  197. removeUnusedExcludedKeys(objectPatternPath);
  198. }
  199. _core.types.assertIdentifier(argument);
  200. insertionPath.insertBefore(impureComputedPropertyDeclarators);
  201. insertionPath.insertBefore(impureObjRefComputedDeclarators);
  202. insertionPath.insertAfter(_core.types.variableDeclarator(argument, callExpression));
  203. insertionPath = insertionPath.getSibling(insertionPath.key + 1);
  204. path.scope.registerBinding(kind, insertionPath);
  205. if (objectPatternPath.node.properties.length === 0) {
  206. objectPatternPath.findParent(path => path.isObjectProperty() || path.isVariableDeclarator()).remove();
  207. }
  208. });
  209. },
  210. ExportNamedDeclaration(path) {
  211. const declaration = path.get("declaration");
  212. if (!declaration.isVariableDeclaration()) return;
  213. const hasRest = declaration.get("declarations").some(path => hasObjectPatternRestElement(path.get("id")));
  214. if (!hasRest) return;
  215. const specifiers = [];
  216. for (const name of Object.keys(path.getOuterBindingIdentifiers(path))) {
  217. specifiers.push(_core.types.exportSpecifier(_core.types.identifier(name), _core.types.identifier(name)));
  218. }
  219. path.replaceWith(declaration.node);
  220. path.insertAfter(_core.types.exportNamedDeclaration(null, specifiers));
  221. },
  222. CatchClause(path) {
  223. const paramPath = path.get("param");
  224. replaceRestElement(paramPath.parentPath, paramPath);
  225. },
  226. AssignmentExpression(path, file) {
  227. const leftPath = path.get("left");
  228. if (leftPath.isObjectPattern() && hasRestElement(leftPath)) {
  229. const nodes = [];
  230. const refName = path.scope.generateUidBasedOnNode(path.node.right, "ref");
  231. nodes.push(_core.types.variableDeclaration("var", [_core.types.variableDeclarator(_core.types.identifier(refName), path.node.right)]));
  232. const [impureComputedPropertyDeclarators, argument, callExpression] = createObjectSpread(leftPath, file, _core.types.identifier(refName));
  233. if (impureComputedPropertyDeclarators.length > 0) {
  234. nodes.push(_core.types.variableDeclaration("var", impureComputedPropertyDeclarators));
  235. }
  236. const nodeWithoutSpread = _core.types.cloneNode(path.node);
  237. nodeWithoutSpread.right = _core.types.identifier(refName);
  238. nodes.push(_core.types.expressionStatement(nodeWithoutSpread));
  239. nodes.push(_core.types.toStatement(_core.types.assignmentExpression("=", argument, callExpression)));
  240. nodes.push(_core.types.expressionStatement(_core.types.identifier(refName)));
  241. path.replaceWithMultiple(nodes);
  242. }
  243. },
  244. ForXStatement(path) {
  245. const {
  246. node,
  247. scope
  248. } = path;
  249. const leftPath = path.get("left");
  250. const left = node.left;
  251. if (!hasObjectPatternRestElement(leftPath)) {
  252. return;
  253. }
  254. if (!_core.types.isVariableDeclaration(left)) {
  255. const temp = scope.generateUidIdentifier("ref");
  256. node.left = _core.types.variableDeclaration("var", [_core.types.variableDeclarator(temp)]);
  257. path.ensureBlock();
  258. if (node.body.body.length === 0 && path.isCompletionRecord()) {
  259. node.body.body.unshift(_core.types.expressionStatement(scope.buildUndefinedNode()));
  260. }
  261. node.body.body.unshift(_core.types.expressionStatement(_core.types.assignmentExpression("=", left, _core.types.cloneNode(temp))));
  262. } else {
  263. const pattern = left.declarations[0].id;
  264. const key = scope.generateUidIdentifier("ref");
  265. node.left = _core.types.variableDeclaration(left.kind, [_core.types.variableDeclarator(key, null)]);
  266. path.ensureBlock();
  267. node.body.body.unshift(_core.types.variableDeclaration(node.left.kind, [_core.types.variableDeclarator(pattern, _core.types.cloneNode(key))]));
  268. }
  269. },
  270. ArrayPattern(path) {
  271. const objectPatterns = [];
  272. visitRestElements(path, path => {
  273. if (!path.parentPath.isObjectPattern()) {
  274. return;
  275. }
  276. const objectPattern = path.parentPath;
  277. const uid = path.scope.generateUidIdentifier("ref");
  278. objectPatterns.push(_core.types.variableDeclarator(objectPattern.node, uid));
  279. objectPattern.replaceWith(_core.types.cloneNode(uid));
  280. path.skip();
  281. });
  282. if (objectPatterns.length > 0) {
  283. const statementPath = path.getStatementParent();
  284. statementPath.insertAfter(_core.types.variableDeclaration(statementPath.node.kind || "var", objectPatterns));
  285. }
  286. },
  287. ObjectExpression(path, file) {
  288. if (!hasSpread(path.node)) return;
  289. const args = [];
  290. let props = [];
  291. function push() {
  292. args.push(_core.types.objectExpression(props));
  293. props = [];
  294. }
  295. for (const prop of path.node.properties) {
  296. if (_core.types.isSpreadElement(prop)) {
  297. push();
  298. args.push(prop.argument);
  299. } else {
  300. props.push(prop);
  301. }
  302. }
  303. if (props.length) {
  304. push();
  305. }
  306. let helper;
  307. if (loose) {
  308. helper = getExtendsHelper(file);
  309. } else {
  310. try {
  311. helper = file.addHelper("objectSpread2");
  312. } catch (_unused) {
  313. this.file.declarations["objectSpread2"] = null;
  314. helper = file.addHelper("objectSpread");
  315. }
  316. }
  317. path.replaceWith(_core.types.callExpression(helper, args));
  318. }
  319. }
  320. };
  321. });
  322. exports.default = _default;