index.js 16 KB

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