index.js 18 KB

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