index.js 17 KB

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