index.js 19 KB

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