@babel/plugin-transform-optional-chaining 7.22.5 → 8.0.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/lib/index.js +94 -83
- package/lib/index.js.map +1 -1
- package/lib/transform.js +88 -77
- package/lib/transform.js.map +1 -1
- package/lib/util.js +4 -11
- package/lib/util.js.map +1 -1
- package/package.json +14 -10
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
> Transform optional chaining operators into a series of nil checks
|
|
4
4
|
|
|
5
|
-
See our website [@babel/plugin-transform-optional-chaining](https://babeljs.io/docs/
|
|
5
|
+
See our website [@babel/plugin-transform-optional-chaining](https://babeljs.io/docs/babel-plugin-transform-optional-chaining) for more information.
|
|
6
6
|
|
|
7
7
|
## Install
|
|
8
8
|
|
package/lib/index.js
CHANGED
|
@@ -1,11 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
var helperPluginUtils = require('@babel/helper-plugin-utils');
|
|
6
|
-
var syntaxOptionalChaining = require('@babel/plugin-syntax-optional-chaining');
|
|
7
|
-
var core = require('@babel/core');
|
|
8
|
-
var helperSkipTransparentExpressionWrappers = require('@babel/helper-skip-transparent-expression-wrappers');
|
|
1
|
+
import { declare } from '@babel/helper-plugin-utils';
|
|
2
|
+
import syntaxOptionalChaining from '@babel/plugin-syntax-optional-chaining';
|
|
3
|
+
import { template, types } from '@babel/core';
|
|
4
|
+
import { isTransparentExprWrapper, skipTransparentExprWrappers, skipTransparentExprWrapperNodes } from '@babel/helper-skip-transparent-expression-wrappers';
|
|
9
5
|
|
|
10
6
|
function willPathCastToBoolean(path) {
|
|
11
7
|
const maybeWrapped = findOutermostTransparentParent(path);
|
|
@@ -43,18 +39,15 @@ function willPathCastToBoolean(path) {
|
|
|
43
39
|
function findOutermostTransparentParent(path) {
|
|
44
40
|
let maybeWrapped = path;
|
|
45
41
|
path.findParent(p => {
|
|
46
|
-
if (!
|
|
42
|
+
if (!isTransparentExprWrapper(p.node)) return true;
|
|
47
43
|
maybeWrapped = p;
|
|
48
44
|
});
|
|
49
45
|
return maybeWrapped;
|
|
50
46
|
}
|
|
51
47
|
|
|
52
|
-
const {
|
|
53
|
-
ast
|
|
54
|
-
} = core.template.expression;
|
|
55
48
|
function isSimpleMemberExpression(expression) {
|
|
56
|
-
expression =
|
|
57
|
-
return
|
|
49
|
+
expression = skipTransparentExprWrapperNodes(expression);
|
|
50
|
+
return types.isIdentifier(expression) || types.isSuper(expression) || types.isMemberExpression(expression) && !expression.computed && isSimpleMemberExpression(expression.object);
|
|
58
51
|
}
|
|
59
52
|
function needsMemoize(path) {
|
|
60
53
|
let optionalPath = path;
|
|
@@ -65,35 +58,30 @@ function needsMemoize(path) {
|
|
|
65
58
|
const {
|
|
66
59
|
node
|
|
67
60
|
} = optionalPath;
|
|
68
|
-
const childPath =
|
|
61
|
+
const childPath = skipTransparentExprWrappers(optionalPath.isOptionalMemberExpression() ? optionalPath.get("object") : optionalPath.get("callee"));
|
|
69
62
|
if (node.optional) {
|
|
70
63
|
return !scope.isStatic(childPath.node);
|
|
71
64
|
}
|
|
72
65
|
optionalPath = childPath;
|
|
73
66
|
}
|
|
74
67
|
}
|
|
75
|
-
|
|
68
|
+
const NULLISH_CHECK = template.expression(`%%check%% === null || %%ref%% === void 0`);
|
|
69
|
+
const NULLISH_CHECK_NO_DDA = template.expression(`%%check%% == null`);
|
|
70
|
+
const NULLISH_CHECK_NEG = template.expression(`%%check%% !== null && %%ref%% !== void 0`);
|
|
71
|
+
const NULLISH_CHECK_NO_DDA_NEG = template.expression(`%%check%% != null`);
|
|
72
|
+
function transformOptionalChain(path, {
|
|
76
73
|
pureGetters,
|
|
77
74
|
noDocumentAll
|
|
78
|
-
}) {
|
|
75
|
+
}, replacementPath, ifNullish, wrapLast) {
|
|
79
76
|
const {
|
|
80
77
|
scope
|
|
81
78
|
} = path;
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
parentPath
|
|
85
|
-
} = maybeWrapped;
|
|
86
|
-
const willReplacementCastToBoolean = willPathCastToBoolean(maybeWrapped);
|
|
87
|
-
let isDeleteOperation = false;
|
|
88
|
-
const parentIsCall = parentPath.isCallExpression({
|
|
89
|
-
callee: maybeWrapped.node
|
|
90
|
-
}) && path.isOptionalMemberExpression();
|
|
91
|
-
const optionals = [];
|
|
92
|
-
let optionalPath = path;
|
|
93
|
-
if (scope.path.isPattern() && needsMemoize(optionalPath)) {
|
|
94
|
-
path.replaceWith(core.template.ast`(() => ${path.node})()`);
|
|
79
|
+
if (scope.path.isPattern() && needsMemoize(path)) {
|
|
80
|
+
replacementPath.replaceWith(template.expression.ast`(() => ${replacementPath.node})()`);
|
|
95
81
|
return;
|
|
96
82
|
}
|
|
83
|
+
const optionals = [];
|
|
84
|
+
let optionalPath = path;
|
|
97
85
|
while (optionalPath.isOptionalMemberExpression() || optionalPath.isOptionalCallExpression()) {
|
|
98
86
|
const {
|
|
99
87
|
node
|
|
@@ -103,43 +91,45 @@ function transform(path, {
|
|
|
103
91
|
}
|
|
104
92
|
if (optionalPath.isOptionalMemberExpression()) {
|
|
105
93
|
optionalPath.node.type = "MemberExpression";
|
|
106
|
-
optionalPath =
|
|
94
|
+
optionalPath = skipTransparentExprWrappers(optionalPath.get("object"));
|
|
107
95
|
} else if (optionalPath.isOptionalCallExpression()) {
|
|
108
96
|
optionalPath.node.type = "CallExpression";
|
|
109
|
-
optionalPath =
|
|
97
|
+
optionalPath = skipTransparentExprWrappers(optionalPath.get("callee"));
|
|
110
98
|
}
|
|
111
99
|
}
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
operator: "delete"
|
|
115
|
-
})) {
|
|
116
|
-
replacementPath = parentPath;
|
|
117
|
-
isDeleteOperation = true;
|
|
100
|
+
if (optionals.length === 0) {
|
|
101
|
+
return;
|
|
118
102
|
}
|
|
103
|
+
const checks = [];
|
|
104
|
+
let tmpVar;
|
|
119
105
|
for (let i = optionals.length - 1; i >= 0; i--) {
|
|
120
106
|
const node = optionals[i];
|
|
121
|
-
const isCall =
|
|
107
|
+
const isCall = types.isCallExpression(node);
|
|
122
108
|
const chainWithTypes = isCall ? node.callee : node.object;
|
|
123
|
-
const chain =
|
|
109
|
+
const chain = skipTransparentExprWrapperNodes(chainWithTypes);
|
|
124
110
|
let ref;
|
|
125
111
|
let check;
|
|
126
|
-
if (isCall &&
|
|
112
|
+
if (isCall && types.isIdentifier(chain, {
|
|
127
113
|
name: "eval"
|
|
128
114
|
})) {
|
|
129
115
|
check = ref = chain;
|
|
130
|
-
node.callee =
|
|
116
|
+
node.callee = types.sequenceExpression([types.numericLiteral(0), ref]);
|
|
131
117
|
} else if (pureGetters && isCall && isSimpleMemberExpression(chain)) {
|
|
132
118
|
check = ref = node.callee;
|
|
119
|
+
} else if (scope.isStatic(chain)) {
|
|
120
|
+
check = ref = chainWithTypes;
|
|
133
121
|
} else {
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
check = ref = chainWithTypes;
|
|
122
|
+
if (!tmpVar || isCall) {
|
|
123
|
+
tmpVar = scope.generateUidIdentifierBasedOnNode(chain);
|
|
124
|
+
scope.push({
|
|
125
|
+
id: types.cloneNode(tmpVar)
|
|
126
|
+
});
|
|
140
127
|
}
|
|
128
|
+
ref = tmpVar;
|
|
129
|
+
check = types.assignmentExpression("=", types.cloneNode(tmpVar), chainWithTypes);
|
|
130
|
+
isCall ? node.callee = ref : node.object = ref;
|
|
141
131
|
}
|
|
142
|
-
if (isCall &&
|
|
132
|
+
if (isCall && types.isMemberExpression(chain)) {
|
|
143
133
|
if (pureGetters && isSimpleMemberExpression(chain)) {
|
|
144
134
|
node.callee = chainWithTypes;
|
|
145
135
|
} else {
|
|
@@ -147,57 +137,79 @@ function transform(path, {
|
|
|
147
137
|
object
|
|
148
138
|
} = chain;
|
|
149
139
|
let context;
|
|
150
|
-
if (
|
|
151
|
-
context =
|
|
140
|
+
if (types.isSuper(object)) {
|
|
141
|
+
context = types.thisExpression();
|
|
152
142
|
} else {
|
|
153
143
|
const memoized = scope.maybeGenerateMemoised(object);
|
|
154
144
|
if (memoized) {
|
|
155
145
|
context = memoized;
|
|
156
|
-
chain.object =
|
|
146
|
+
chain.object = types.assignmentExpression("=", memoized, object);
|
|
157
147
|
} else {
|
|
158
148
|
context = object;
|
|
159
149
|
}
|
|
160
150
|
}
|
|
161
|
-
node.arguments.unshift(
|
|
162
|
-
node.callee =
|
|
151
|
+
node.arguments.unshift(types.cloneNode(context));
|
|
152
|
+
node.callee = types.memberExpression(node.callee, types.identifier("call"));
|
|
163
153
|
}
|
|
164
154
|
}
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
155
|
+
const data = {
|
|
156
|
+
check: types.cloneNode(check),
|
|
157
|
+
ref: types.cloneNode(ref)
|
|
158
|
+
};
|
|
159
|
+
Object.defineProperty(data, "ref", {
|
|
160
|
+
enumerable: false
|
|
161
|
+
});
|
|
162
|
+
checks.push(data);
|
|
163
|
+
}
|
|
164
|
+
let result = replacementPath.node;
|
|
165
|
+
if (wrapLast) result = wrapLast(result);
|
|
166
|
+
const ifNullishBoolean = types.isBooleanLiteral(ifNullish);
|
|
167
|
+
const ifNullishFalse = ifNullishBoolean && ifNullish.value === false;
|
|
168
|
+
const tpl = ifNullishFalse ? noDocumentAll ? NULLISH_CHECK_NO_DDA_NEG : NULLISH_CHECK_NEG : noDocumentAll ? NULLISH_CHECK_NO_DDA : NULLISH_CHECK;
|
|
169
|
+
const logicalOp = ifNullishFalse ? "&&" : "||";
|
|
170
|
+
const check = checks.map(tpl).reduce((expr, check) => types.logicalExpression(logicalOp, expr, check));
|
|
171
|
+
replacementPath.replaceWith(ifNullishBoolean ? types.logicalExpression(logicalOp, check, result) : types.conditionalExpression(check, ifNullish, result));
|
|
172
|
+
}
|
|
173
|
+
function transform(path, assumptions) {
|
|
174
|
+
const {
|
|
175
|
+
scope
|
|
176
|
+
} = path;
|
|
177
|
+
const maybeWrapped = findOutermostTransparentParent(path);
|
|
178
|
+
const {
|
|
179
|
+
parentPath
|
|
180
|
+
} = maybeWrapped;
|
|
181
|
+
if (parentPath.isUnaryExpression({
|
|
182
|
+
operator: "delete"
|
|
183
|
+
})) {
|
|
184
|
+
transformOptionalChain(path, assumptions, parentPath, types.booleanLiteral(true));
|
|
185
|
+
} else {
|
|
186
|
+
let wrapLast;
|
|
187
|
+
if (parentPath.isCallExpression({
|
|
188
|
+
callee: maybeWrapped.node
|
|
189
|
+
}) && path.isOptionalMemberExpression()) {
|
|
190
|
+
wrapLast = replacement => {
|
|
191
|
+
const object = skipTransparentExprWrapperNodes(replacement.object);
|
|
192
|
+
let baseRef;
|
|
193
|
+
if (!assumptions.pureGetters || !isSimpleMemberExpression(object)) {
|
|
194
|
+
baseRef = scope.maybeGenerateMemoised(object);
|
|
195
|
+
if (baseRef) {
|
|
196
|
+
replacement.object = types.assignmentExpression("=", baseRef, object);
|
|
197
|
+
}
|
|
174
198
|
}
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
}
|
|
178
|
-
if (willReplacementCastToBoolean) {
|
|
179
|
-
const nonNullishCheck = noDocumentAll ? ast`${core.types.cloneNode(check)} != null` : ast`
|
|
180
|
-
${core.types.cloneNode(check)} !== null && ${core.types.cloneNode(ref)} !== void 0`;
|
|
181
|
-
replacementPath.replaceWith(core.types.logicalExpression("&&", nonNullishCheck, replacement));
|
|
182
|
-
replacementPath = helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers(replacementPath.get("right"));
|
|
183
|
-
} else {
|
|
184
|
-
const nullishCheck = noDocumentAll ? ast`${core.types.cloneNode(check)} == null` : ast`
|
|
185
|
-
${core.types.cloneNode(check)} === null || ${core.types.cloneNode(ref)} === void 0`;
|
|
186
|
-
const returnValue = isDeleteOperation ? ast`true` : ast`void 0`;
|
|
187
|
-
replacementPath.replaceWith(core.types.conditionalExpression(nullishCheck, returnValue, replacement));
|
|
188
|
-
replacementPath = helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers(replacementPath.get("alternate"));
|
|
199
|
+
return types.callExpression(types.memberExpression(replacement, types.identifier("bind")), [types.cloneNode(baseRef ?? object)]);
|
|
200
|
+
};
|
|
189
201
|
}
|
|
202
|
+
transformOptionalChain(path, assumptions, path, willPathCastToBoolean(maybeWrapped) ? types.booleanLiteral(false) : scope.buildUndefinedNode(), wrapLast);
|
|
190
203
|
}
|
|
191
204
|
}
|
|
192
205
|
|
|
193
|
-
var index =
|
|
194
|
-
var _api$assumption, _api$assumption2;
|
|
206
|
+
var index = declare((api, options) => {
|
|
195
207
|
api.assertVersion(7);
|
|
196
208
|
const {
|
|
197
209
|
loose = false
|
|
198
210
|
} = options;
|
|
199
|
-
const noDocumentAll =
|
|
200
|
-
const pureGetters =
|
|
211
|
+
const noDocumentAll = api.assumption("noDocumentAll") ?? loose;
|
|
212
|
+
const pureGetters = api.assumption("pureGetters") ?? loose;
|
|
201
213
|
return {
|
|
202
214
|
name: "transform-optional-chaining",
|
|
203
215
|
inherits: syntaxOptionalChaining.default,
|
|
@@ -212,6 +224,5 @@ var index = helperPluginUtils.declare((api, options) => {
|
|
|
212
224
|
};
|
|
213
225
|
});
|
|
214
226
|
|
|
215
|
-
|
|
216
|
-
exports.transform = transform;
|
|
227
|
+
export { index as default, transform };
|
|
217
228
|
//# sourceMappingURL=index.js.map
|
package/lib/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/util.ts","../src/transform.ts","../src/index.ts"],"sourcesContent":["import type { NodePath } from \"@babel/traverse\";\nimport { isTransparentExprWrapper } from \"@babel/helper-skip-transparent-expression-wrappers\";\n/**\n * Test if a NodePath will be cast to boolean when evaluated.\n * It respects transparent expression wrappers defined in\n * \"@babel/helper-skip-transparent-expression-wrappers\"\n *\n * @example\n * // returns true\n * const nodePathADotB = NodePath(\"if (a.b) {}\").get(\"test\"); // a.b\n * willPathCastToBoolean(nodePathADotB)\n * @example\n * // returns false\n * willPathCastToBoolean(NodePath(\"a.b\"))\n * @param {NodePath} path\n * @returns {boolean}\n */\nexport function willPathCastToBoolean(path: NodePath): boolean {\n const maybeWrapped = findOutermostTransparentParent(path);\n const { node, parentPath } = maybeWrapped;\n if (parentPath.isLogicalExpression()) {\n const { operator, right } = parentPath.node;\n if (\n operator === \"&&\" ||\n operator === \"||\" ||\n (operator === \"??\" && node === right)\n ) {\n return willPathCastToBoolean(parentPath);\n }\n }\n if (parentPath.isSequenceExpression()) {\n const { expressions } = parentPath.node;\n if (expressions[expressions.length - 1] === node) {\n return willPathCastToBoolean(parentPath);\n } else {\n // if it is in the middle of a sequence expression, we don't\n // care the return value so just cast to boolean for smaller\n // output\n return true;\n }\n }\n return (\n parentPath.isConditional({ test: node }) ||\n parentPath.isUnaryExpression({ operator: \"!\" }) ||\n parentPath.isLoop({ test: node })\n );\n}\n\n/**\n * Return the outermost transparent expression wrapper of a given path,\n * otherwise returns path itself.\n * @example\n * const nodePathADotB = NodePath(\"(a.b as any)\").get(\"expression\"); // a.b\n * // returns NodePath(\"(a.b as any)\")\n * findOutermostTransparentParent(nodePathADotB);\n * @param {NodePath} path\n * @returns {NodePath}\n */\nexport function findOutermostTransparentParent(path: NodePath): NodePath {\n let maybeWrapped = path;\n path.findParent(p => {\n if (!isTransparentExprWrapper(p.node)) return true;\n maybeWrapped = p;\n });\n return maybeWrapped;\n}\n","import { types as t, template } from \"@babel/core\";\nimport type { NodePath } from \"@babel/traverse\";\nimport {\n skipTransparentExprWrapperNodes,\n skipTransparentExprWrappers,\n} from \"@babel/helper-skip-transparent-expression-wrappers\";\nimport { willPathCastToBoolean, findOutermostTransparentParent } from \"./util\";\n\nconst { ast } = template.expression;\n\nfunction isSimpleMemberExpression(\n expression: t.Expression | t.Super,\n): expression is t.Identifier | t.Super | t.MemberExpression {\n expression = skipTransparentExprWrapperNodes(expression);\n return (\n t.isIdentifier(expression) ||\n t.isSuper(expression) ||\n (t.isMemberExpression(expression) &&\n !expression.computed &&\n isSimpleMemberExpression(expression.object))\n );\n}\n\n/**\n * Test if a given optional chain `path` needs to be memoized\n * @param {NodePath} path\n * @returns {boolean}\n */\nfunction needsMemoize(\n path: NodePath<t.OptionalCallExpression | t.OptionalMemberExpression>,\n) {\n let optionalPath: NodePath = path;\n const { scope } = path;\n while (\n optionalPath.isOptionalMemberExpression() ||\n optionalPath.isOptionalCallExpression()\n ) {\n const { node } = optionalPath;\n const childPath = skipTransparentExprWrappers(\n // @ts-expect-error isOptionalMemberExpression does not work with NodePath union\n optionalPath.isOptionalMemberExpression()\n ? optionalPath.get(\"object\")\n : optionalPath.get(\"callee\"),\n );\n if (node.optional) {\n return !scope.isStatic(childPath.node);\n }\n\n optionalPath = childPath;\n }\n}\n\nexport function transform(\n path: NodePath<t.OptionalCallExpression | t.OptionalMemberExpression>,\n {\n pureGetters,\n noDocumentAll,\n }: { pureGetters: boolean; noDocumentAll: boolean },\n) {\n const { scope } = path;\n // maybeWrapped points to the outermost transparent expression wrapper\n // or the path itself\n const maybeWrapped = findOutermostTransparentParent(path);\n const { parentPath } = maybeWrapped;\n const willReplacementCastToBoolean = willPathCastToBoolean(maybeWrapped);\n let isDeleteOperation = false;\n const parentIsCall =\n parentPath.isCallExpression({ callee: maybeWrapped.node }) &&\n // note that the first condition must implies that `path.optional` is `true`,\n // otherwise the parentPath should be an OptionalCallExpression\n path.isOptionalMemberExpression();\n\n const optionals = [];\n\n let optionalPath = path;\n // Replace `function (a, x = a.b?.c) {}` to `function (a, x = (() => a.b?.c)() ){}`\n // so the temporary variable can be injected in correct scope\n if (scope.path.isPattern() && needsMemoize(optionalPath)) {\n path.replaceWith(template.ast`(() => ${path.node})()` as t.Statement);\n // The injected optional chain will be queued and eventually transformed when visited\n return;\n }\n while (\n optionalPath.isOptionalMemberExpression() ||\n optionalPath.isOptionalCallExpression()\n ) {\n const { node } = optionalPath;\n if (node.optional) {\n optionals.push(node);\n }\n // @ts-expect-error isOptionalMemberExpression does not work with NodePath union\n if (optionalPath.isOptionalMemberExpression()) {\n // @ts-expect-error todo(flow->ts) avoid changing more type\n optionalPath.node.type = \"MemberExpression\";\n // @ts-expect-error todo(flow->ts)\n optionalPath = skipTransparentExprWrappers(optionalPath.get(\"object\"));\n } else if (optionalPath.isOptionalCallExpression()) {\n // @ts-expect-error todo(flow->ts) avoid changing more type\n optionalPath.node.type = \"CallExpression\";\n // @ts-expect-error todo(flow->ts)\n optionalPath = skipTransparentExprWrappers(optionalPath.get(\"callee\"));\n }\n }\n\n // todo: Improve replacementPath typings\n let replacementPath: NodePath<any> = path;\n if (parentPath.isUnaryExpression({ operator: \"delete\" })) {\n replacementPath = parentPath;\n isDeleteOperation = true;\n }\n for (let i = optionals.length - 1; i >= 0; i--) {\n const node = optionals[i] as unknown as\n | t.MemberExpression\n | t.CallExpression;\n\n const isCall = t.isCallExpression(node);\n\n const chainWithTypes = isCall\n ? // V8 intrinsics must not be an optional call\n (node.callee as t.Expression)\n : node.object;\n const chain = skipTransparentExprWrapperNodes(chainWithTypes);\n\n let ref;\n let check;\n if (isCall && t.isIdentifier(chain, { name: \"eval\" })) {\n check = ref = chain;\n // `eval?.()` is an indirect eval call transformed to `(0,eval)()`\n node.callee = t.sequenceExpression([t.numericLiteral(0), ref]);\n } else if (pureGetters && isCall && isSimpleMemberExpression(chain)) {\n // If we assume getters are pure (avoiding a Function#call) and we are at the call,\n // we can avoid a needless memoize. We only do this if the callee is a simple member\n // expression, to avoid multiple calls to nested call expressions.\n check = ref = node.callee;\n } else {\n ref = scope.maybeGenerateMemoised(chain);\n if (ref) {\n check = t.assignmentExpression(\n \"=\",\n t.cloneNode(ref),\n // Here `chainWithTypes` MUST NOT be cloned because it could be\n // updated when generating the memoised context of a call\n // expression. It must be an Expression when `ref` is an identifier\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n chainWithTypes as t.Expression,\n );\n\n isCall ? (node.callee = ref) : (node.object = ref);\n } else {\n check = ref = chainWithTypes;\n }\n }\n\n // Ensure call expressions have the proper `this`\n // `foo.bar()` has context `foo`.\n if (isCall && t.isMemberExpression(chain)) {\n if (pureGetters && isSimpleMemberExpression(chain)) {\n // To avoid a Function#call, we can instead re-grab the property from the context object.\n // `a.?b.?()` translates roughly to `_a.b != null && _a.b()`\n node.callee = chainWithTypes;\n } else {\n // Otherwise, we need to memoize the context object, and change the call into a Function#call.\n // `a.?b.?()` translates roughly to `(_b = _a.b) != null && _b.call(_a)`\n const { object } = chain;\n let context: t.Expression;\n if (t.isSuper(object)) {\n context = t.thisExpression();\n } else {\n const memoized = scope.maybeGenerateMemoised(object);\n if (memoized) {\n context = memoized;\n chain.object = t.assignmentExpression(\"=\", memoized, object);\n } else {\n context = object;\n }\n }\n\n node.arguments.unshift(t.cloneNode(context));\n // @ts-expect-error node.callee can not be an V8IntrinsicIdentifier: V8 intrinsic is disallowed in optional chain\n node.callee = t.memberExpression(node.callee, t.identifier(\"call\"));\n }\n }\n let replacement = replacementPath.node;\n // Ensure (a?.b)() has proper `this`\n // The `parentIsCall` is constant within loop, we should check i === 0\n // to ensure that it is only applied to the first optional chain element\n // i.e. `?.b` in `(a?.b.c)()`\n if (i === 0 && parentIsCall) {\n // `(a?.b)()` to `(a == null ? undefined : a.b.bind(a))()`\n // object must not be Super as super?.foo is invalid\n const object = skipTransparentExprWrapperNodes(\n replacement.object,\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n ) as any as t.Expression;\n let baseRef;\n if (!pureGetters || !isSimpleMemberExpression(object)) {\n // memoize the context object when getters are not always pure\n // or the object is not a simple member expression\n // `(a?.b.c)()` to `(a == null ? undefined : (_a$b = a.b).c.bind(_a$b))()`\n baseRef = scope.maybeGenerateMemoised(object);\n if (baseRef) {\n replacement.object = t.assignmentExpression(\"=\", baseRef, object);\n }\n }\n replacement = t.callExpression(\n t.memberExpression(replacement, t.identifier(\"bind\")),\n [t.cloneNode(baseRef ?? object)],\n );\n }\n\n if (willReplacementCastToBoolean) {\n // `if (a?.b) {}` transformed to `if (a != null && a.b) {}`\n // we don't need to return `void 0` because the returned value will\n // eventually cast to boolean.\n const nonNullishCheck = noDocumentAll\n ? ast`${t.cloneNode(check)} != null`\n : ast`\n ${t.cloneNode(check)} !== null && ${t.cloneNode(ref)} !== void 0`;\n replacementPath.replaceWith(\n t.logicalExpression(\"&&\", nonNullishCheck, replacement),\n );\n replacementPath = skipTransparentExprWrappers(\n // @ts-expect-error todo(flow->ts)\n replacementPath.get(\"right\"),\n );\n } else {\n const nullishCheck = noDocumentAll\n ? ast`${t.cloneNode(check)} == null`\n : ast`\n ${t.cloneNode(check)} === null || ${t.cloneNode(ref)} === void 0`;\n\n const returnValue = isDeleteOperation ? ast`true` : ast`void 0`;\n replacementPath.replaceWith(\n t.conditionalExpression(nullishCheck, returnValue, replacement),\n );\n replacementPath = skipTransparentExprWrappers(\n // @ts-expect-error todo(flow->ts)\n replacementPath.get(\"alternate\"),\n );\n }\n }\n}\n","import { declare } from \"@babel/helper-plugin-utils\";\nimport syntaxOptionalChaining from \"@babel/plugin-syntax-optional-chaining\";\nimport { transform } from \"./transform\";\nimport type { NodePath } from \"@babel/traverse\";\nimport type * as t from \"@babel/types\";\n\nexport interface Options {\n loose?: boolean;\n}\nexport default declare((api, options: Options) => {\n api.assertVersion(7);\n\n const { loose = false } = options;\n const noDocumentAll = api.assumption(\"noDocumentAll\") ?? loose;\n const pureGetters = api.assumption(\"pureGetters\") ?? loose;\n\n return {\n name: \"transform-optional-chaining\",\n inherits: syntaxOptionalChaining.default,\n\n visitor: {\n \"OptionalCallExpression|OptionalMemberExpression\"(\n path: NodePath<t.OptionalCallExpression | t.OptionalMemberExpression>,\n ) {\n transform(path, { noDocumentAll, pureGetters });\n },\n },\n };\n});\n\nexport { transform };\n"],"names":["willPathCastToBoolean","path","maybeWrapped","findOutermostTransparentParent","node","parentPath","isLogicalExpression","operator","right","isSequenceExpression","expressions","length","isConditional","test","isUnaryExpression","isLoop","findParent","p","isTransparentExprWrapper","ast","template","expression","isSimpleMemberExpression","skipTransparentExprWrapperNodes","t","isIdentifier","isSuper","isMemberExpression","computed","object","needsMemoize","optionalPath","scope","isOptionalMemberExpression","isOptionalCallExpression","childPath","skipTransparentExprWrappers","get","optional","isStatic","transform","pureGetters","noDocumentAll","willReplacementCastToBoolean","isDeleteOperation","parentIsCall","isCallExpression","callee","optionals","isPattern","replaceWith","push","type","replacementPath","i","isCall","chainWithTypes","chain","ref","check","name","sequenceExpression","numericLiteral","maybeGenerateMemoised","assignmentExpression","cloneNode","context","thisExpression","memoized","arguments","unshift","memberExpression","identifier","replacement","_baseRef","baseRef","callExpression","nonNullishCheck","logicalExpression","nullishCheck","returnValue","conditionalExpression","declare","api","options","_api$assumption","_api$assumption2","assertVersion","loose","assumption","inherits","syntaxOptionalChaining","default","visitor","OptionalCallExpression|OptionalMemberExpression"],"mappings":";;;;;;;;;AAiBO,SAASA,qBAAqBA,CAACC,IAAc,EAAW;AAC7D,EAAA,MAAMC,YAAY,GAAGC,8BAA8B,CAACF,IAAI,CAAC,CAAA;EACzD,MAAM;IAAEG,IAAI;AAAEC,IAAAA,UAAAA;AAAW,GAAC,GAAGH,YAAY,CAAA;AACzC,EAAA,IAAIG,UAAU,CAACC,mBAAmB,EAAE,EAAE;IACpC,MAAM;MAAEC,QAAQ;AAAEC,MAAAA,KAAAA;KAAO,GAAGH,UAAU,CAACD,IAAI,CAAA;AAC3C,IAAA,IACEG,QAAQ,KAAK,IAAI,IACjBA,QAAQ,KAAK,IAAI,IAChBA,QAAQ,KAAK,IAAI,IAAIH,IAAI,KAAKI,KAAM,EACrC;MACA,OAAOR,qBAAqB,CAACK,UAAU,CAAC,CAAA;AAC1C,KAAA;AACF,GAAA;AACA,EAAA,IAAIA,UAAU,CAACI,oBAAoB,EAAE,EAAE;IACrC,MAAM;AAA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AAC,KAAAJ,IAAAA,GAAAA,eAAA,GAAIG,KAAK,CAAA;AAC9D,EAAA,MAAM/C,WAAW,GAAA,CAAA6C,gBAAA,GAAGH,GAAG,CAACM,UAAU,CAAC,aAAa,CAAC,KAAAH,IAAAA,GAAAA,gBAAA,GAAIE,KAAK,CAAA;EAE1D,OAAO;AACL5B,IAAAA,IAAI,EAAE,6BAA6B;IACnC8B,QAAQ,EAAEC,sBAAsB,CAACC,OAAO;AAExCC,IAAAA,OAAO,EAAE;MACP,iDAAiDC,CAC/C7F,IAAqE,EACrE;QACAuC,SAAS,CAACvC,IAAI,EAAE;UAAEyC,aAAa;AAAED,UAAAA,WAAAA;AAAY,SAAC,CAAC,CAAA;AACjD,OAAA;AACF,KAAA;GACD,CAAA;AACH,CAAC,CAAC;;;;;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/util.ts","../src/transform.ts","../src/index.ts"],"sourcesContent":["import type { NodePath } from \"@babel/traverse\";\nimport { isTransparentExprWrapper } from \"@babel/helper-skip-transparent-expression-wrappers\";\n/**\n * Test if a NodePath will be cast to boolean when evaluated.\n * It respects transparent expression wrappers defined in\n * \"@babel/helper-skip-transparent-expression-wrappers\"\n *\n * @example\n * // returns true\n * const nodePathADotB = NodePath(\"if (a.b) {}\").get(\"test\"); // a.b\n * willPathCastToBoolean(nodePathADotB)\n * @example\n * // returns false\n * willPathCastToBoolean(NodePath(\"a.b\"))\n * @param {NodePath} path\n * @returns {boolean}\n */\nexport function willPathCastToBoolean(path: NodePath): boolean {\n const maybeWrapped = findOutermostTransparentParent(path);\n const { node, parentPath } = maybeWrapped;\n if (parentPath.isLogicalExpression()) {\n const { operator, right } = parentPath.node;\n if (\n operator === \"&&\" ||\n operator === \"||\" ||\n (operator === \"??\" && node === right)\n ) {\n return willPathCastToBoolean(parentPath);\n }\n }\n if (parentPath.isSequenceExpression()) {\n const { expressions } = parentPath.node;\n if (expressions[expressions.length - 1] === node) {\n return willPathCastToBoolean(parentPath);\n } else {\n // if it is in the middle of a sequence expression, we don't\n // care the return value so just cast to boolean for smaller\n // output\n return true;\n }\n }\n return (\n parentPath.isConditional({ test: node }) ||\n parentPath.isUnaryExpression({ operator: \"!\" }) ||\n parentPath.isLoop({ test: node })\n );\n}\n\n/**\n * Return the outermost transparent expression wrapper of a given path,\n * otherwise returns path itself.\n * @example\n * const nodePathADotB = NodePath(\"(a.b as any)\").get(\"expression\"); // a.b\n * // returns NodePath(\"(a.b as any)\")\n * findOutermostTransparentParent(nodePathADotB);\n * @param {NodePath} path\n * @returns {NodePath}\n */\nexport function findOutermostTransparentParent(path: NodePath): NodePath {\n let maybeWrapped = path;\n path.findParent(p => {\n if (!isTransparentExprWrapper(p.node)) return true;\n maybeWrapped = p;\n });\n return maybeWrapped;\n}\n","import { types as t, template } from \"@babel/core\";\nimport type { NodePath } from \"@babel/traverse\";\nimport {\n skipTransparentExprWrapperNodes,\n skipTransparentExprWrappers,\n} from \"@babel/helper-skip-transparent-expression-wrappers\";\nimport { willPathCastToBoolean, findOutermostTransparentParent } from \"./util\";\n\nfunction isSimpleMemberExpression(\n expression: t.Expression | t.Super,\n): expression is t.Identifier | t.Super | t.MemberExpression {\n expression = skipTransparentExprWrapperNodes(expression);\n return (\n t.isIdentifier(expression) ||\n t.isSuper(expression) ||\n (t.isMemberExpression(expression) &&\n !expression.computed &&\n isSimpleMemberExpression(expression.object))\n );\n}\n\n/**\n * Test if a given optional chain `path` needs to be memoized\n * @param {NodePath} path\n * @returns {boolean}\n */\nfunction needsMemoize(\n path: NodePath<t.OptionalCallExpression | t.OptionalMemberExpression>,\n) {\n let optionalPath: NodePath = path;\n const { scope } = path;\n while (\n optionalPath.isOptionalMemberExpression() ||\n optionalPath.isOptionalCallExpression()\n ) {\n const { node } = optionalPath;\n const childPath = skipTransparentExprWrappers(\n // @ts-expect-error isOptionalMemberExpression does not work with NodePath union\n optionalPath.isOptionalMemberExpression()\n ? optionalPath.get(\"object\")\n : optionalPath.get(\"callee\"),\n );\n if (node.optional) {\n return !scope.isStatic(childPath.node);\n }\n\n optionalPath = childPath;\n }\n}\n\nconst NULLISH_CHECK = template.expression(\n `%%check%% === null || %%ref%% === void 0`,\n);\nconst NULLISH_CHECK_NO_DDA = template.expression(`%%check%% == null`);\nconst NULLISH_CHECK_NEG = template.expression(\n `%%check%% !== null && %%ref%% !== void 0`,\n);\nconst NULLISH_CHECK_NO_DDA_NEG = template.expression(`%%check%% != null`);\n\ninterface OptionalChainAssumptions {\n pureGetters: boolean;\n noDocumentAll: boolean;\n}\n\nexport function transformOptionalChain(\n path: NodePath<t.OptionalCallExpression | t.OptionalMemberExpression>,\n { pureGetters, noDocumentAll }: OptionalChainAssumptions,\n replacementPath: NodePath<t.Expression>,\n ifNullish: t.Expression,\n wrapLast?: (value: t.Expression) => t.Expression,\n) {\n const { scope } = path;\n\n // Replace `function (a, x = a.b?.c) {}` to `function (a, x = (() => a.b?.c)() ){}`\n // so the temporary variable can be injected in correct scope\n if (scope.path.isPattern() && needsMemoize(path)) {\n replacementPath.replaceWith(\n template.expression.ast`(() => ${replacementPath.node})()`,\n );\n // The injected optional chain will be queued and eventually transformed when visited\n return;\n }\n\n const optionals = [];\n\n let optionalPath = path;\n while (\n optionalPath.isOptionalMemberExpression() ||\n optionalPath.isOptionalCallExpression()\n ) {\n const { node } = optionalPath;\n if (node.optional) {\n optionals.push(node);\n }\n // @ts-expect-error isOptionalMemberExpression does not work with NodePath union\n if (optionalPath.isOptionalMemberExpression()) {\n // @ts-expect-error todo(flow->ts) avoid changing more type\n optionalPath.node.type = \"MemberExpression\";\n // @ts-expect-error todo(flow->ts)\n optionalPath = skipTransparentExprWrappers(optionalPath.get(\"object\"));\n } else if (optionalPath.isOptionalCallExpression()) {\n // @ts-expect-error todo(flow->ts) avoid changing more type\n optionalPath.node.type = \"CallExpression\";\n // @ts-expect-error todo(flow->ts)\n optionalPath = skipTransparentExprWrappers(optionalPath.get(\"callee\"));\n }\n }\n\n if (optionals.length === 0) {\n // Malformed AST: there was an OptionalMemberExpression node\n // with no actual optional elements.\n return;\n }\n\n const checks = [];\n\n let tmpVar;\n\n for (let i = optionals.length - 1; i >= 0; i--) {\n const node = optionals[i] as unknown as\n | t.MemberExpression\n | t.CallExpression;\n\n const isCall = t.isCallExpression(node);\n\n const chainWithTypes = isCall\n ? // V8 intrinsics must not be an optional call\n (node.callee as t.Expression)\n : node.object;\n const chain = skipTransparentExprWrapperNodes(chainWithTypes);\n\n let ref;\n let check;\n if (isCall && t.isIdentifier(chain, { name: \"eval\" })) {\n check = ref = chain;\n // `eval?.()` is an indirect eval call transformed to `(0,eval)()`\n node.callee = t.sequenceExpression([t.numericLiteral(0), ref]);\n } else if (pureGetters && isCall && isSimpleMemberExpression(chain)) {\n // If we assume getters are pure (avoiding a Function#call) and we are at the call,\n // we can avoid a needless memoize. We only do this if the callee is a simple member\n // expression, to avoid multiple calls to nested call expressions.\n check = ref = node.callee;\n } else if (scope.isStatic(chain)) {\n check = ref = chainWithTypes;\n } else {\n // We cannot reuse the tmpVar for calls, because we need to\n // store both the method and the receiver.\n if (!tmpVar || isCall) {\n tmpVar = scope.generateUidIdentifierBasedOnNode(chain);\n scope.push({ id: t.cloneNode(tmpVar) });\n }\n ref = tmpVar;\n check = t.assignmentExpression(\n \"=\",\n t.cloneNode(tmpVar),\n // Here `chainWithTypes` MUST NOT be cloned because it could be\n // updated when generating the memoised context of a call\n // expression. It must be an Expression when `ref` is an identifier\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n chainWithTypes as t.Expression,\n );\n\n isCall ? (node.callee = ref) : (node.object = ref);\n }\n\n // Ensure call expressions have the proper `this`\n // `foo.bar()` has context `foo`.\n if (isCall && t.isMemberExpression(chain)) {\n if (pureGetters && isSimpleMemberExpression(chain)) {\n // To avoid a Function#call, we can instead re-grab the property from the context object.\n // `a.?b.?()` translates roughly to `_a.b != null && _a.b()`\n node.callee = chainWithTypes;\n } else {\n // Otherwise, we need to memoize the context object, and change the call into a Function#call.\n // `a.?b.?()` translates roughly to `(_b = _a.b) != null && _b.call(_a)`\n const { object } = chain;\n let context: t.Expression;\n if (t.isSuper(object)) {\n context = t.thisExpression();\n } else {\n const memoized = scope.maybeGenerateMemoised(object);\n if (memoized) {\n context = memoized;\n chain.object = t.assignmentExpression(\"=\", memoized, object);\n } else {\n context = object;\n }\n }\n\n node.arguments.unshift(t.cloneNode(context));\n // @ts-expect-error node.callee can not be an V8IntrinsicIdentifier: V8 intrinsic is disallowed in optional chain\n node.callee = t.memberExpression(node.callee, t.identifier(\"call\"));\n }\n }\n\n const data = { check: t.cloneNode(check), ref: t.cloneNode(ref) };\n // We make `ref` non-enumerable, so that @babel/template doesn't throw\n // in the noDocumentAll template if it's not used.\n Object.defineProperty(data, \"ref\", { enumerable: false });\n checks.push(data);\n }\n\n let result = replacementPath.node;\n if (wrapLast) result = wrapLast(result);\n\n const ifNullishBoolean = t.isBooleanLiteral(ifNullish);\n const ifNullishFalse = ifNullishBoolean && ifNullish.value === false;\n\n // prettier-ignore\n const tpl = ifNullishFalse\n ? (noDocumentAll ? NULLISH_CHECK_NO_DDA_NEG : NULLISH_CHECK_NEG)\n : (noDocumentAll ? NULLISH_CHECK_NO_DDA : NULLISH_CHECK);\n const logicalOp = ifNullishFalse ? \"&&\" : \"||\";\n\n const check = checks\n .map(tpl)\n .reduce((expr, check) => t.logicalExpression(logicalOp, expr, check));\n\n replacementPath.replaceWith(\n ifNullishBoolean\n ? t.logicalExpression(logicalOp, check, result)\n : t.conditionalExpression(check, ifNullish, result),\n );\n}\n\nexport function transform(\n path: NodePath<t.OptionalCallExpression | t.OptionalMemberExpression>,\n assumptions: OptionalChainAssumptions,\n) {\n const { scope } = path;\n\n // maybeWrapped points to the outermost transparent expression wrapper\n // or the path itself\n const maybeWrapped = findOutermostTransparentParent(path);\n const { parentPath } = maybeWrapped;\n\n if (parentPath.isUnaryExpression({ operator: \"delete\" })) {\n transformOptionalChain(\n path,\n assumptions,\n parentPath,\n t.booleanLiteral(true),\n );\n } else {\n let wrapLast;\n if (\n parentPath.isCallExpression({ callee: maybeWrapped.node }) &&\n // note that the first condition must implies that `path.optional` is `true`,\n // otherwise the parentPath should be an OptionalCallExpression\n path.isOptionalMemberExpression()\n ) {\n // Ensure (a?.b)() has proper `this`\n wrapLast = (replacement: t.MemberExpression) => {\n // `(a?.b)()` to `(a == null ? undefined : a.b.bind(a))()`\n // object must not be Super as super?.foo is invalid\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n const object = skipTransparentExprWrapperNodes(\n replacement.object,\n ) as t.Expression;\n let baseRef: t.Expression;\n if (!assumptions.pureGetters || !isSimpleMemberExpression(object)) {\n // memoize the context object when getters are not always pure\n // or the object is not a simple member expression\n // `(a?.b.c)()` to `(a == null ? undefined : (_a$b = a.b).c.bind(_a$b))()`\n baseRef = scope.maybeGenerateMemoised(object);\n if (baseRef) {\n replacement.object = t.assignmentExpression(\"=\", baseRef, object);\n }\n }\n return t.callExpression(\n t.memberExpression(replacement, t.identifier(\"bind\")),\n [t.cloneNode(baseRef ?? object)],\n );\n };\n }\n\n transformOptionalChain(\n path,\n assumptions,\n path,\n willPathCastToBoolean(maybeWrapped)\n ? t.booleanLiteral(false)\n : scope.buildUndefinedNode(),\n wrapLast,\n );\n }\n}\n","import { declare } from \"@babel/helper-plugin-utils\";\nimport syntaxOptionalChaining from \"@babel/plugin-syntax-optional-chaining\";\nimport { transform } from \"./transform\";\nimport type { NodePath } from \"@babel/traverse\";\nimport type * as t from \"@babel/types\";\n\nexport interface Options {\n loose?: boolean;\n}\nexport default declare((api, options: Options) => {\n api.assertVersion(7);\n\n const { loose = false } = options;\n const noDocumentAll = api.assumption(\"noDocumentAll\") ?? loose;\n const pureGetters = api.assumption(\"pureGetters\") ?? loose;\n\n return {\n name: \"transform-optional-chaining\",\n inherits: syntaxOptionalChaining.default,\n\n visitor: {\n \"OptionalCallExpression|OptionalMemberExpression\"(\n path: NodePath<t.OptionalCallExpression | t.OptionalMemberExpression>,\n ) {\n transform(path, { noDocumentAll, pureGetters });\n },\n },\n };\n});\n\nexport { transform };\n"],"names":["willPathCastToBoolean","path","maybeWrapped","findOutermostTransparentParent","node","parentPath","isLogicalExpression","operator","right","isSequenceExpression","expressions","length","isConditional","test","isUnaryExpression","isLoop","findParent","p","isTransparentExprWrapper","isSimpleMemberExpression","expression","skipTransparentExprWrapperNodes","t","isIdentifier","isSuper","isMemberExpression","computed","object","needsMemoize","optionalPath","scope","isOptionalMemberExpression","isOptionalCallExpression","childPath","skipTransparentExprWrappers","get","optional","isStatic","NULLISH_CHECK","template","NULLISH_CHECK_NO_DDA","NULLISH_CHECK_NEG","NULLISH_CHECK_NO_DDA_NEG","transformOptionalChain","pureGetters","noDocumentAll","replacementPath","ifNullish","wrapLast","isPattern","replaceWith","ast","optionals","push","type","checks","tmpVar","i","isCall","isCallExpression","chainWithTypes","callee","chain","ref","check","name","sequenceExpression","numericLiteral","generateUidIdentifierBasedOnNode","id","cloneNode","assignmentExpression","context","thisExpression","memoized","maybeGenerateMemoised","arguments","unshift","memberExpression","identifier","data","Object","defineProperty","enumerable","result","ifNullishBoolean","isBooleanLiteral","ifNullishFalse","value","tpl","logicalOp","map","reduce","expr","logicalExpression","conditionalExpression","transform","assumptions","booleanLiteral","replacement","baseRef","callExpression","buildUndefinedNode","declare","api","options","assertVersion","loose","assumption","inherits","syntaxOptionalChaining","default","visitor","OptionalCallExpression|OptionalMemberExpression"],"mappings":";;;;;AAiBO,SAASA,qBAAqBA,CAACC,IAAc,EAAW;AAC7D,EAAA,MAAMC,YAAY,GAAGC,8BAA8B,CAACF,IAAI,CAAC,CAAA;EACzD,MAAM;IAAEG,IAAI;AAAEC,IAAAA,UAAAA;AAAW,GAAC,GAAGH,YAAY,CAAA;AACzC,EAAA,IAAIG,UAAU,CAACC,mBAAmB,EAAE,EAAE;IACpC,MAAM;MAAEC,QAAQ;AAAEC,MAAAA,KAAAA;KAAO,GAAGH,UAAU,CAACD,IAAI,CAAA;AAC3C,IAAA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,6BAA6B;IACnC4C,QAAQ,EAAEC,sBAAsB,CAACC,OAAO;AAExCC,IAAAA,OAAO,EAAE;MACP,iDAAiDC,CAC/ChH,IAAqE,EACrE;QACA+F,SAAS,CAAC/F,IAAI,EAAE;UAAE4C,aAAa;AAAED,UAAAA,WAAAA;AAAY,SAAC,CAAC,CAAA;AACjD,OAAA;AACF,KAAA;GACD,CAAA;AACH,CAAC,CAAC;;;;"}
|
package/lib/transform.js
CHANGED
|
@@ -1,18 +1,9 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
value: true
|
|
5
|
-
});
|
|
6
|
-
exports.transform = transform;
|
|
7
|
-
var _core = require("@babel/core");
|
|
8
|
-
var _helperSkipTransparentExpressionWrappers = require("@babel/helper-skip-transparent-expression-wrappers");
|
|
9
|
-
var _util = require("./util");
|
|
10
|
-
const {
|
|
11
|
-
ast
|
|
12
|
-
} = _core.template.expression;
|
|
1
|
+
import { types as t, template } from "@babel/core";
|
|
2
|
+
import { skipTransparentExprWrapperNodes, skipTransparentExprWrappers } from "@babel/helper-skip-transparent-expression-wrappers";
|
|
3
|
+
import { willPathCastToBoolean, findOutermostTransparentParent } from "./util.js";
|
|
13
4
|
function isSimpleMemberExpression(expression) {
|
|
14
|
-
expression =
|
|
15
|
-
return
|
|
5
|
+
expression = skipTransparentExprWrapperNodes(expression);
|
|
6
|
+
return t.isIdentifier(expression) || t.isSuper(expression) || t.isMemberExpression(expression) && !expression.computed && isSimpleMemberExpression(expression.object);
|
|
16
7
|
}
|
|
17
8
|
function needsMemoize(path) {
|
|
18
9
|
let optionalPath = path;
|
|
@@ -23,35 +14,30 @@ function needsMemoize(path) {
|
|
|
23
14
|
const {
|
|
24
15
|
node
|
|
25
16
|
} = optionalPath;
|
|
26
|
-
const childPath =
|
|
17
|
+
const childPath = skipTransparentExprWrappers(optionalPath.isOptionalMemberExpression() ? optionalPath.get("object") : optionalPath.get("callee"));
|
|
27
18
|
if (node.optional) {
|
|
28
19
|
return !scope.isStatic(childPath.node);
|
|
29
20
|
}
|
|
30
21
|
optionalPath = childPath;
|
|
31
22
|
}
|
|
32
23
|
}
|
|
33
|
-
|
|
24
|
+
const NULLISH_CHECK = template.expression(`%%check%% === null || %%ref%% === void 0`);
|
|
25
|
+
const NULLISH_CHECK_NO_DDA = template.expression(`%%check%% == null`);
|
|
26
|
+
const NULLISH_CHECK_NEG = template.expression(`%%check%% !== null && %%ref%% !== void 0`);
|
|
27
|
+
const NULLISH_CHECK_NO_DDA_NEG = template.expression(`%%check%% != null`);
|
|
28
|
+
export function transformOptionalChain(path, {
|
|
34
29
|
pureGetters,
|
|
35
30
|
noDocumentAll
|
|
36
|
-
}) {
|
|
31
|
+
}, replacementPath, ifNullish, wrapLast) {
|
|
37
32
|
const {
|
|
38
33
|
scope
|
|
39
34
|
} = path;
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
parentPath
|
|
43
|
-
} = maybeWrapped;
|
|
44
|
-
const willReplacementCastToBoolean = (0, _util.willPathCastToBoolean)(maybeWrapped);
|
|
45
|
-
let isDeleteOperation = false;
|
|
46
|
-
const parentIsCall = parentPath.isCallExpression({
|
|
47
|
-
callee: maybeWrapped.node
|
|
48
|
-
}) && path.isOptionalMemberExpression();
|
|
49
|
-
const optionals = [];
|
|
50
|
-
let optionalPath = path;
|
|
51
|
-
if (scope.path.isPattern() && needsMemoize(optionalPath)) {
|
|
52
|
-
path.replaceWith(_core.template.ast`(() => ${path.node})()`);
|
|
35
|
+
if (scope.path.isPattern() && needsMemoize(path)) {
|
|
36
|
+
replacementPath.replaceWith(template.expression.ast`(() => ${replacementPath.node})()`);
|
|
53
37
|
return;
|
|
54
38
|
}
|
|
39
|
+
const optionals = [];
|
|
40
|
+
let optionalPath = path;
|
|
55
41
|
while (optionalPath.isOptionalMemberExpression() || optionalPath.isOptionalCallExpression()) {
|
|
56
42
|
const {
|
|
57
43
|
node
|
|
@@ -61,43 +47,45 @@ function transform(path, {
|
|
|
61
47
|
}
|
|
62
48
|
if (optionalPath.isOptionalMemberExpression()) {
|
|
63
49
|
optionalPath.node.type = "MemberExpression";
|
|
64
|
-
optionalPath =
|
|
50
|
+
optionalPath = skipTransparentExprWrappers(optionalPath.get("object"));
|
|
65
51
|
} else if (optionalPath.isOptionalCallExpression()) {
|
|
66
52
|
optionalPath.node.type = "CallExpression";
|
|
67
|
-
optionalPath =
|
|
53
|
+
optionalPath = skipTransparentExprWrappers(optionalPath.get("callee"));
|
|
68
54
|
}
|
|
69
55
|
}
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
operator: "delete"
|
|
73
|
-
})) {
|
|
74
|
-
replacementPath = parentPath;
|
|
75
|
-
isDeleteOperation = true;
|
|
56
|
+
if (optionals.length === 0) {
|
|
57
|
+
return;
|
|
76
58
|
}
|
|
59
|
+
const checks = [];
|
|
60
|
+
let tmpVar;
|
|
77
61
|
for (let i = optionals.length - 1; i >= 0; i--) {
|
|
78
62
|
const node = optionals[i];
|
|
79
|
-
const isCall =
|
|
63
|
+
const isCall = t.isCallExpression(node);
|
|
80
64
|
const chainWithTypes = isCall ? node.callee : node.object;
|
|
81
|
-
const chain =
|
|
65
|
+
const chain = skipTransparentExprWrapperNodes(chainWithTypes);
|
|
82
66
|
let ref;
|
|
83
67
|
let check;
|
|
84
|
-
if (isCall &&
|
|
68
|
+
if (isCall && t.isIdentifier(chain, {
|
|
85
69
|
name: "eval"
|
|
86
70
|
})) {
|
|
87
71
|
check = ref = chain;
|
|
88
|
-
node.callee =
|
|
72
|
+
node.callee = t.sequenceExpression([t.numericLiteral(0), ref]);
|
|
89
73
|
} else if (pureGetters && isCall && isSimpleMemberExpression(chain)) {
|
|
90
74
|
check = ref = node.callee;
|
|
75
|
+
} else if (scope.isStatic(chain)) {
|
|
76
|
+
check = ref = chainWithTypes;
|
|
91
77
|
} else {
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
check = ref = chainWithTypes;
|
|
78
|
+
if (!tmpVar || isCall) {
|
|
79
|
+
tmpVar = scope.generateUidIdentifierBasedOnNode(chain);
|
|
80
|
+
scope.push({
|
|
81
|
+
id: t.cloneNode(tmpVar)
|
|
82
|
+
});
|
|
98
83
|
}
|
|
84
|
+
ref = tmpVar;
|
|
85
|
+
check = t.assignmentExpression("=", t.cloneNode(tmpVar), chainWithTypes);
|
|
86
|
+
isCall ? node.callee = ref : node.object = ref;
|
|
99
87
|
}
|
|
100
|
-
if (isCall &&
|
|
88
|
+
if (isCall && t.isMemberExpression(chain)) {
|
|
101
89
|
if (pureGetters && isSimpleMemberExpression(chain)) {
|
|
102
90
|
node.callee = chainWithTypes;
|
|
103
91
|
} else {
|
|
@@ -105,46 +93,69 @@ function transform(path, {
|
|
|
105
93
|
object
|
|
106
94
|
} = chain;
|
|
107
95
|
let context;
|
|
108
|
-
if (
|
|
109
|
-
context =
|
|
96
|
+
if (t.isSuper(object)) {
|
|
97
|
+
context = t.thisExpression();
|
|
110
98
|
} else {
|
|
111
99
|
const memoized = scope.maybeGenerateMemoised(object);
|
|
112
100
|
if (memoized) {
|
|
113
101
|
context = memoized;
|
|
114
|
-
chain.object =
|
|
102
|
+
chain.object = t.assignmentExpression("=", memoized, object);
|
|
115
103
|
} else {
|
|
116
104
|
context = object;
|
|
117
105
|
}
|
|
118
106
|
}
|
|
119
|
-
node.arguments.unshift(
|
|
120
|
-
node.callee =
|
|
107
|
+
node.arguments.unshift(t.cloneNode(context));
|
|
108
|
+
node.callee = t.memberExpression(node.callee, t.identifier("call"));
|
|
121
109
|
}
|
|
122
110
|
}
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
111
|
+
const data = {
|
|
112
|
+
check: t.cloneNode(check),
|
|
113
|
+
ref: t.cloneNode(ref)
|
|
114
|
+
};
|
|
115
|
+
Object.defineProperty(data, "ref", {
|
|
116
|
+
enumerable: false
|
|
117
|
+
});
|
|
118
|
+
checks.push(data);
|
|
119
|
+
}
|
|
120
|
+
let result = replacementPath.node;
|
|
121
|
+
if (wrapLast) result = wrapLast(result);
|
|
122
|
+
const ifNullishBoolean = t.isBooleanLiteral(ifNullish);
|
|
123
|
+
const ifNullishFalse = ifNullishBoolean && ifNullish.value === false;
|
|
124
|
+
const tpl = ifNullishFalse ? noDocumentAll ? NULLISH_CHECK_NO_DDA_NEG : NULLISH_CHECK_NEG : noDocumentAll ? NULLISH_CHECK_NO_DDA : NULLISH_CHECK;
|
|
125
|
+
const logicalOp = ifNullishFalse ? "&&" : "||";
|
|
126
|
+
const check = checks.map(tpl).reduce((expr, check) => t.logicalExpression(logicalOp, expr, check));
|
|
127
|
+
replacementPath.replaceWith(ifNullishBoolean ? t.logicalExpression(logicalOp, check, result) : t.conditionalExpression(check, ifNullish, result));
|
|
128
|
+
}
|
|
129
|
+
export function transform(path, assumptions) {
|
|
130
|
+
const {
|
|
131
|
+
scope
|
|
132
|
+
} = path;
|
|
133
|
+
const maybeWrapped = findOutermostTransparentParent(path);
|
|
134
|
+
const {
|
|
135
|
+
parentPath
|
|
136
|
+
} = maybeWrapped;
|
|
137
|
+
if (parentPath.isUnaryExpression({
|
|
138
|
+
operator: "delete"
|
|
139
|
+
})) {
|
|
140
|
+
transformOptionalChain(path, assumptions, parentPath, t.booleanLiteral(true));
|
|
141
|
+
} else {
|
|
142
|
+
let wrapLast;
|
|
143
|
+
if (parentPath.isCallExpression({
|
|
144
|
+
callee: maybeWrapped.node
|
|
145
|
+
}) && path.isOptionalMemberExpression()) {
|
|
146
|
+
wrapLast = replacement => {
|
|
147
|
+
const object = skipTransparentExprWrapperNodes(replacement.object);
|
|
148
|
+
let baseRef;
|
|
149
|
+
if (!assumptions.pureGetters || !isSimpleMemberExpression(object)) {
|
|
150
|
+
baseRef = scope.maybeGenerateMemoised(object);
|
|
151
|
+
if (baseRef) {
|
|
152
|
+
replacement.object = t.assignmentExpression("=", baseRef, object);
|
|
153
|
+
}
|
|
132
154
|
}
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
}
|
|
136
|
-
if (willReplacementCastToBoolean) {
|
|
137
|
-
const nonNullishCheck = noDocumentAll ? ast`${_core.types.cloneNode(check)} != null` : ast`
|
|
138
|
-
${_core.types.cloneNode(check)} !== null && ${_core.types.cloneNode(ref)} !== void 0`;
|
|
139
|
-
replacementPath.replaceWith(_core.types.logicalExpression("&&", nonNullishCheck, replacement));
|
|
140
|
-
replacementPath = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(replacementPath.get("right"));
|
|
141
|
-
} else {
|
|
142
|
-
const nullishCheck = noDocumentAll ? ast`${_core.types.cloneNode(check)} == null` : ast`
|
|
143
|
-
${_core.types.cloneNode(check)} === null || ${_core.types.cloneNode(ref)} === void 0`;
|
|
144
|
-
const returnValue = isDeleteOperation ? ast`true` : ast`void 0`;
|
|
145
|
-
replacementPath.replaceWith(_core.types.conditionalExpression(nullishCheck, returnValue, replacement));
|
|
146
|
-
replacementPath = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(replacementPath.get("alternate"));
|
|
155
|
+
return t.callExpression(t.memberExpression(replacement, t.identifier("bind")), [t.cloneNode(baseRef ?? object)]);
|
|
156
|
+
};
|
|
147
157
|
}
|
|
158
|
+
transformOptionalChain(path, assumptions, path, willPathCastToBoolean(maybeWrapped) ? t.booleanLiteral(false) : scope.buildUndefinedNode(), wrapLast);
|
|
148
159
|
}
|
|
149
160
|
}
|
|
150
161
|
|
package/lib/transform.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["_core","require","_helperSkipTransparentExpressionWrappers","_util","ast","template","expression","isSimpleMemberExpression","skipTransparentExprWrapperNodes","t","isIdentifier","isSuper","isMemberExpression","computed","object","needsMemoize","path","optionalPath","scope","isOptionalMemberExpression","isOptionalCallExpression","node","childPath","skipTransparentExprWrappers","get","optional","isStatic","transform","pureGetters","noDocumentAll","maybeWrapped","findOutermostTransparentParent","parentPath","willReplacementCastToBoolean","willPathCastToBoolean","isDeleteOperation","parentIsCall","isCallExpression","callee","optionals","isPattern","replaceWith","push","type","replacementPath","isUnaryExpression","operator","i","length","isCall","chainWithTypes","chain","ref","check","name","sequenceExpression","numericLiteral","maybeGenerateMemoised","assignmentExpression","cloneNode","context","thisExpression","memoized","arguments","unshift","memberExpression","identifier","replacement","_baseRef","baseRef","callExpression","nonNullishCheck","logicalExpression","nullishCheck","returnValue","conditionalExpression"],"sources":["../src/transform.ts"],"sourcesContent":["import { types as t, template } from \"@babel/core\";\nimport type { NodePath } from \"@babel/traverse\";\nimport {\n skipTransparentExprWrapperNodes,\n skipTransparentExprWrappers,\n} from \"@babel/helper-skip-transparent-expression-wrappers\";\nimport { willPathCastToBoolean, findOutermostTransparentParent } from \"./util\";\n\nconst { ast } = template.expression;\n\nfunction isSimpleMemberExpression(\n expression: t.Expression | t.Super,\n): expression is t.Identifier | t.Super | t.MemberExpression {\n expression = skipTransparentExprWrapperNodes(expression);\n return (\n t.isIdentifier(expression) ||\n t.isSuper(expression) ||\n (t.isMemberExpression(expression) &&\n !expression.computed &&\n isSimpleMemberExpression(expression.object))\n );\n}\n\n/**\n * Test if a given optional chain `path` needs to be memoized\n * @param {NodePath} path\n * @returns {boolean}\n */\nfunction needsMemoize(\n path: NodePath<t.OptionalCallExpression | t.OptionalMemberExpression>,\n) {\n let optionalPath: NodePath = path;\n const { scope } = path;\n while (\n optionalPath.isOptionalMemberExpression() ||\n optionalPath.isOptionalCallExpression()\n ) {\n const { node } = optionalPath;\n const childPath = skipTransparentExprWrappers(\n // @ts-expect-error isOptionalMemberExpression does not work with NodePath union\n optionalPath.isOptionalMemberExpression()\n ? optionalPath.get(\"object\")\n : optionalPath.get(\"callee\"),\n );\n if (node.optional) {\n return !scope.isStatic(childPath.node);\n }\n\n optionalPath = childPath;\n }\n}\n\nexport function transform(\n path: NodePath<t.OptionalCallExpression | t.OptionalMemberExpression>,\n {\n pureGetters,\n noDocumentAll,\n }: { pureGetters: boolean; noDocumentAll: boolean },\n) {\n const { scope } = path;\n // maybeWrapped points to the outermost transparent expression wrapper\n // or the path itself\n const maybeWrapped = findOutermostTransparentParent(path);\n const { parentPath } = maybeWrapped;\n const willReplacementCastToBoolean = willPathCastToBoolean(maybeWrapped);\n let isDeleteOperation = false;\n const parentIsCall =\n parentPath.isCallExpression({ callee: maybeWrapped.node }) &&\n // note that the first condition must implies that `path.optional` is `true`,\n // otherwise the parentPath should be an OptionalCallExpression\n path.isOptionalMemberExpression();\n\n const optionals = [];\n\n let optionalPath = path;\n // Replace `function (a, x = a.b?.c) {}` to `function (a, x = (() => a.b?.c)() ){}`\n // so the temporary variable can be injected in correct scope\n if (scope.path.isPattern() && needsMemoize(optionalPath)) {\n path.replaceWith(template.ast`(() => ${path.node})()` as t.Statement);\n // The injected optional chain will be queued and eventually transformed when visited\n return;\n }\n while (\n optionalPath.isOptionalMemberExpression() ||\n optionalPath.isOptionalCallExpression()\n ) {\n const { node } = optionalPath;\n if (node.optional) {\n optionals.push(node);\n }\n // @ts-expect-error isOptionalMemberExpression does not work with NodePath union\n if (optionalPath.isOptionalMemberExpression()) {\n // @ts-expect-error todo(flow->ts) avoid changing more type\n optionalPath.node.type = \"MemberExpression\";\n // @ts-expect-error todo(flow->ts)\n optionalPath = skipTransparentExprWrappers(optionalPath.get(\"object\"));\n } else if (optionalPath.isOptionalCallExpression()) {\n // @ts-expect-error todo(flow->ts) avoid changing more type\n optionalPath.node.type = \"CallExpression\";\n // @ts-expect-error todo(flow->ts)\n optionalPath = skipTransparentExprWrappers(optionalPath.get(\"callee\"));\n }\n }\n\n // todo: Improve replacementPath typings\n let replacementPath: NodePath<any> = path;\n if (parentPath.isUnaryExpression({ operator: \"delete\" })) {\n replacementPath = parentPath;\n isDeleteOperation = true;\n }\n for (let i = optionals.length - 1; i >= 0; i--) {\n const node = optionals[i] as unknown as\n | t.MemberExpression\n | t.CallExpression;\n\n const isCall = t.isCallExpression(node);\n\n const chainWithTypes = isCall\n ? // V8 intrinsics must not be an optional call\n (node.callee as t.Expression)\n : node.object;\n const chain = skipTransparentExprWrapperNodes(chainWithTypes);\n\n let ref;\n let check;\n if (isCall && t.isIdentifier(chain, { name: \"eval\" })) {\n check = ref = chain;\n // `eval?.()` is an indirect eval call transformed to `(0,eval)()`\n node.callee = t.sequenceExpression([t.numericLiteral(0), ref]);\n } else if (pureGetters && isCall && isSimpleMemberExpression(chain)) {\n // If we assume getters are pure (avoiding a Function#call) and we are at the call,\n // we can avoid a needless memoize. We only do this if the callee is a simple member\n // expression, to avoid multiple calls to nested call expressions.\n check = ref = node.callee;\n } else {\n ref = scope.maybeGenerateMemoised(chain);\n if (ref) {\n check = t.assignmentExpression(\n \"=\",\n t.cloneNode(ref),\n // Here `chainWithTypes` MUST NOT be cloned because it could be\n // updated when generating the memoised context of a call\n // expression. It must be an Expression when `ref` is an identifier\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n chainWithTypes as t.Expression,\n );\n\n isCall ? (node.callee = ref) : (node.object = ref);\n } else {\n check = ref = chainWithTypes;\n }\n }\n\n // Ensure call expressions have the proper `this`\n // `foo.bar()` has context `foo`.\n if (isCall && t.isMemberExpression(chain)) {\n if (pureGetters && isSimpleMemberExpression(chain)) {\n // To avoid a Function#call, we can instead re-grab the property from the context object.\n // `a.?b.?()` translates roughly to `_a.b != null && _a.b()`\n node.callee = chainWithTypes;\n } else {\n // Otherwise, we need to memoize the context object, and change the call into a Function#call.\n // `a.?b.?()` translates roughly to `(_b = _a.b) != null && _b.call(_a)`\n const { object } = chain;\n let context: t.Expression;\n if (t.isSuper(object)) {\n context = t.thisExpression();\n } else {\n const memoized = scope.maybeGenerateMemoised(object);\n if (memoized) {\n context = memoized;\n chain.object = t.assignmentExpression(\"=\", memoized, object);\n } else {\n context = object;\n }\n }\n\n node.arguments.unshift(t.cloneNode(context));\n // @ts-expect-error node.callee can not be an V8IntrinsicIdentifier: V8 intrinsic is disallowed in optional chain\n node.callee = t.memberExpression(node.callee, t.identifier(\"call\"));\n }\n }\n let replacement = replacementPath.node;\n // Ensure (a?.b)() has proper `this`\n // The `parentIsCall` is constant within loop, we should check i === 0\n // to ensure that it is only applied to the first optional chain element\n // i.e. `?.b` in `(a?.b.c)()`\n if (i === 0 && parentIsCall) {\n // `(a?.b)()` to `(a == null ? undefined : a.b.bind(a))()`\n // object must not be Super as super?.foo is invalid\n const object = skipTransparentExprWrapperNodes(\n replacement.object,\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n ) as any as t.Expression;\n let baseRef;\n if (!pureGetters || !isSimpleMemberExpression(object)) {\n // memoize the context object when getters are not always pure\n // or the object is not a simple member expression\n // `(a?.b.c)()` to `(a == null ? undefined : (_a$b = a.b).c.bind(_a$b))()`\n baseRef = scope.maybeGenerateMemoised(object);\n if (baseRef) {\n replacement.object = t.assignmentExpression(\"=\", baseRef, object);\n }\n }\n replacement = t.callExpression(\n t.memberExpression(replacement, t.identifier(\"bind\")),\n [t.cloneNode(baseRef ?? object)],\n );\n }\n\n if (willReplacementCastToBoolean) {\n // `if (a?.b) {}` transformed to `if (a != null && a.b) {}`\n // we don't need to return `void 0` because the returned value will\n // eventually cast to boolean.\n const nonNullishCheck = noDocumentAll\n ? ast`${t.cloneNode(check)} != null`\n : ast`\n ${t.cloneNode(check)} !== null && ${t.cloneNode(ref)} !== void 0`;\n replacementPath.replaceWith(\n t.logicalExpression(\"&&\", nonNullishCheck, replacement),\n );\n replacementPath = skipTransparentExprWrappers(\n // @ts-expect-error todo(flow->ts)\n replacementPath.get(\"right\"),\n );\n } else {\n const nullishCheck = noDocumentAll\n ? ast`${t.cloneNode(check)} == null`\n : ast`\n ${t.cloneNode(check)} === null || ${t.cloneNode(ref)} === void 0`;\n\n const returnValue = isDeleteOperation ? ast`true` : ast`void 0`;\n replacementPath.replaceWith(\n t.conditionalExpression(nullishCheck, returnValue, replacement),\n );\n replacementPath = skipTransparentExprWrappers(\n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ACd,cAAcK,WAAC,CAACkD,SAAS,CAACN,KAAK,CAAE,gBAAe5C,WAAC,CAACkD,SAAS,CAACP,GAAG,CAAE,aAAY;MAEvE,MAAMsB,WAAW,GAAGvC,iBAAiB,GAAG/B,GAAI,MAAK,GAAGA,GAAI,QAAO;MAC/DwC,eAAe,CAACH,WAAW,CACzBhC,WAAC,CAACkE,qBAAqB,CAACF,YAAY,EAAEC,WAAW,EAAEP,WAAW,CAChE,CAAC;MACDvB,eAAe,GAAG,IAAArB,oEAA2B,EAE3CqB,eAAe,CAACpB,GAAG,CAAC,WAAW,CACjC,CAAC;IACH;EACF;AACF"}
|
|
1
|
+
{"version":3,"names":["types","t","template","skipTransparentExprWrapperNodes","skipTransparentExprWrappers","willPathCastToBoolean","findOutermostTransparentParent","isSimpleMemberExpression","expression","isIdentifier","isSuper","isMemberExpression","computed","object","needsMemoize","path","optionalPath","scope","isOptionalMemberExpression","isOptionalCallExpression","node","childPath","get","optional","isStatic","NULLISH_CHECK","NULLISH_CHECK_NO_DDA","NULLISH_CHECK_NEG","NULLISH_CHECK_NO_DDA_NEG","transformOptionalChain","pureGetters","noDocumentAll","replacementPath","ifNullish","wrapLast","isPattern","replaceWith","ast","optionals","push","type","length","checks","tmpVar","i","isCall","isCallExpression","chainWithTypes","callee","chain","ref","check","name","sequenceExpression","numericLiteral","generateUidIdentifierBasedOnNode","id","cloneNode","assignmentExpression","context","thisExpression","memoized","maybeGenerateMemoised","arguments","unshift","memberExpression","identifier","data","Object","defineProperty","enumerable","result","ifNullishBoolean","isBooleanLiteral","ifNullishFalse","value","tpl","logicalOp","map","reduce","expr","logicalExpression","conditionalExpression","transform","assumptions","maybeWrapped","parentPath","isUnaryExpression","operator","booleanLiteral","replacement","baseRef","callExpression","buildUndefinedNode"],"sources":["../src/transform.ts"],"sourcesContent":["import { types as t, template } from \"@babel/core\";\nimport type { NodePath } from \"@babel/traverse\";\nimport {\n skipTransparentExprWrapperNodes,\n skipTransparentExprWrappers,\n} from \"@babel/helper-skip-transparent-expression-wrappers\";\nimport { willPathCastToBoolean, findOutermostTransparentParent } from \"./util\";\n\nfunction isSimpleMemberExpression(\n expression: t.Expression | t.Super,\n): expression is t.Identifier | t.Super | t.MemberExpression {\n expression = skipTransparentExprWrapperNodes(expression);\n return (\n t.isIdentifier(expression) ||\n t.isSuper(expression) ||\n (t.isMemberExpression(expression) &&\n !expression.computed &&\n isSimpleMemberExpression(expression.object))\n );\n}\n\n/**\n * Test if a given optional chain `path` needs to be memoized\n * @param {NodePath} path\n * @returns {boolean}\n */\nfunction needsMemoize(\n path: NodePath<t.OptionalCallExpression | t.OptionalMemberExpression>,\n) {\n let optionalPath: NodePath = path;\n const { scope } = path;\n while (\n optionalPath.isOptionalMemberExpression() ||\n optionalPath.isOptionalCallExpression()\n ) {\n const { node } = optionalPath;\n const childPath = skipTransparentExprWrappers(\n // @ts-expect-error isOptionalMemberExpression does not work with NodePath union\n optionalPath.isOptionalMemberExpression()\n ? optionalPath.get(\"object\")\n : optionalPath.get(\"callee\"),\n );\n if (node.optional) {\n return !scope.isStatic(childPath.node);\n }\n\n optionalPath = childPath;\n }\n}\n\nconst NULLISH_CHECK = template.expression(\n `%%check%% === null || %%ref%% === void 0`,\n);\nconst NULLISH_CHECK_NO_DDA = template.expression(`%%check%% == null`);\nconst NULLISH_CHECK_NEG = template.expression(\n `%%check%% !== null && %%ref%% !== void 0`,\n);\nconst NULLISH_CHECK_NO_DDA_NEG = template.expression(`%%check%% != null`);\n\ninterface OptionalChainAssumptions {\n pureGetters: boolean;\n noDocumentAll: boolean;\n}\n\nexport function transformOptionalChain(\n path: NodePath<t.OptionalCallExpression | t.OptionalMemberExpression>,\n { pureGetters, noDocumentAll }: OptionalChainAssumptions,\n replacementPath: NodePath<t.Expression>,\n ifNullish: t.Expression,\n wrapLast?: (value: t.Expression) => t.Expression,\n) {\n const { scope } = path;\n\n // Replace `function (a, x = a.b?.c) {}` to `function (a, x = (() => a.b?.c)() ){}`\n // so the temporary variable can be injected in correct scope\n if (scope.path.isPattern() && needsMemoize(path)) {\n replacementPath.replaceWith(\n template.expression.ast`(() => ${replacementPath.node})()`,\n );\n // The injected optional chain will be queued and eventually transformed when visited\n return;\n }\n\n const optionals = [];\n\n let optionalPath = path;\n while (\n optionalPath.isOptionalMemberExpression() ||\n optionalPath.isOptionalCallExpression()\n ) {\n const { node } = optionalPath;\n if (node.optional) {\n optionals.push(node);\n }\n // @ts-expect-error isOptionalMemberExpression does not work with NodePath union\n if (optionalPath.isOptionalMemberExpression()) {\n // @ts-expect-error todo(flow->ts) avoid changing more type\n optionalPath.node.type = \"MemberExpression\";\n // @ts-expect-error todo(flow->ts)\n optionalPath = skipTransparentExprWrappers(optionalPath.get(\"object\"));\n } else if (optionalPath.isOptionalCallExpression()) {\n // @ts-expect-error todo(flow->ts) avoid changing more type\n optionalPath.node.type = \"CallExpression\";\n // @ts-expect-error todo(flow->ts)\n optionalPath = skipTransparentExprWrappers(optionalPath.get(\"callee\"));\n }\n }\n\n if (optionals.length === 0) {\n // Malformed AST: there was an OptionalMemberExpression node\n // with no actual optional elements.\n return;\n }\n\n const checks = [];\n\n let tmpVar;\n\n for (let i = optionals.length - 1; i >= 0; i--) {\n const node = optionals[i] as unknown as\n | t.MemberExpression\n | t.CallExpression;\n\n const isCall = t.isCallExpression(node);\n\n const chainWithTypes = isCall\n ? // V8 intrinsics must not be an optional call\n (node.callee as t.Expression)\n : node.object;\n const chain = skipTransparentExprWrapperNodes(chainWithTypes);\n\n let ref;\n let check;\n if (isCall && t.isIdentifier(chain, { name: \"eval\" })) {\n check = ref = chain;\n // `eval?.()` is an indirect eval call transformed to `(0,eval)()`\n node.callee = t.sequenceExpression([t.numericLiteral(0), ref]);\n } else if (pureGetters && isCall && isSimpleMemberExpression(chain)) {\n // If we assume getters are pure (avoiding a Function#call) and we are at the call,\n // we can avoid a needless memoize. We only do this if the callee is a simple member\n // expression, to avoid multiple calls to nested call expressions.\n check = ref = node.callee;\n } else if (scope.isStatic(chain)) {\n check = ref = chainWithTypes;\n } else {\n // We cannot reuse the tmpVar for calls, because we need to\n // store both the method and the receiver.\n if (!tmpVar || isCall) {\n tmpVar = scope.generateUidIdentifierBasedOnNode(chain);\n scope.push({ id: t.cloneNode(tmpVar) });\n }\n ref = tmpVar;\n check = t.assignmentExpression(\n \"=\",\n t.cloneNode(tmpVar),\n // Here `chainWithTypes` MUST NOT be cloned because it could be\n // updated when generating the memoised context of a call\n // expression. It must be an Expression when `ref` is an identifier\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n chainWithTypes as t.Expression,\n );\n\n isCall ? (node.callee = ref) : (node.object = ref);\n }\n\n // Ensure call expressions have the proper `this`\n // `foo.bar()` has context `foo`.\n if (isCall && t.isMemberExpression(chain)) {\n if (pureGetters && isSimpleMemberExpression(chain)) {\n // To avoid a Function#call, we can instead re-grab the property from the context object.\n // `a.?b.?()` translates roughly to `_a.b != null && _a.b()`\n node.callee = chainWithTypes;\n } else {\n // Otherwise, we need to memoize the context object, and change the call into a Function#call.\n // `a.?b.?()` translates roughly to `(_b = _a.b) != null && _b.call(_a)`\n const { object } = chain;\n let context: t.Expression;\n if (t.isSuper(object)) {\n context = t.thisExpression();\n } else {\n const memoized = scope.maybeGenerateMemoised(object);\n if (memoized) {\n context = memoized;\n chain.object = t.assignmentExpression(\"=\", memoized, object);\n } else {\n context = object;\n }\n }\n\n node.arguments.unshift(t.cloneNode(context));\n // @ts-expect-error node.callee can not be an V8IntrinsicIdentifier: V8 intrinsic is disallowed in optional chain\n node.callee = t.memberExpression(node.callee, t.identifier(\"call\"));\n }\n }\n\n const data = { check: t.cloneNode(check), ref: t.cloneNode(ref) };\n // We make `ref` non-enumerable, so that @babel/template doesn't throw\n // in the noDocumentAll template if it's not used.\n Object.defineProperty(data, \"ref\", { enumerable: false });\n checks.push(data);\n }\n\n let result = replacementPath.node;\n if (wrapLast) result = wrapLast(result);\n\n const ifNullishBoolean = t.isBooleanLiteral(ifNullish);\n const ifNullishFalse = ifNullishBoolean && ifNullish.value === false;\n\n // prettier-ignore\n const tpl = ifNullishFalse\n ? (noDocumentAll ? NULLISH_CHECK_NO_DDA_NEG : NULLISH_CHECK_NEG)\n : (noDocumentAll ? NULLISH_CHECK_NO_DDA : NULLISH_CHECK);\n const logicalOp = ifNullishFalse ? \"&&\" : \"||\";\n\n const check = checks\n .map(tpl)\n .reduce((expr, check) => t.logicalExpression(logicalOp, expr, check));\n\n replacementPath.replaceWith(\n ifNullishBoolean\n ? t.logicalExpression(logicalOp, check, result)\n : t.conditionalExpression(check, ifNullish, result),\n );\n}\n\nexport function transform(\n path: NodePath<t.OptionalCallExpression | t.OptionalMemberExpression>,\n assumptions: OptionalChainAssumptions,\n) {\n const { scope } = path;\n\n // maybeWrapped points to the outermost transparent expression wrapper\n // or the path itself\n const maybeWrapped = findOutermostTransparentParent(path);\n const { parentPath } = maybeWrapped;\n\n if (parentPath.isUnaryExpression({ operator: \"delete\" })) {\n transformOptionalChain(\n path,\n assumptions,\n parentPath,\n t.booleanLiteral(true),\n );\n } else {\n let wrapLast;\n if (\n parentPath.isCallExpression({ callee: maybeWrapped.node }) &&\n // note that the first condition must implies that `path.optional` is `true`,\n // otherwise the parentPath should be an OptionalCallExpression\n path.isOptionalMemberExpression()\n ) {\n // Ensure (a?.b)() has proper `this`\n wrapLast = (replacement: t.MemberExpression) => {\n // `(a?.b)()` to `(a == null ? undefined : a.b.bind(a))()`\n // object must not be Super as super?.foo is invalid\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n const object = skipTransparentExprWrapperNodes(\n replacement.object,\n ) as t.Expression;\n let baseRef: t.Expression;\n if (!assumptions.pureGetters || !isSimpleMemberExpression(object)) {\n // memoize the context object when getters are not always pure\n // or the object is not a simple member expression\n // `(a?.b.c)()` to `(a == null ? undefined : (_a$b = a.b).c.bind(_a$b))()`\n baseRef = scope.maybeGenerateMemoised(object);\n if (baseRef) {\n replacement.object = t.assignmentExpression(\"=\", baseRef, object);\n }\n }\n return t.callExpression(\n t.memberExpression(replacement, t.identifier(\"bind\")),\n [t.cloneNode(baseRef ?? object)],\n );\n };\n }\n\n transformOptionalChain(\n path,\n assumptions,\n path,\n willPathCastToBoolean(maybeWrapped)\n ? t.booleanLiteral(false)\n : scope.buildUndefinedNode(),\n wrapLast,\n );\n }\n}\n"],"mappings":"AAAA,SAASA,KAAK,IAAIC,CAAC,EAAEC,QAAQ,QAAQ,aAAa;AAElD,SACEC,+BAA+B,EAC/BC,2BAA2B,QACtB,oDAAoD;AAC3D,SAASC,qBAAqB,EAAEC,8BAA8B,QAAQ,WAAQ;AAE9E,SAASC,wBAAwBA,CAC/BC,UAAkC,EACyB;EAC3DA,UAAU,GAAGL,+BAA+B,CAACK,UAAU,CAAC;EACxD,OACEP,CAAC,CAACQ,YAAY,CAACD,UAAU,CAAC,IAC1BP,CAAC,CAACS,OAAO,CAACF,UAAU,CAAC,IACpBP,CAAC,CAACU,kBAAkB,CAACH,UAAU,CAAC,IAC/B,CAACA,UAAU,CAACI,QAAQ,IACpBL,wBAAwB,CAACC,UAAU,CAACK,MAAM,CAAE;AAElD;AAOA,SAASC,YAAYA,CACnBC,IAAqE,EACrE;EACA,IAAIC,YAAsB,GAAGD,IAAI;EACjC,MAAM;IAAEE;EAAM,CAAC,GAAGF,IAAI;EACtB,OACEC,YAAY,CAACE,0BAA0B,CAAC,CAAC,IACzCF,YAAY,CAACG,wBAAwB,CAAC,CAAC,EACvC;IACA,MAAM;MAAEC;IAAK,CAAC,GAAGJ,YAAY;IAC7B,MAAMK,SAAS,GAAGjB,2BAA2B,CAE3CY,YAAY,CAACE,0BAA0B,CAAC,CAAC,GACrCF,YAAY,CAACM,GAAG,CAAC,QAAQ,CAAC,GAC1BN,YAAY,CAACM,GAAG,CAAC,QAAQ,CAC/B,CAAC;IACD,IAAIF,IAAI,CAACG,QAAQ,EAAE;MACjB,OAAO,CAACN,KAAK,CAACO,QAAQ,CAACH,SAAS,CAACD,IAAI,CAAC;IACxC;IA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D,CAACjE,CAAC,CAACwD,SAAS,CAACkC,OAAO,IAAI9E,MAAM,CAAC,CACjC,CAAC;MACH,CAAC;IACH;IAEAgB,sBAAsB,CACpBd,IAAI,EACJqE,WAAW,EACXrE,IAAI,EACJV,qBAAqB,CAACgF,YAAY,CAAC,GAC/BpF,CAAC,CAACwF,cAAc,CAAC,KAAK,CAAC,GACvBxE,KAAK,CAAC4E,kBAAkB,CAAC,CAAC,EAC9B3D,QACF,CAAC;EACH;AACF"}
|
package/lib/util.js
CHANGED
|
@@ -1,12 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
Object.defineProperty(exports, "__esModule", {
|
|
4
|
-
value: true
|
|
5
|
-
});
|
|
6
|
-
exports.findOutermostTransparentParent = findOutermostTransparentParent;
|
|
7
|
-
exports.willPathCastToBoolean = willPathCastToBoolean;
|
|
8
|
-
var _helperSkipTransparentExpressionWrappers = require("@babel/helper-skip-transparent-expression-wrappers");
|
|
9
|
-
function willPathCastToBoolean(path) {
|
|
1
|
+
import { isTransparentExprWrapper } from "@babel/helper-skip-transparent-expression-wrappers";
|
|
2
|
+
export function willPathCastToBoolean(path) {
|
|
10
3
|
const maybeWrapped = findOutermostTransparentParent(path);
|
|
11
4
|
const {
|
|
12
5
|
node,
|
|
@@ -39,10 +32,10 @@ function willPathCastToBoolean(path) {
|
|
|
39
32
|
test: node
|
|
40
33
|
});
|
|
41
34
|
}
|
|
42
|
-
function findOutermostTransparentParent(path) {
|
|
35
|
+
export function findOutermostTransparentParent(path) {
|
|
43
36
|
let maybeWrapped = path;
|
|
44
37
|
path.findParent(p => {
|
|
45
|
-
if (!
|
|
38
|
+
if (!isTransparentExprWrapper(p.node)) return true;
|
|
46
39
|
maybeWrapped = p;
|
|
47
40
|
});
|
|
48
41
|
return maybeWrapped;
|
package/lib/util.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["
|
|
1
|
+
{"version":3,"names":["isTransparentExprWrapper","willPathCastToBoolean","path","maybeWrapped","findOutermostTransparentParent","node","parentPath","isLogicalExpression","operator","right","isSequenceExpression","expressions","length","isConditional","test","isUnaryExpression","isLoop","findParent","p"],"sources":["../src/util.ts"],"sourcesContent":["import type { NodePath } from \"@babel/traverse\";\nimport { isTransparentExprWrapper } from \"@babel/helper-skip-transparent-expression-wrappers\";\n/**\n * Test if a NodePath will be cast to boolean when evaluated.\n * It respects transparent expression wrappers defined in\n * \"@babel/helper-skip-transparent-expression-wrappers\"\n *\n * @example\n * // returns true\n * const nodePathADotB = NodePath(\"if (a.b) {}\").get(\"test\"); // a.b\n * willPathCastToBoolean(nodePathADotB)\n * @example\n * // returns false\n * willPathCastToBoolean(NodePath(\"a.b\"))\n * @param {NodePath} path\n * @returns {boolean}\n */\nexport function willPathCastToBoolean(path: NodePath): boolean {\n const maybeWrapped = findOutermostTransparentParent(path);\n const { node, parentPath } = maybeWrapped;\n if (parentPath.isLogicalExpression()) {\n const { operator, right } = parentPath.node;\n if (\n operator === \"&&\" ||\n operator === \"||\" ||\n (operator === \"??\" && node === right)\n ) {\n return willPathCastToBoolean(parentPath);\n }\n }\n if (parentPath.isSequenceExpression()) {\n const { expressions } = parentPath.node;\n if (expressions[expressions.length - 1] === node) {\n return willPathCastToBoolean(parentPath);\n } else {\n // if it is in the middle of a sequence expression, we don't\n // care the return value so just cast to boolean for smaller\n // output\n return true;\n }\n }\n return (\n parentPath.isConditional({ test: node }) ||\n parentPath.isUnaryExpression({ operator: \"!\" }) ||\n parentPath.isLoop({ test: node })\n );\n}\n\n/**\n * Return the outermost transparent expression wrapper of a given path,\n * otherwise returns path itself.\n * @example\n * const nodePathADotB = NodePath(\"(a.b as any)\").get(\"expression\"); // a.b\n * // returns NodePath(\"(a.b as any)\")\n * findOutermostTransparentParent(nodePathADotB);\n * @param {NodePath} path\n * @returns {NodePath}\n */\nexport function findOutermostTransparentParent(path: NodePath): NodePath {\n let maybeWrapped = path;\n path.findParent(p => {\n if (!isTransparentExprWrapper(p.node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;IAClDF,YAAY,GAAGe,CAAC;EAClB,CAAC,CAAC;EACF,OAAOf,YAAY;AACrB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@babel/plugin-transform-optional-chaining",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "8.0.0-alpha.0",
|
|
4
4
|
"description": "Transform optional chaining operators into a series of nil checks",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -17,22 +17,26 @@
|
|
|
17
17
|
"babel-plugin"
|
|
18
18
|
],
|
|
19
19
|
"dependencies": {
|
|
20
|
-
"@babel/helper-plugin-utils": "^
|
|
21
|
-
"@babel/helper-skip-transparent-expression-wrappers": "^
|
|
20
|
+
"@babel/helper-plugin-utils": "^8.0.0-alpha.0",
|
|
21
|
+
"@babel/helper-skip-transparent-expression-wrappers": "^8.0.0-alpha.0",
|
|
22
22
|
"@babel/plugin-syntax-optional-chaining": "^7.8.3"
|
|
23
23
|
},
|
|
24
24
|
"peerDependencies": {
|
|
25
|
-
"@babel/core": "^
|
|
25
|
+
"@babel/core": "^8.0.0-alpha.0"
|
|
26
26
|
},
|
|
27
27
|
"devDependencies": {
|
|
28
|
-
"@babel/core": "^
|
|
29
|
-
"@babel/helper-plugin-test-runner": "^
|
|
30
|
-
"@babel/plugin-transform-block-scoping": "^
|
|
31
|
-
"@babel/traverse": "^
|
|
28
|
+
"@babel/core": "^8.0.0-alpha.0",
|
|
29
|
+
"@babel/helper-plugin-test-runner": "^8.0.0-alpha.0",
|
|
30
|
+
"@babel/plugin-transform-block-scoping": "^8.0.0-alpha.0",
|
|
31
|
+
"@babel/traverse": "^8.0.0-alpha.0"
|
|
32
32
|
},
|
|
33
33
|
"engines": {
|
|
34
|
-
"node": ">=
|
|
34
|
+
"node": "^16.20.0 || ^18.16.0 || >=20.0.0"
|
|
35
35
|
},
|
|
36
36
|
"author": "The Babel Team (https://babel.dev/team)",
|
|
37
|
-
"
|
|
37
|
+
"exports": {
|
|
38
|
+
".": "./lib/index.js",
|
|
39
|
+
"./package.json": "./package.json"
|
|
40
|
+
},
|
|
41
|
+
"type": "module"
|
|
38
42
|
}
|