@babel/plugin-transform-optional-chaining 7.22.5 → 7.22.10

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 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/en/babel-plugin-transform-optional-chaining) for more information.
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
@@ -49,9 +49,6 @@ function findOutermostTransparentParent(path) {
49
49
  return maybeWrapped;
50
50
  }
51
51
 
52
- const {
53
- ast
54
- } = core.template.expression;
55
52
  function isSimpleMemberExpression(expression) {
56
53
  expression = helperSkipTransparentExpressionWrappers.skipTransparentExprWrapperNodes(expression);
57
54
  return core.types.isIdentifier(expression) || core.types.isSuper(expression) || core.types.isMemberExpression(expression) && !expression.computed && isSimpleMemberExpression(expression.object);
@@ -72,28 +69,23 @@ function needsMemoize(path) {
72
69
  optionalPath = childPath;
73
70
  }
74
71
  }
75
- function transform(path, {
72
+ const NULLISH_CHECK = core.template.expression(`%%check%% === null || %%ref%% === void 0`);
73
+ const NULLISH_CHECK_NO_DDA = core.template.expression(`%%check%% == null`);
74
+ const NULLISH_CHECK_NEG = core.template.expression(`%%check%% !== null && %%ref%% !== void 0`);
75
+ const NULLISH_CHECK_NO_DDA_NEG = core.template.expression(`%%check%% != null`);
76
+ function transformOptionalChain(path, {
76
77
  pureGetters,
77
78
  noDocumentAll
78
- }) {
79
+ }, replacementPath, ifNullish, wrapLast) {
79
80
  const {
80
81
  scope
81
82
  } = path;
82
- const maybeWrapped = findOutermostTransparentParent(path);
83
- const {
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})()`);
83
+ if (scope.path.isPattern() && needsMemoize(path)) {
84
+ replacementPath.replaceWith(core.template.expression.ast`(() => ${replacementPath.node})()`);
95
85
  return;
96
86
  }
87
+ const optionals = [];
88
+ let optionalPath = path;
97
89
  while (optionalPath.isOptionalMemberExpression() || optionalPath.isOptionalCallExpression()) {
98
90
  const {
99
91
  node
@@ -109,13 +101,11 @@ function transform(path, {
109
101
  optionalPath = helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers(optionalPath.get("callee"));
110
102
  }
111
103
  }
112
- let replacementPath = path;
113
- if (parentPath.isUnaryExpression({
114
- operator: "delete"
115
- })) {
116
- replacementPath = parentPath;
117
- isDeleteOperation = true;
104
+ if (optionals.length === 0) {
105
+ return;
118
106
  }
107
+ const checks = [];
108
+ let tmpVar;
119
109
  for (let i = optionals.length - 1; i >= 0; i--) {
120
110
  const node = optionals[i];
121
111
  const isCall = core.types.isCallExpression(node);
@@ -130,14 +120,18 @@ function transform(path, {
130
120
  node.callee = core.types.sequenceExpression([core.types.numericLiteral(0), ref]);
131
121
  } else if (pureGetters && isCall && isSimpleMemberExpression(chain)) {
132
122
  check = ref = node.callee;
123
+ } else if (scope.isStatic(chain)) {
124
+ check = ref = chainWithTypes;
133
125
  } else {
134
- ref = scope.maybeGenerateMemoised(chain);
135
- if (ref) {
136
- check = core.types.assignmentExpression("=", core.types.cloneNode(ref), chainWithTypes);
137
- isCall ? node.callee = ref : node.object = ref;
138
- } else {
139
- check = ref = chainWithTypes;
126
+ if (!tmpVar || isCall) {
127
+ tmpVar = scope.generateUidIdentifierBasedOnNode(chain);
128
+ scope.push({
129
+ id: core.types.cloneNode(tmpVar)
130
+ });
140
131
  }
132
+ ref = tmpVar;
133
+ check = core.types.assignmentExpression("=", core.types.cloneNode(tmpVar), chainWithTypes);
134
+ isCall ? node.callee = ref : node.object = ref;
141
135
  }
142
136
  if (isCall && core.types.isMemberExpression(chain)) {
143
137
  if (pureGetters && isSimpleMemberExpression(chain)) {
@@ -162,31 +156,55 @@ function transform(path, {
162
156
  node.callee = core.types.memberExpression(node.callee, core.types.identifier("call"));
163
157
  }
164
158
  }
165
- let replacement = replacementPath.node;
166
- if (i === 0 && parentIsCall) {
167
- var _baseRef;
168
- const object = helperSkipTransparentExpressionWrappers.skipTransparentExprWrapperNodes(replacement.object);
169
- let baseRef;
170
- if (!pureGetters || !isSimpleMemberExpression(object)) {
171
- baseRef = scope.maybeGenerateMemoised(object);
172
- if (baseRef) {
173
- replacement.object = core.types.assignmentExpression("=", baseRef, object);
159
+ const data = {
160
+ check: core.types.cloneNode(check),
161
+ ref: core.types.cloneNode(ref)
162
+ };
163
+ Object.defineProperty(data, "ref", {
164
+ enumerable: false
165
+ });
166
+ checks.push(data);
167
+ }
168
+ let result = replacementPath.node;
169
+ if (wrapLast) result = wrapLast(result);
170
+ const ifNullishBoolean = core.types.isBooleanLiteral(ifNullish);
171
+ const ifNullishFalse = ifNullishBoolean && ifNullish.value === false;
172
+ const tpl = ifNullishFalse ? noDocumentAll ? NULLISH_CHECK_NO_DDA_NEG : NULLISH_CHECK_NEG : noDocumentAll ? NULLISH_CHECK_NO_DDA : NULLISH_CHECK;
173
+ const logicalOp = ifNullishFalse ? "&&" : "||";
174
+ const check = checks.map(tpl).reduce((expr, check) => core.types.logicalExpression(logicalOp, expr, check));
175
+ replacementPath.replaceWith(ifNullishBoolean ? core.types.logicalExpression(logicalOp, check, result) : core.types.conditionalExpression(check, ifNullish, result));
176
+ }
177
+ function transform(path, assumptions) {
178
+ const {
179
+ scope
180
+ } = path;
181
+ const maybeWrapped = findOutermostTransparentParent(path);
182
+ const {
183
+ parentPath
184
+ } = maybeWrapped;
185
+ if (parentPath.isUnaryExpression({
186
+ operator: "delete"
187
+ })) {
188
+ transformOptionalChain(path, assumptions, parentPath, core.types.booleanLiteral(true));
189
+ } else {
190
+ let wrapLast;
191
+ if (parentPath.isCallExpression({
192
+ callee: maybeWrapped.node
193
+ }) && path.isOptionalMemberExpression()) {
194
+ wrapLast = replacement => {
195
+ var _baseRef;
196
+ const object = helperSkipTransparentExpressionWrappers.skipTransparentExprWrapperNodes(replacement.object);
197
+ let baseRef;
198
+ if (!assumptions.pureGetters || !isSimpleMemberExpression(object)) {
199
+ baseRef = scope.maybeGenerateMemoised(object);
200
+ if (baseRef) {
201
+ replacement.object = core.types.assignmentExpression("=", baseRef, object);
202
+ }
174
203
  }
175
- }
176
- replacement = core.types.callExpression(core.types.memberExpression(replacement, core.types.identifier("bind")), [core.types.cloneNode((_baseRef = baseRef) != null ? _baseRef : object)]);
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"));
204
+ return core.types.callExpression(core.types.memberExpression(replacement, core.types.identifier("bind")), [core.types.cloneNode((_baseRef = baseRef) != null ? _baseRef : object)]);
205
+ };
189
206
  }
207
+ transformOptionalChain(path, assumptions, path, willPathCastToBoolean(maybeWrapped) ? core.types.booleanLiteral(false) : scope.buildUndefinedNode(), wrapLast);
190
208
  }
191
209
  }
192
210
 
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,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EC,OAAgB,KAAK;EAAA,IAAAC,eAAA,EAAAC,gBAAA,CAAA;AAChDH,EAAAA,GAAG,CAACI,aAAa,CAAC,CAAC,CAAC,CAAA;EAEpB,MAAM;AAAEC,IAAAA,KAAK,GAAG,KAAA;AAAM,GAAC,GAAGJ,OAAO,CAAA;AACjC,EAAA,MAAM1C,aAAa,GAAA,CAAA2C,eAAA,GAAGF,GAAG,CAACM,UAAU,CAAC,eAAe,CAAC,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","baseRef","callExpression","buildUndefinedNode","declare","api","options","_api$assumption","_api$assumption2","assertVersion","loose","assumption","inherits","syntaxOptionalChaining","default","visitor","OptionalCallExpression|OptionalMemberExpression"],"mappings":";;;;;;;;;AAiBO,SAASA,qBAAqBA,CAACC,IAAc,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C,GAAG,EAAEC,OAAgB,KAAK;EAAA,IAAAC,eAAA,EAAAC,gBAAA,CAAA;AAChDH,EAAAA,GAAG,CAACI,aAAa,CAAC,CAAC,CAAC,CAAA;EAEpB,MAAM;AAAEC,IAAAA,KAAK,GAAG,KAAA;AAAM,GAAC,GAAGJ,OAAO,CAAA;AACjC,EAAA,MAAM7D,aAAa,GAAA,CAAA8D,eAAA,GAAGF,GAAG,CAACM,UAAU,CAAC,eAAe,CAAC,KAAAJ,IAAAA,GAAAA,eAAA,GAAIG,KAAK,CAAA;AAC9D,EAAA,MAAMlE,WAAW,GAAA,CAAAgE,gBAAA,GAAGH,GAAG,CAACM,UAAU,CAAC,aAAa,CAAC,KAAAH,IAAAA,GAAAA,gBAAA,GAAIE,KAAK,CAAA;EAE1D,OAAO;AACL7C,IAAAA,IAAI,EAAE,6BAA6B;IACnC+C,QAAQ,EAAEC,sBAAsB,CAACC,OAAO;AAExCC,IAAAA,OAAO,EAAE;MACP,iDAAiDC,CAC/CnH,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
@@ -4,12 +4,10 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.transform = transform;
7
+ exports.transformOptionalChain = transformOptionalChain;
7
8
  var _core = require("@babel/core");
8
9
  var _helperSkipTransparentExpressionWrappers = require("@babel/helper-skip-transparent-expression-wrappers");
9
10
  var _util = require("./util");
10
- const {
11
- ast
12
- } = _core.template.expression;
13
11
  function isSimpleMemberExpression(expression) {
14
12
  expression = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrapperNodes)(expression);
15
13
  return _core.types.isIdentifier(expression) || _core.types.isSuper(expression) || _core.types.isMemberExpression(expression) && !expression.computed && isSimpleMemberExpression(expression.object);
@@ -30,28 +28,23 @@ function needsMemoize(path) {
30
28
  optionalPath = childPath;
31
29
  }
32
30
  }
33
- function transform(path, {
31
+ const NULLISH_CHECK = _core.template.expression(`%%check%% === null || %%ref%% === void 0`);
32
+ const NULLISH_CHECK_NO_DDA = _core.template.expression(`%%check%% == null`);
33
+ const NULLISH_CHECK_NEG = _core.template.expression(`%%check%% !== null && %%ref%% !== void 0`);
34
+ const NULLISH_CHECK_NO_DDA_NEG = _core.template.expression(`%%check%% != null`);
35
+ function transformOptionalChain(path, {
34
36
  pureGetters,
35
37
  noDocumentAll
36
- }) {
38
+ }, replacementPath, ifNullish, wrapLast) {
37
39
  const {
38
40
  scope
39
41
  } = path;
40
- const maybeWrapped = (0, _util.findOutermostTransparentParent)(path);
41
- const {
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})()`);
42
+ if (scope.path.isPattern() && needsMemoize(path)) {
43
+ replacementPath.replaceWith(_core.template.expression.ast`(() => ${replacementPath.node})()`);
53
44
  return;
54
45
  }
