source: frontend/node_modules/@babel/plugin-transform-object-rest-spread/lib/index.js

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 12 days ago

Fix frontend appearance

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