index.js 17 KB

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