46
+ const optionals = [];
47
+ let optionalPath = path;
55
48
  while (optionalPath.isOptionalMemberExpression() || optionalPath.isOptionalCallExpression()) {
56
49
  const {
57
50
  node
@@ -67,13 +60,11 @@ function transform(path, {
67
60
  optionalPath = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(optionalPath.get("callee"));
68
61
  }
69
62
  }
70
- let replacementPath = path;
71
- if (parentPath.isUnaryExpression({
72
- operator: "delete"
73
- })) {
74
- replacementPath = parentPath;
75
- isDeleteOperation = true;
63
+ if (optionals.length === 0) {
64
+ return;
76
65
  }
66
+ const checks = [];
67
+ let tmpVar;
77
68
  for (let i = optionals.length - 1; i >= 0; i--) {
78
69
  const node = optionals[i];
79
70
  const isCall = _core.types.isCallExpression(node);
@@ -88,14 +79,18 @@ function transform(path, {
88
79
  node.callee = _core.types.sequenceExpression([_core.types.numericLiteral(0), ref]);
89
80
  } else if (pureGetters && isCall && isSimpleMemberExpression(chain)) {
90
81
  check = ref = node.callee;
82
+ } else if (scope.isStatic(chain)) {
83
+ check = ref = chainWithTypes;
91
84
  } else {
92
- ref = scope.maybeGenerateMemoised(chain);
93
- if (ref) {
94
- check = _core.types.assignmentExpression("=", _core.types.cloneNode(ref), chainWithTypes);
95
- isCall ? node.callee = ref : node.object = ref;
96
- } else {
97
- check = ref = chainWithTypes;
85
+ if (!tmpVar || isCall) {
86
+ tmpVar = scope.generateUidIdentifierBasedOnNode(chain);
87
+ scope.push({
88
+ id: _core.types.cloneNode(tmpVar)
89
+ });
98
90
  }
91
+ ref = tmpVar;
92
+ check = _core.types.assignmentExpression("=", _core.types.cloneNode(tmpVar), chainWithTypes);
93
+ isCall ? node.callee = ref : node.object = ref;
99
94
  }
100
95
  if (isCall && _core.types.isMemberExpression(chain)) {
101
96
  if (pureGetters && isSimpleMemberExpression(chain)) {
@@ -120,31 +115,55 @@ function transform(path, {
120
115
  node.callee = _core.types.memberExpression(node.callee, _core.types.identifier("call"));
121
116
  }
122
117
  }
123
- let replacement = replacementPath.node;
124
- if (i === 0 && parentIsCall) {
125
- var _baseRef;
126
- const object = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrapperNodes)(replacement.object);
127
- let baseRef;
128
- if (!pureGetters || !isSimpleMemberExpression(object)) {
129
- baseRef = scope.maybeGenerateMemoised(object);
130
- if (baseRef) {
131
- replacement.object = _core.types.assignmentExpression("=", baseRef, object);
118
+ const data = {
119
+ check: _core.types.cloneNode(check),
120
+ ref: _core.types.cloneNode(ref)
121
+ };
122
+ Object.defineProperty(data, "ref", {
123
+ enumerable: false
124
+ });
125
+ checks.push(data);
126
+ }
127
+ let result = replacementPath.node;
128
+ if (wrapLast) result = wrapLast(result);
129
+ const ifNullishBoolean = _core.types.isBooleanLiteral(ifNullish);
130
+ const ifNullishFalse = ifNullishBoolean && ifNullish.value === false;
131
+ const tpl = ifNullishFalse ? noDocumentAll ? NULLISH_CHECK_NO_DDA_NEG : NULLISH_CHECK_NEG : noDocumentAll ? NULLISH_CHECK_NO_DDA : NULLISH_CHECK;
132
+ const logicalOp = ifNullishFalse ? "&&" : "||";
133
+ const check = checks.map(tpl).reduce((expr, check) => _core.types.logicalExpression(logicalOp, expr, check));
134
+ replacementPath.replaceWith(ifNullishBoolean ? _core.types.logicalExpression(logicalOp, check, result) : _core.types.conditionalExpression(check, ifNullish, result));
135
+ }
136
+ function transform(path, assumptions) {
137
+ const {
138
+ scope
139
+ } = path;
140
+ const maybeWrapped = (0, _util.findOutermostTransparentParent)(path);
141
+ const {
142
+ parentPath
143
+ } = maybeWrapped;
144
+ if (parentPath.isUnaryExpression({
145
+ operator: "delete"
146
+ })) {
147
+ transformOptionalChain(path, assumptions, parentPath, _core.types.booleanLiteral(true));
148
+ } else {
149
+ let wrapLast;
150
+ if (parentPath.isCallExpression({
151
+ callee: maybeWrapped.node
152
+ }) && path.isOptionalMemberExpression()) {
153
+ wrapLast = replacement => {
154
+ var _baseRef;
155
+ const object = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrapperNodes)(replacement.object);
156
+ let baseRef;
157
+ if (!assumptions.pureGetters || !isSimpleMemberExpression(object)) {
158
+ baseRef = scope.maybeGenerateMemoised(object);
159
+ if (baseRef) {
160
+ replacement.object = _core.types.assignmentExpression("=", baseRef, object);
161
+ }
132
162
  }
133
- }
134
- replacement = _core.types.callExpression(_core.types.memberExpression(replacement, _core.types.identifier("bind")), [_core.types.cloneNode((_baseRef = baseRef) != null ? _baseRef : object)]);
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"));
163
+ return _core.types.callExpression(_core.types.memberExpression(replacement, _core.types.identifier("bind")), [_core.types.cloneNode((_baseRef = baseRef) != null ? _baseRef : object)]);
164
+ };
147
165
  }
166
+ transformOptionalChain(path, assumptions, path, (0, _util.willPathCastToBoolean)(maybeWrapped) ? _core.types.booleanLiteral(false) : scope.buildUndefinedNode(), wrapLast);
148
167
  }
149
168
  }
150
169
 
@@ -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 // @ts-expect-error todo(flow->ts)\n replacementPath.get(\"alternate\"),\n );\n }\n }\n}\n"],"mappings":";;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAEA,IAAAC,wCAAA,GAAAD,OAAA;AAIA,IAAAE,KAAA,GAAAF,OAAA;AAEA,MAAM;EAAEG;AAAI,CAAC,GAAGC,cAAQ,CAACC,UAAU;AAEnC,SAASC,wBAAwBA,CAC/BD,UAAkC,EACyB;EA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E,CAAC;MACDvB,eAAe,GAAG,IAAArB,oEAA2B,EAE3CqB,eAAe,CAACpB,GAAG,CAAC,WAAW,CACjC,CAAC;IACH;EACF;AACF"}
1
+ {"version":3,"names":["_core","require","_helperSkipTransparentExpressionWrappers","_util","isSimpleMemberExpression","expression","skipTransparentExprWrapperNodes","t","isIdentifier","isSuper","isMemberExpression","computed","object","needsMemoize","path","optionalPath","scope","isOptionalMemberExpression","isOptionalCallExpression","node","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","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","findOutermostTransparentParent","parentPath","isUnaryExpression","operator","booleanLiteral","replacement","_baseRef","baseRef","callExpression","willPathCastToBoolean","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,IAAAA,KAAA,GAAAC,OA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KAAK,CAAC,GACvB3E,KAAK,CAACiF,kBAAkB,CAAC,CAAC,EAC9B9D,QACF,CAAC;EACH;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@babel/plugin-transform-optional-chaining",
3
- "version": "7.22.5",
3
+ "version": "7.22.10",
4
4
  "description": "Transform optional chaining operators into a series of nil checks",
5
5
  "repository": {
6
6
  "type": "git",
@@ -25,10 +25,10 @@
25
25
  "@babel/core": "^7.0.0-0"
26
26
  },
27
27
  "devDependencies": {
28
- "@babel/core": "^7.22.5",
28
+ "@babel/core": "^7.22.10",
29
29
  "@babel/helper-plugin-test-runner": "^7.22.5",
30
- "@babel/plugin-transform-block-scoping": "^7.22.5",
31
- "@babel/traverse": "^7.22.5"
30
+ "@babel/plugin-transform-block-scoping": "^7.22.10",
31
+ "@babel/traverse": "^7.22.10"
32
32
  },
33
33
  "engines": {
34
34
  "node": ">=6.9.0"