index.js 20 KB

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