Commit 0ae470fd authored by Rosanny Sihombing's avatar Rosanny Sihombing
Browse files

Merge branch 'MLAB-670' into 'testing'

Update required modules

See merge request !162
parents cad730bf d27c335f
Pipeline #6650 passed with stage
in 4 seconds
MIT License
Copyright (c) 2014-present Sebastian McKenzie and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# @babel/helper-member-expression-to-functions
> Helper function to replace certain member expressions with function calls
See our website [@babel/helper-member-expression-to-functions](https://babeljs.io/docs/en/babel-helper-member-expression-to-functions) for more information.
## Install
Using npm:
```sh
npm install --save @babel/helper-member-expression-to-functions
```
or using yarn:
```sh
yarn add @babel/helper-member-expression-to-functions
```
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var _t = require('@babel/types');
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n["default"] = e;
return Object.freeze(n);
}
var _t__namespace = /*#__PURE__*/_interopNamespace(_t);
function willPathCastToBoolean(path) {
const maybeWrapped = path;
const {
node,
parentPath
} = maybeWrapped;
if (parentPath.isLogicalExpression()) {
const {
operator,
right
} = parentPath.node;
if (operator === "&&" || operator === "||" || operator === "??" && node === right) {
return willPathCastToBoolean(parentPath);
}
}
if (parentPath.isSequenceExpression()) {
const {
expressions
} = parentPath.node;
if (expressions[expressions.length - 1] === node) {
return willPathCastToBoolean(parentPath);
} else {
return true;
}
}
return parentPath.isConditional({
test: node
}) || parentPath.isUnaryExpression({
operator: "!"
}) || parentPath.isLoop({
test: node
});
}
const {
LOGICAL_OPERATORS,
arrowFunctionExpression,
assignmentExpression,
binaryExpression,
booleanLiteral,
callExpression,
cloneNode,
conditionalExpression,
identifier,
isMemberExpression,
isOptionalCallExpression,
isOptionalMemberExpression,
isUpdateExpression,
logicalExpression,
memberExpression,
nullLiteral,
optionalCallExpression,
optionalMemberExpression,
sequenceExpression,
updateExpression
} = _t__namespace;
class AssignmentMemoiser {
constructor() {
this._map = void 0;
this._map = new WeakMap();
}
has(key) {
return this._map.has(key);
}
get(key) {
if (!this.has(key)) return;
const record = this._map.get(key);
const {
value
} = record;
record.count--;
if (record.count === 0) {
return assignmentExpression("=", value, key);
}
return value;
}
set(key, value, count) {
return this._map.set(key, {
count,
value
});
}
}
function toNonOptional(path, base) {
const {
node
} = path;
if (isOptionalMemberExpression(node)) {
return memberExpression(base, node.property, node.computed);
}
if (path.isOptionalCallExpression()) {
const callee = path.get("callee");
if (path.node.optional && callee.isOptionalMemberExpression()) {
const object = callee.node.object;
const context = path.scope.maybeGenerateMemoised(object);
callee.get("object").replaceWith(assignmentExpression("=", context, object));
return callExpression(memberExpression(base, identifier("call")), [context, ...path.node.arguments]);
}
return callExpression(base, path.node.arguments);
}
return path.node;
}
function isInDetachedTree(path) {
while (path) {
if (path.isProgram()) break;
const {
parentPath,
container,
listKey
} = path;
const parentNode = parentPath.node;
if (listKey) {
if (container !== parentNode[listKey]) {
return true;
}
} else {
if (container !== parentNode) return true;
}
path = parentPath;
}
return false;
}
const handle = {
memoise() {},
handle(member, noDocumentAll) {
const {
node,
parent,
parentPath,
scope
} = member;
if (member.isOptionalMemberExpression()) {
if (isInDetachedTree(member)) return;
const endPath = member.find(({
node,
parent
}) => {
if (isOptionalMemberExpression(parent)) {
return parent.optional || parent.object !== node;
}
if (isOptionalCallExpression(parent)) {
return node !== member.node && parent.optional || parent.callee !== node;
}
return true;
});
if (scope.path.isPattern()) {
endPath.replaceWith(callExpression(arrowFunctionExpression([], endPath.node), []));
return;
}
const willEndPathCastToBoolean = willPathCastToBoolean(endPath);
const rootParentPath = endPath.parentPath;
if (rootParentPath.isUpdateExpression({
argument: node
}) || rootParentPath.isAssignmentExpression({
left: node
})) {
throw member.buildCodeFrameError(`can't handle assignment`);
}
const isDeleteOperation = rootParentPath.isUnaryExpression({
operator: "delete"
});
if (isDeleteOperation && endPath.isOptionalMemberExpression() && endPath.get("property").isPrivateName()) {
throw member.buildCodeFrameError(`can't delete a private class element`);
}
let startingOptional = member;
for (;;) {
if (startingOptional.isOptionalMemberExpression()) {
if (startingOptional.node.optional) break;
startingOptional = startingOptional.get("object");
continue;
} else if (startingOptional.isOptionalCallExpression()) {
if (startingOptional.node.optional) break;
startingOptional = startingOptional.get("callee");
continue;
}
throw new Error(`Internal error: unexpected ${startingOptional.node.type}`);
}
const startingNode = startingOptional.isOptionalMemberExpression() ? startingOptional.node.object : startingOptional.node.callee;
const baseNeedsMemoised = scope.maybeGenerateMemoised(startingNode);
const baseRef = baseNeedsMemoised != null ? baseNeedsMemoised : startingNode;
const parentIsOptionalCall = parentPath.isOptionalCallExpression({
callee: node
});
const isOptionalCall = parent => parentIsOptionalCall;
const parentIsCall = parentPath.isCallExpression({
callee: node
});
startingOptional.replaceWith(toNonOptional(startingOptional, baseRef));
if (isOptionalCall()) {
if (parent.optional) {
parentPath.replaceWith(this.optionalCall(member, parent.arguments));
} else {
parentPath.replaceWith(this.call(member, parent.arguments));
}
} else if (parentIsCall) {
member.replaceWith(this.boundGet(member));
} else {
member.replaceWith(this.get(member));
}
let regular = member.node;
for (let current = member; current !== endPath;) {
const parentPath = current.parentPath;
if (parentPath === endPath && isOptionalCall() && parent.optional) {
regular = parentPath.node;
break;
}
regular = toNonOptional(parentPath, regular);
current = parentPath;
}
let context;
const endParentPath = endPath.parentPath;
if (isMemberExpression(regular) && endParentPath.isOptionalCallExpression({
callee: endPath.node,
optional: true
})) {
const {
object
} = regular;
context = member.scope.maybeGenerateMemoised(object);
if (context) {
regular.object = assignmentExpression("=", context, object);
}
}
let replacementPath = endPath;
if (isDeleteOperation) {
replacementPath = endParentPath;
regular = endParentPath.node;
}
const baseMemoised = baseNeedsMemoised ? assignmentExpression("=", cloneNode(baseRef), cloneNode(startingNode)) : cloneNode(baseRef);
if (willEndPathCastToBoolean) {
let nonNullishCheck;
if (noDocumentAll) {
nonNullishCheck = binaryExpression("!=", baseMemoised, nullLiteral());
} else {
nonNullishCheck = logicalExpression("&&", binaryExpression("!==", baseMemoised, nullLiteral()), binaryExpression("!==", cloneNode(baseRef), scope.buildUndefinedNode()));
}
replacementPath.replaceWith(logicalExpression("&&", nonNullishCheck, regular));
} else {
let nullishCheck;
if (noDocumentAll) {
nullishCheck = binaryExpression("==", baseMemoised, nullLiteral());
} else {
nullishCheck = logicalExpression("||", binaryExpression("===", baseMemoised, nullLiteral()), binaryExpression("===", cloneNode(baseRef), scope.buildUndefinedNode()));
}
replacementPath.replaceWith(conditionalExpression(nullishCheck, isDeleteOperation ? booleanLiteral(true) : scope.buildUndefinedNode(), regular));
}
if (context) {
const endParent = endParentPath.node;
endParentPath.replaceWith(optionalCallExpression(optionalMemberExpression(endParent.callee, identifier("call"), false, true), [cloneNode(context), ...endParent.arguments], false));
}
return;
}
if (isUpdateExpression(parent, {
argument: node
})) {
if (this.simpleSet) {
member.replaceWith(this.simpleSet(member));
return;
}
const {
operator,
prefix
} = parent;
this.memoise(member, 2);
const ref = scope.generateUidIdentifierBasedOnNode(node);
scope.push({
id: ref
});
const seq = [assignmentExpression("=", cloneNode(ref), this.get(member))];
if (prefix) {
seq.push(updateExpression(operator, cloneNode(ref), prefix));
const value = sequenceExpression(seq);
parentPath.replaceWith(this.set(member, value));
return;
} else {
const ref2 = scope.generateUidIdentifierBasedOnNode(node);
scope.push({
id: ref2
});
seq.push(assignmentExpression("=", cloneNode(ref2), updateExpression(operator, cloneNode(ref), prefix)), cloneNode(ref));
const value = sequenceExpression(seq);
parentPath.replaceWith(sequenceExpression([this.set(member, value), cloneNode(ref2)]));
return;
}
}
if (parentPath.isAssignmentExpression({
left: node
})) {
if (this.simpleSet) {
member.replaceWith(this.simpleSet(member));
return;
}
const {
operator,
right: value
} = parentPath.node;
if (operator === "=") {
parentPath.replaceWith(this.set(member, value));
} else {
const operatorTrunc = operator.slice(0, -1);
if (LOGICAL_OPERATORS.includes(operatorTrunc)) {
this.memoise(member, 1);
parentPath.replaceWith(logicalExpression(operatorTrunc, this.get(member), this.set(member, value)));
} else {
this.memoise(member, 2);
parentPath.replaceWith(this.set(member, binaryExpression(operatorTrunc, this.get(member), value)));
}
}
return;
}
if (parentPath.isCallExpression({
callee: node
})) {
parentPath.replaceWith(this.call(member, parentPath.node.arguments));
return;
}
if (parentPath.isOptionalCallExpression({
callee: node
})) {
if (scope.path.isPattern()) {
parentPath.replaceWith(callExpression(arrowFunctionExpression([], parentPath.node), []));
return;
}
parentPath.replaceWith(this.optionalCall(member, parentPath.node.arguments));
return;
}
if (parentPath.isForXStatement({
left: node
}) || parentPath.isObjectProperty({
value: node
}) && parentPath.parentPath.isObjectPattern() || parentPath.isAssignmentPattern({
left: node
}) && parentPath.parentPath.isObjectProperty({
value: parent
}) && parentPath.parentPath.parentPath.isObjectPattern() || parentPath.isArrayPattern() || parentPath.isAssignmentPattern({
left: node
}) && parentPath.parentPath.isArrayPattern() || parentPath.isRestElement()) {
member.replaceWith(this.destructureSet(member));
return;
}
if (parentPath.isTaggedTemplateExpression()) {
member.replaceWith(this.boundGet(member));
} else {
member.replaceWith(this.get(member));
}
}
};
function memberExpressionToFunctions(path, visitor, state) {
path.traverse(visitor, Object.assign({}, handle, state, {
memoiser: new AssignmentMemoiser()
}));
}
exports["default"] = memberExpressionToFunctions;
//# sourceMappingURL=index.js.map
{"version":3,"file":"index.js","sources":["../src/util.ts","../src/index.ts"],"sourcesContent":["import type { NodePath } from \"@babel/traverse\";\n\n/**\n * Test if a NodePath will be cast to boolean when evaluated.\n *\n * @example\n * // returns true\n * const nodePathAQDotB = NodePath(\"if (a?.#b) {}\").get(\"test\"); // a?.#b\n * willPathCastToBoolean(nodePathAQDotB)\n * @example\n * // returns false\n * willPathCastToBoolean(NodePath(\"a?.#b\"))\n * @todo Respect transparent expression wrappers\n * @see {@link packages/babel-plugin-proposal-optional-chaining/src/util.js}\n * @param {NodePath} path\n * @returns {boolean}\n */\nexport function willPathCastToBoolean(path: NodePath): boolean {\n const maybeWrapped = 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","import type { NodePath, Visitor } from \"@babel/traverse\";\nimport {\n LOGICAL_OPERATORS,\n arrowFunctionExpression,\n assignmentExpression,\n binaryExpression,\n booleanLiteral,\n callExpression,\n cloneNode,\n conditionalExpression,\n identifier,\n isMemberExpression,\n isOptionalCallExpression,\n isOptionalMemberExpression,\n isUpdateExpression,\n logicalExpression,\n memberExpression,\n nullLiteral,\n optionalCallExpression,\n optionalMemberExpression,\n sequenceExpression,\n updateExpression,\n} from \"@babel/types\";\nimport type * as t from \"@babel/types\";\nimport { willPathCastToBoolean } from \"./util\";\n\nclass AssignmentMemoiser {\n private _map: WeakMap<t.Expression, { count: number; value: t.Identifier }>;\n constructor() {\n this._map = new WeakMap();\n }\n\n has(key: t.Expression) {\n return this._map.has(key);\n }\n\n get(key: t.Expression) {\n if (!this.has(key)) return;\n\n const record = this._map.get(key);\n const { value } = record;\n\n record.count--;\n if (record.count === 0) {\n // The `count` access is the outermost function call (hopefully), so it\n // does the assignment.\n return assignmentExpression(\"=\", value, key);\n }\n return value;\n }\n\n set(key: t.Expression, value: t.Identifier, count: number) {\n return this._map.set(key, { count, value });\n }\n}\n\nfunction toNonOptional(\n path: NodePath<t.Expression>,\n base: t.Expression,\n): t.Expression {\n const { node } = path;\n if (isOptionalMemberExpression(node)) {\n return memberExpression(base, node.property, node.computed);\n }\n\n if (path.isOptionalCallExpression()) {\n const callee = path.get(\"callee\");\n if (path.node.optional && callee.isOptionalMemberExpression()) {\n // object must be a conditional expression because the optional private access in object has been transformed\n const object = callee.node.object as t.ConditionalExpression;\n const context = path.scope.maybeGenerateMemoised(object);\n callee\n .get(\"object\")\n .replaceWith(assignmentExpression(\"=\", context, object));\n\n return callExpression(memberExpression(base, identifier(\"call\")), [\n context,\n ...path.node.arguments,\n ]);\n }\n\n return callExpression(base, path.node.arguments);\n }\n\n return path.node;\n}\n\n// Determines if the current path is in a detached tree. This can happen when\n// we are iterating on a path, and replace an ancestor with a new node. Babel\n// doesn't always stop traversing the old node tree, and that can cause\n// inconsistencies.\nfunction isInDetachedTree(path: NodePath) {\n while (path) {\n if (path.isProgram()) break;\n\n const { parentPath, container, listKey } = path;\n const parentNode = parentPath.node;\n if (listKey) {\n if (\n container !==\n // @ts-expect-error listKey must be a valid parent node key\n parentNode[listKey]\n ) {\n return true;\n }\n } else {\n if (container !== parentNode) return true;\n }\n\n path = parentPath;\n }\n\n return false;\n}\n\ntype Member = NodePath<t.OptionalMemberExpression | t.MemberExpression>;\n\nconst handle = {\n memoise() {\n // noop.\n },\n\n handle(this: HandlerState, member: Member, noDocumentAll: boolean) {\n const { node, parent, parentPath, scope } = member;\n\n if (member.isOptionalMemberExpression()) {\n // Transforming optional chaining requires we replace ancestors.\n if (isInDetachedTree(member)) return;\n\n // We're looking for the end of _this_ optional chain, which is actually\n // the \"rightmost\" property access of the chain. This is because\n // everything up to that property access is \"optional\".\n //\n // Let's take the case of `FOO?.BAR.baz?.qux`, with `FOO?.BAR` being our\n // member. The \"end\" to most users would be `qux` property access.\n // Everything up to it could be skipped if it `FOO` were nullish. But\n // actually, we can consider the `baz` access to be the end. So we're\n // looking for the nearest optional chain that is `optional: true`.\n const endPath = member.find(({ node, parent }) => {\n if (isOptionalMemberExpression(parent)) {\n // We need to check `parent.object` since we could be inside the\n // computed expression of a `bad?.[FOO?.BAR]`. In this case, the\n // endPath is the `FOO?.BAR` member itself.\n return parent.optional || parent.object !== node;\n }\n if (isOptionalCallExpression(parent)) {\n // Checking `parent.callee` since we could be in the arguments, eg\n // `bad?.(FOO?.BAR)`.\n // Also skip `FOO?.BAR` in `FOO?.BAR?.()` since we need to transform the optional call to ensure proper this\n return (\n // In FOO?.#BAR?.(), endPath points the optional call expression so we skip FOO?.#BAR\n (node !== member.node && parent.optional) || parent.callee !== node\n );\n }\n return true;\n }) as NodePath<t.OptionalMemberExpression>;\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 // This can be further optimized to avoid unecessary IIFE\n if (scope.path.isPattern()) {\n endPath.replaceWith(\n // The injected member will be queued and eventually transformed when visited\n callExpression(arrowFunctionExpression([], endPath.node), []),\n );\n return;\n }\n\n const willEndPathCastToBoolean = willPathCastToBoolean(endPath);\n\n const rootParentPath = endPath.parentPath;\n if (\n rootParentPath.isUpdateExpression({ argument: node }) ||\n rootParentPath.isAssignmentExpression({ left: node })\n ) {\n throw member.buildCodeFrameError(`can't handle assignment`);\n }\n const isDeleteOperation = rootParentPath.isUnaryExpression({\n operator: \"delete\",\n });\n if (\n isDeleteOperation &&\n endPath.isOptionalMemberExpression() &&\n endPath.get(\"property\").isPrivateName()\n ) {\n // @babel/parser will throw error on `delete obj?.#x`.\n // This error serves as fallback when `delete obj?.#x` is constructed from babel types\n throw member.buildCodeFrameError(\n `can't delete a private class element`,\n );\n }\n\n // Now, we're looking for the start of this optional chain, which is\n // optional to the left of this member.\n //\n // Let's take the case of `foo?.bar?.baz.QUX?.BAM`, with `QUX?.BAM` being\n // our member. The \"start\" to most users would be `foo` object access.\n // But actually, we can consider the `bar` access to be the start. So\n // we're looking for the nearest optional chain that is `optional: true`,\n // which is guaranteed to be somewhere in the object/callee tree.\n let startingOptional: NodePath<t.Expression> = member;\n for (;;) {\n if (startingOptional.isOptionalMemberExpression()) {\n if (startingOptional.node.optional) break;\n startingOptional = startingOptional.get(\"object\");\n continue;\n } else if (startingOptional.isOptionalCallExpression()) {\n if (startingOptional.node.optional) break;\n startingOptional = startingOptional.get(\"callee\");\n continue;\n }\n // prevent infinite loop: unreachable if the AST is well-formed\n throw new Error(\n `Internal error: unexpected ${startingOptional.node.type}`,\n );\n }\n\n const startingNode = startingOptional.isOptionalMemberExpression()\n ? startingOptional.node.object\n : startingOptional.node.callee;\n const baseNeedsMemoised = scope.maybeGenerateMemoised(startingNode);\n const baseRef = baseNeedsMemoised ?? startingNode;\n\n // Compute parentIsOptionalCall before `startingOptional` is replaced\n // as `node` may refer to `startingOptional.node` before replaced.\n const parentIsOptionalCall = parentPath.isOptionalCallExpression({\n callee: node,\n });\n // here we use a function to wrap `parentIsOptionalCall` to get type\n // for parent, do not use it anywhere else\n // See https://github.com/microsoft/TypeScript/issues/10421\n const isOptionalCall = (\n parent: t.Node,\n ): parent is t.OptionalCallExpression => parentIsOptionalCall;\n // if parentIsCall is true, it implies that node.extra.parenthesized is always true\n const parentIsCall = parentPath.isCallExpression({ callee: node });\n startingOptional.replaceWith(toNonOptional(startingOptional, baseRef));\n if (isOptionalCall(parent)) {\n if (parent.optional) {\n parentPath.replaceWith(this.optionalCall(member, parent.arguments));\n } else {\n parentPath.replaceWith(this.call(member, parent.arguments));\n }\n } else if (parentIsCall) {\n // `(a?.#b)()` to `(a == null ? void 0 : a.#b.bind(a))()`\n member.replaceWith(this.boundGet(member));\n } else {\n member.replaceWith(this.get(member));\n }\n\n let regular: t.Expression = member.node;\n for (let current: NodePath = member; current !== endPath; ) {\n const parentPath = current.parentPath as NodePath<t.Expression>;\n // skip transforming `Foo.#BAR?.call(FOO)`\n if (\n parentPath === endPath &&\n isOptionalCall(parent) &&\n parent.optional\n ) {\n regular = parentPath.node;\n break;\n }\n regular = toNonOptional(parentPath, regular);\n current = parentPath;\n }\n\n let context: t.Identifier;\n const endParentPath = endPath.parentPath as NodePath<t.Expression>;\n if (\n isMemberExpression(regular) &&\n endParentPath.isOptionalCallExpression({\n callee: endPath.node,\n optional: true,\n })\n ) {\n const { object } = regular;\n context = member.scope.maybeGenerateMemoised(object);\n if (context) {\n regular.object = assignmentExpression(\"=\", context, object);\n }\n }\n\n let replacementPath: NodePath = endPath;\n if (isDeleteOperation) {\n replacementPath = endParentPath;\n regular = endParentPath.node;\n }\n\n const baseMemoised = baseNeedsMemoised\n ? assignmentExpression(\n \"=\",\n // When base needs memoised, the baseRef must be an identifier\n cloneNode(baseRef as t.Identifier),\n cloneNode(startingNode),\n )\n : cloneNode(baseRef);\n\n if (willEndPathCastToBoolean) {\n let nonNullishCheck;\n if (noDocumentAll) {\n nonNullishCheck = binaryExpression(\"!=\", baseMemoised, nullLiteral());\n } else {\n nonNullishCheck = logicalExpression(\n \"&&\",\n binaryExpression(\"!==\", baseMemoised, nullLiteral()),\n binaryExpression(\n \"!==\",\n cloneNode(baseRef),\n scope.buildUndefinedNode(),\n ),\n );\n }\n replacementPath.replaceWith(\n logicalExpression(\"&&\", nonNullishCheck, regular),\n );\n } else {\n let nullishCheck;\n if (noDocumentAll) {\n nullishCheck = binaryExpression(\"==\", baseMemoised, nullLiteral());\n } else {\n nullishCheck = logicalExpression(\n \"||\",\n binaryExpression(\"===\", baseMemoised, nullLiteral()),\n binaryExpression(\n \"===\",\n cloneNode(baseRef),\n scope.buildUndefinedNode(),\n ),\n );\n }\n\n replacementPath.replaceWith(\n conditionalExpression(\n nullishCheck,\n isDeleteOperation\n ? booleanLiteral(true)\n : scope.buildUndefinedNode(),\n regular,\n ),\n );\n }\n\n // context and isDeleteOperation can not be both truthy\n if (context) {\n const endParent = endParentPath.node as t.OptionalCallExpression;\n endParentPath.replaceWith(\n optionalCallExpression(\n optionalMemberExpression(\n endParent.callee,\n identifier(\"call\"),\n false,\n true,\n ),\n [cloneNode(context), ...endParent.arguments],\n false,\n ),\n );\n }\n\n return;\n }\n\n // MEMBER++ -> _set(MEMBER, (ref = _get(MEMBER), ref2 = ref++, ref)), ref2\n // ++MEMBER -> _set(MEMBER, (ref = _get(MEMBER), ++ref))\n if (isUpdateExpression(parent, { argument: node })) {\n if (this.simpleSet) {\n member.replaceWith(this.simpleSet(member));\n return;\n }\n\n const { operator, prefix } = parent;\n\n // Give the state handler a chance to memoise the member, since we'll\n // reference it twice. The second access (the set) should do the memo\n // assignment.\n this.memoise(member, 2);\n\n const ref = scope.generateUidIdentifierBasedOnNode(node);\n scope.push({ id: ref });\n\n const seq: t.Expression[] = [\n // ref = _get(MEMBER)\n assignmentExpression(\"=\", cloneNode(ref), this.get(member)),\n ];\n\n if (prefix) {\n seq.push(updateExpression(operator, cloneNode(ref), prefix));\n\n // (ref = _get(MEMBER), ++ref)\n const value = sequenceExpression(seq);\n parentPath.replaceWith(this.set(member, value));\n\n return;\n } else {\n const ref2 = scope.generateUidIdentifierBasedOnNode(node);\n scope.push({ id: ref2 });\n\n seq.push(\n assignmentExpression(\n \"=\",\n cloneNode(ref2),\n updateExpression(operator, cloneNode(ref), prefix),\n ),\n cloneNode(ref),\n );\n\n // (ref = _get(MEMBER), ref2 = ref++, ref)\n const value = sequenceExpression(seq);\n parentPath.replaceWith(\n sequenceExpression([this.set(member, value), cloneNode(ref2)]),\n );\n\n return;\n }\n }\n\n // MEMBER = VALUE -> _set(MEMBER, VALUE)\n // MEMBER += VALUE -> _set(MEMBER, _get(MEMBER) + VALUE)\n // MEMBER ??= VALUE -> _get(MEMBER) ?? _set(MEMBER, VALUE)\n if (parentPath.isAssignmentExpression({ left: node })) {\n if (this.simpleSet) {\n member.replaceWith(this.simpleSet(member));\n return;\n }\n\n const { operator, right: value } = parentPath.node;\n\n if (operator === \"=\") {\n parentPath.replaceWith(this.set(member, value));\n } else {\n const operatorTrunc = operator.slice(0, -1);\n if (LOGICAL_OPERATORS.includes(operatorTrunc)) {\n // Give the state handler a chance to memoise the member, since we'll\n // reference it twice. The first access (the get) should do the memo\n // assignment.\n this.memoise(member, 1);\n parentPath.replaceWith(\n logicalExpression(\n operatorTrunc as t.LogicalExpression[\"operator\"],\n this.get(member),\n this.set(member, value),\n ),\n );\n } else {\n // Here, the second access (the set) is evaluated first.\n this.memoise(member, 2);\n parentPath.replaceWith(\n this.set(\n member,\n binaryExpression(\n operatorTrunc as t.BinaryExpression[\"operator\"],\n this.get(member),\n value,\n ),\n ),\n );\n }\n }\n return;\n }\n\n // MEMBER(ARGS) -> _call(MEMBER, ARGS)\n if (parentPath.isCallExpression({ callee: node })) {\n parentPath.replaceWith(this.call(member, parentPath.node.arguments));\n return;\n }\n\n // MEMBER?.(ARGS) -> _optionalCall(MEMBER, ARGS)\n if (parentPath.isOptionalCallExpression({ callee: node })) {\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 // This can be further optimized to avoid unecessary IIFE\n if (scope.path.isPattern()) {\n parentPath.replaceWith(\n // The injected member will be queued and eventually transformed when visited\n callExpression(arrowFunctionExpression([], parentPath.node), []),\n );\n return;\n }\n parentPath.replaceWith(\n this.optionalCall(member, parentPath.node.arguments),\n );\n return;\n }\n\n // for (MEMBER of ARR)\n // for (MEMBER in ARR)\n // { KEY: MEMBER } = OBJ -> { KEY: _destructureSet(MEMBER) } = OBJ\n // { KEY: MEMBER = _VALUE } = OBJ -> { KEY: _destructureSet(MEMBER) = _VALUE } = OBJ\n // {...MEMBER} -> {..._destructureSet(MEMBER)}\n //\n // [MEMBER] = ARR -> [_destructureSet(MEMBER)] = ARR\n // [MEMBER = _VALUE] = ARR -> [_destructureSet(MEMBER) = _VALUE] = ARR\n // [...MEMBER] -> [..._destructureSet(MEMBER)]\n if (\n // for (MEMBER of ARR)\n // for (MEMBER in ARR)\n parentPath.isForXStatement({ left: node }) ||\n // { KEY: MEMBER } = OBJ\n (parentPath.isObjectProperty({ value: node }) &&\n parentPath.parentPath.isObjectPattern()) ||\n // { KEY: MEMBER = _VALUE } = OBJ\n (parentPath.isAssignmentPattern({ left: node }) &&\n parentPath.parentPath.isObjectProperty({ value: parent }) &&\n parentPath.parentPath.parentPath.isObjectPattern()) ||\n // [MEMBER] = ARR\n parentPath.isArrayPattern() ||\n // [MEMBER = _VALUE] = ARR\n (parentPath.isAssignmentPattern({ left: node }) &&\n parentPath.parentPath.isArrayPattern()) ||\n // {...MEMBER}\n // [...MEMBER]\n parentPath.isRestElement()\n ) {\n member.replaceWith(this.destructureSet(member));\n return;\n }\n\n if (parentPath.isTaggedTemplateExpression()) {\n // MEMBER -> _get(MEMBER).bind(this)\n member.replaceWith(this.boundGet(member));\n } else {\n // MEMBER -> _get(MEMBER)\n member.replaceWith(this.get(member));\n }\n },\n};\n\nexport interface Handler<State> {\n memoise?(\n this: HandlerState<State> & State,\n member: Member,\n count: number,\n ): void;\n destructureSet(\n this: HandlerState<State> & State,\n member: Member,\n ): t.Expression;\n boundGet(this: HandlerState<State> & State, member: Member): t.Expression;\n simpleSet?(this: HandlerState<State> & State, member: Member): t.Expression;\n get(this: HandlerState<State> & State, member: Member): t.Expression;\n set(\n this: HandlerState<State> & State,\n member: Member,\n value: t.Expression,\n ): t.Expression;\n call(\n this: HandlerState<State> & State,\n member: Member,\n args: t.CallExpression[\"arguments\"],\n ): t.Expression;\n optionalCall(\n this: HandlerState<State> & State,\n member: Member,\n args: t.OptionalCallExpression[\"arguments\"],\n ): t.Expression;\n}\n\nexport interface HandlerState<State = {}> extends Handler<State> {\n handle(\n this: HandlerState<State> & State,\n member: Member,\n noDocumentAll?: boolean,\n ): void;\n memoiser: AssignmentMemoiser;\n}\n\n// We do not provide a default traversal visitor\n// Instead, caller passes one, and must call `state.handle` on the members\n// it wishes to be transformed.\n// Additionally, the caller must pass in a state object with at least\n// get, set, and call methods.\n// Optionally, a memoise method may be defined on the state, which will be\n// called when the member is a self-referential update.\nexport default function memberExpressionToFunctions<CustomState = {}>(\n path: NodePath,\n visitor: Visitor<HandlerState<CustomState>>,\n state: Handler<CustomState> & CustomState,\n) {\n path.traverse(visitor, {\n ...handle,\n ...state,\n memoiser: new AssignmentMemoiser(),\n });\n}\n"],"names":["willPathCastToBoolean","path","maybeWrapped","node","parentPath","isLogicalExpression","operator","right","isSequenceExpression","expressions","length","isConditional","test","isUnaryExpression","isLoop","LOGICAL_OPERATORS","arrowFunctionExpression","assignmentExpression","binaryExpression","booleanLiteral","callExpression","cloneNode","conditionalExpression","identifier","isMemberExpression","isOptionalCallExpression","isOptionalMemberExpression","isUpdateExpression","logicalExpression","memberExpression","nullLiteral","optionalCallExpression","optionalMemberExpression","sequenceExpression","updateExpression","AssignmentMemoiser","constructor","_map","WeakMap","has","key","get","record","value","count","set","toNonOptional","base","property","computed","callee","optional","object","context","scope","maybeGenerateMemoised","replaceWith","arguments","isInDetachedTree","isProgram","container","listKey","parentNode","handle","memoise","member","noDocumentAll","parent","endPath","find","isPattern","willEndPathCastToBoolean","rootParentPath","argument","isAssignmentExpression","left","buildCodeFrameError","isDeleteOperation","isPrivateName","startingOptional","Error","type","startingNode","baseNeedsMemoised","baseRef","parentIsOptionalCall","isOptionalCall","parentIsCall","isCallExpression","optionalCall","call","boundGet","regular","current","endParentPath","replacementPath","baseMemoised","nonNullishCheck","buildUndefinedNode","nullishCheck","endParent","simpleSet","prefix","ref","generateUidIdentifierBasedOnNode","push","id","seq","ref2","operatorTrunc","slice","includes","isForXStatement","isObjectProperty","isObjectPattern","isAssignmentPattern","isArrayPattern","isRestElement","destructureSet","isTaggedTemplateExpression","memberExpressionToFunctions","visitor","state","traverse","memoiser"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAiBO,SAASA,qBAAT,CAA+BC,IAA/B,EAAwD;EAC7D,MAAMC,YAAY,GAAGD,IAArB,CAAA;EACA,MAAM;IAAEE,IAAF;AAAQC,IAAAA,UAAAA;AAAR,GAAA,GAAuBF,YAA7B,CAAA;;AACA,EAAA,IAAIE,UAAU,CAACC,mBAAX,EAAJ,EAAsC;IACpC,MAAM;MAAEC,QAAF;AAAYC,MAAAA,KAAAA;KAAUH,GAAAA,UAAU,CAACD,IAAvC,CAAA;;AACA,IAAA,IACEG,QAAQ,KAAK,IAAb,IACAA,QAAQ,KAAK,IADb,IAECA,QAAQ,KAAK,IAAb,IAAqBH,IAAI,KAAKI,KAHjC,EAIE;MACA,OAAOP,qBAAqB,CAACI,UAAD,CAA5B,CAAA;AACD,KAAA;AACF,GAAA;;AACD,EAAA,IAAIA,UAAU,CAACI,oBAAX,EAAJ,EAAuC;IACrC,MAAM;AAAEC,MAAAA,WAAAA;KAAgBL,GAAAA,UAAU,CAACD,IAAnC,CAAA;;IACA,IAAIM,WAAW,CAACA,WAAW,CAACC,MAAZ,GAAqB,CAAtB,CAAX,KAAwCP,IAA5C,EAAkD;MAChD,OAAOH,qBAAqB,CAACI,UAAD,CAA5B,CAAA;AACD,KAFD,MAEO;AAIL,MAAA,OAAO,IAAP,CAAA;AACD,KAAA;AACF,GAAA;;EACD,OACEA,UAAU,CAACO,aAAX,CAAyB;AAAEC,IAAAA,IAAI,EAAET,IAAAA;AAAR,GAAzB,CACAC,IAAAA,UAAU,CAACS,iBA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CAAnB,CAAA,CAAA;AACD,KAHD,MAGO;AAELA,MAAAA,MAAM,CAACT,WAAP,CAAmB,KAAKf,GAAL,CAASwB,MAAT,CAAnB,CAAA,CAAA;AACD,KAAA;AACF,GAAA;;AAxZY,CAAf,CAAA;AAyce,SAASuD,2BAAT,CACbvH,IADa,EAEbwH,OAFa,EAGbC,KAHa,EAIb;AACAzH,EAAAA,IAAI,CAAC0H,QAAL,CAAcF,OAAd,EACK1D,MAAAA,CAAAA,MAAAA,CAAAA,EAAAA,EAAAA,MADL,EAEK2D,KAFL,EAAA;IAGEE,QAAQ,EAAE,IAAIzF,kBAAJ,EAAA;AAHZ,GAAA,CAAA,CAAA,CAAA;AAKD;;;;"}
\ No newline at end of file
{
"name": "@babel/helper-member-expression-to-functions",
"version": "7.18.6",
"description": "Helper function to replace certain member expressions with function calls",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel.git",
"directory": "packages/babel-helper-member-expression-to-functions"
},
"homepage": "https://babel.dev/docs/en/next/babel-helper-member-expression-to-functions",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"main": "./lib/index.js",
"author": "The Babel Team (https://babel.dev/team)",
"dependencies": {
"@babel/types": "^7.18.6"
},
"devDependencies": {
"@babel/traverse": "^7.18.6"
},
"engines": {
"node": ">=6.9.0"
},
"type": "commonjs"
}
\ No newline at end of file
MIT License
Copyright (c) 2014-present Sebastian McKenzie and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# @babel/helper-module-imports
> Babel helper functions for inserting module loads
See our website [@babel/helper-module-imports](https://babeljs.io/docs/en/babel-helper-module-imports) for more information.
## Install
Using npm:
```sh
npm install --save @babel/helper-module-imports
```
or using yarn:
```sh
yarn add @babel/helper-module-imports
```
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _assert = require("assert");
var _t = require("@babel/types");
const {
callExpression,
cloneNode,
expressionStatement,
identifier,
importDeclaration,
importDefaultSpecifier,
importNamespaceSpecifier,
importSpecifier,
memberExpression,
stringLiteral,
variableDeclaration,
variableDeclarator
} = _t;
class ImportBuilder {
constructor(importedSource, scope, hub) {
this._statements = [];
this._resultName = null;
this._importedSource = void 0;
this._scope = scope;
this._hub = hub;
this._importedSource = importedSource;
}
done() {
return {
statements: this._statements,
resultName: this._resultName
};
}
import() {
this._statements.push(importDeclaration([], stringLiteral(this._importedSource)));
return this;
}
require() {
this._statements.push(expressionStatement(callExpression(identifier("require"), [stringLiteral(this._importedSource)])));
return this;
}
namespace(name = "namespace") {
const local = this._scope.generateUidIdentifier(name);
const statement = this._statements[this._statements.length - 1];
_assert(statement.type === "ImportDeclaration");
_assert(statement.specifiers.length === 0);
statement.specifiers = [importNamespaceSpecifier(local)];
this._resultName = cloneNode(local);
return this;
}
default(name) {
const id = this._scope.generateUidIdentifier(name);
const statement = this._statements[this._statements.length - 1];
_assert(statement.type === "ImportDeclaration");
_assert(statement.specifiers.length === 0);
statement.specifiers = [importDefaultSpecifier(id)];
this._resultName = cloneNode(id);
return this;
}
named(name, importName) {
if (importName === "default") return this.default(name);
const id = this._scope.generateUidIdentifier(name);
const statement = this._statements[this._statements.length - 1];
_assert(statement.type === "ImportDeclaration");
_assert(statement.specifiers.length === 0);
statement.specifiers = [importSpecifier(id, identifier(importName))];
this._resultName = cloneNode(id);
return this;
}
var(name) {
const id = this._scope.generateUidIdentifier(name);
let statement = this._statements[this._statements.length - 1];
if (statement.type !== "ExpressionStatement") {
_assert(this._resultName);
statement = expressionStatement(this._resultName);
this._statements.push(statement);
}
this._statements[this._statements.length - 1] = variableDeclaration("var", [variableDeclarator(id, statement.expression)]);
this._resultName = cloneNode(id);
return this;
}
defaultInterop() {
return this._interop(this._hub.addHelper("interopRequireDefault"));
}
wildcardInterop() {
return this._interop(this._hub.addHelper("interopRequireWildcard"));
}
_interop(callee) {
const statement = this._statements[this._statements.length - 1];
if (statement.type === "ExpressionStatement") {
statement.expression = callExpression(callee, [statement.expression]);
} else if (statement.type === "VariableDeclaration") {
_assert(statement.declarations.length === 1);
statement.declarations[0].init = callExpression(callee, [statement.declarations[0].init]);
} else {
_assert.fail("Unexpected type.");
}
return this;
}
prop(name) {
const statement = this._statements[this._statements.length - 1];
if (statement.type === "ExpressionStatement") {
statement.expression = memberExpression(statement.expression, identifier(name));
} else if (statement.type === "VariableDeclaration") {
_assert(statement.declarations.length === 1);
statement.declarations[0].init = memberExpression(statement.declarations[0].init, identifier(name));
} else {
_assert.fail("Unexpected type:" + statement.type);
}
return this;
}
read(name) {
this._resultName = memberExpression(this._resultName, identifier(name));
}
}
exports.default = ImportBuilder;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _assert = require("assert");
var _t = require("@babel/types");
var _importBuilder = require("./import-builder");
var _isModule = require("./is-module");
const {
numericLiteral,
sequenceExpression
} = _t;
class ImportInjector {
constructor(path, importedSource, opts) {
this._defaultOpts = {
importedSource: null,
importedType: "commonjs",
importedInterop: "babel",
importingInterop: "babel",
ensureLiveReference: false,
ensureNoContext: false,
importPosition: "before"
};
const programPath = path.find(p => p.isProgram());
this._programPath = programPath;
this._programScope = programPath.scope;
this._hub = programPath.hub;
this._defaultOpts = this._applyDefaults(importedSource, opts, true);
}
addDefault(importedSourceIn, opts) {
return this.addNamed("default", importedSourceIn, opts);
}
addNamed(importName, importedSourceIn, opts) {
_assert(typeof importName === "string");
return this._generateImport(this._applyDefaults(importedSourceIn, opts), importName);
}
addNamespace(importedSourceIn, opts) {
return this._generateImport(this._applyDefaults(importedSourceIn, opts), null);
}
addSideEffect(importedSourceIn, opts) {
return this._generateImport(this._applyDefaults(importedSourceIn, opts), void 0);
}
_applyDefaults(importedSource, opts, isInit = false) {
let newOpts;
if (typeof importedSource === "string") {
newOpts = Object.assign({}, this._defaultOpts, {
importedSource
}, opts);
} else {
_assert(!opts, "Unexpected secondary arguments.");
newOpts = Object.assign({}, this._defaultOpts, importedSource);
}
if (!isInit && opts) {
if (opts.nameHint !== undefined) newOpts.nameHint = opts.nameHint;
if (opts.blockHoist !== undefined) newOpts.blockHoist = opts.blockHoist;
}
return newOpts;
}
_generateImport(opts, importName) {
const isDefault = importName === "default";
const isNamed = !!importName && !isDefault;
const isNamespace = importName === null;
const {
importedSource,
importedType,
importedInterop,
importingInterop,
ensureLiveReference,
ensureNoContext,
nameHint,
importPosition,
blockHoist
} = opts;
let name = nameHint || importName;
const isMod = (0, _isModule.default)(this._programPath);
const isModuleForNode = isMod && importingInterop === "node";
const isModuleForBabel = isMod && importingInterop === "babel";
if (importPosition === "after" && !isMod) {
throw new Error(`"importPosition": "after" is only supported in modules`);
}
const builder = new _importBuilder.default(importedSource, this._programScope, this._hub);
if (importedType === "es6") {
if (!isModuleForNode && !isModuleForBabel) {
throw new Error("Cannot import an ES6 module from CommonJS");
}
builder.import();
if (isNamespace) {
builder.namespace(nameHint || importedSource);
} else if (isDefault || isNamed) {
builder.named(name, importName);
}
} else if (importedType !== "commonjs") {
throw new Error(`Unexpected interopType "${importedType}"`);
} else if (importedInterop === "babel") {
if (isModuleForNode) {
name = name !== "default" ? name : importedSource;
const es6Default = `${importedSource}$es6Default`;
builder.import();
if (isNamespace) {
builder.default(es6Default).var(name || importedSource).wildcardInterop();
} else if (isDefault) {
if (ensureLiveReference) {
builder.default(es6Default).var(name || importedSource).defaultInterop().read("default");
} else {
builder.default(es6Default).var(name).defaultInterop().prop(importName);
}
} else if (isNamed) {
builder.default(es6Default).read(importName);
}
} else if (isModuleForBabel) {
builder.import();
if (isNamespace) {
builder.namespace(name || importedSource);
} else if (isDefault || isNamed) {
builder.named(name, importName);
}
} else {
builder.require();
if (isNamespace) {
builder.var(name || importedSource).wildcardInterop();
} else if ((isDefault || isNamed) && ensureLiveReference) {
if (isDefault) {
name = name !== "default" ? name : importedSource;
builder.var(name).read(importName);
builder.defaultInterop();
} else {
builder.var(importedSource).read(importName);
}
} else if (isDefault) {
builder.var(name).defaultInterop().prop(importName);
} else if (isNamed) {
builder.var(name).prop(importName);
}
}
} else if (importedInterop === "compiled") {
if (isModuleForNode) {
builder.import();
if (isNamespace) {
builder.default(name || importedSource);
} else if (isDefault || isNamed) {
builder.default(importedSource).read(name);
}
} else if (isModuleForBabel) {
builder.import();
if (isNamespace) {
builder.namespace(name || importedSource);
} else if (isDefault || isNamed) {
builder.named(name, importName);
}
} else {
builder.require();
if (isNamespace) {
builder.var(name || importedSource);
} else if (isDefault || isNamed) {
if (ensureLiveReference) {
builder.var(importedSource).read(name);
} else {
builder.prop(importName).var(name);
}
}
}
} else if (importedInterop === "uncompiled") {
if (isDefault && ensureLiveReference) {
throw new Error("No live reference for commonjs default");
}
if (isModuleForNode) {
builder.import();
if (isNamespace) {
builder.default(name || importedSource);
} else if (isDefault) {
builder.default(name);
} else if (isNamed) {
builder.default(importedSource).read(name);
}
} else if (isModuleForBabel) {
builder.import();
if (isNamespace) {
builder.default(name || importedSource);
} else if (isDefault) {
builder.default(name);
} else if (isNamed) {
builder.named(name, importName);
}
} else {
builder.require();
if (isNamespace) {
builder.var(name || importedSource);
} else if (isDefault) {
builder.var(name);
} else if (isNamed) {
if (ensureLiveReference) {
builder.var(importedSource).read(name);
} else {
builder.var(name).prop(importName);
}
}
}
} else {
throw new Error(`Unknown importedInterop "${importedInterop}".`);
}
const {
statements,
resultName
} = builder.done();
this._insertStatements(statements, importPosition, blockHoist);
if ((isDefault || isNamed) && ensureNoContext && resultName.type !== "Identifier") {
return sequenceExpression([numericLiteral(0), resultName]);
}
return resultName;
}
_insertStatements(statements, importPosition = "before", blockHoist = 3) {
const body = this._programPath.get("body");
if (importPosition === "after") {
for (let i = body.length - 1; i >= 0; i--) {
if (body[i].isImportDeclaration()) {
body[i].insertAfter(statements);
return;
}
}
} else {
statements.forEach(node => {
node._blockHoist = blockHoist;
});
const targetPath = body.find(p => {
const val = p.node._blockHoist;
return Number.isFinite(val) && val < 4;
});
if (targetPath) {
targetPath.insertBefore(statements);
return;
}
}
this._programPath.unshiftContainer("body", statements);
}
}
exports.default = ImportInjector;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "ImportInjector", {
enumerable: true,
get: function () {
return _importInjector.default;
}
});
exports.addDefault = addDefault;
exports.addNamed = addNamed;
exports.addNamespace = addNamespace;
exports.addSideEffect = addSideEffect;
Object.defineProperty(exports, "isModule", {
enumerable: true,
get: function () {
return _isModule.default;
}
});
var _importInjector = require("./import-injector");
var _isModule = require("./is-module");
function addDefault(path, importedSource, opts) {
return new _importInjector.default(path).addDefault(importedSource, opts);
}
function addNamed(path, name, importedSource, opts) {
return new _importInjector.default(path).addNamed(name, importedSource, opts);
}
function addNamespace(path, importedSource, opts) {
return new _importInjector.default(path).addNamespace(importedSource, opts);
}
function addSideEffect(path, importedSource, opts) {
return new _importInjector.default(path).addSideEffect(importedSource, opts);
}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isModule;
function isModule(path) {
const {
sourceType
} = path.node;
if (sourceType !== "module" && sourceType !== "script") {
throw path.buildCodeFrameError(`Unknown sourceType "${sourceType}", cannot transform.`);
}
return path.node.sourceType === "module";
}
\ No newline at end of file
{
"name": "@babel/helper-module-imports",
"version": "7.18.6",
"description": "Babel helper functions for inserting module loads",
"author": "The Babel Team (https://babel.dev/team)",
"homepage": "https://babel.dev/docs/en/next/babel-helper-module-imports",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/babel/babel.git",
"directory": "packages/babel-helper-module-imports"
},
"main": "./lib/index.js",
"dependencies": {
"@babel/types": "^7.18.6"
},
"devDependencies": {
"@babel/core": "^7.18.6",
"@babel/traverse": "^7.18.6"
},
"engines": {
"node": ">=6.9.0"
},
"type": "commonjs"
}
\ No newline at end of file
MIT License
Copyright (c) 2014-present Sebastian McKenzie and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# @babel/helper-module-transforms
> Babel helper functions for implementing ES6 module transformations
See our website [@babel/helper-module-transforms](https://babeljs.io/docs/en/babel-helper-module-transforms) for more information.
## Install
Using npm:
```sh
npm install --save @babel/helper-module-transforms
```
or using yarn:
```sh
yarn add @babel/helper-module-transforms
```
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = getModuleName;
{
const originalGetModuleName = getModuleName;
exports.default = getModuleName = function getModuleName(rootOpts, pluginOpts) {
var _pluginOpts$moduleId, _pluginOpts$moduleIds, _pluginOpts$getModule, _pluginOpts$moduleRoo;
return originalGetModuleName(rootOpts, {
moduleId: (_pluginOpts$moduleId = pluginOpts.moduleId) != null ? _pluginOpts$moduleId : rootOpts.moduleId,
moduleIds: (_pluginOpts$moduleIds = pluginOpts.moduleIds) != null ? _pluginOpts$moduleIds : rootOpts.moduleIds,
getModuleId: (_pluginOpts$getModule = pluginOpts.getModuleId) != null ? _pluginOpts$getModule : rootOpts.getModuleId,
moduleRoot: (_pluginOpts$moduleRoo = pluginOpts.moduleRoot) != null ? _pluginOpts$moduleRoo : rootOpts.moduleRoot
});
};
}
function getModuleName(rootOpts, pluginOpts) {
const {
filename,
filenameRelative = filename,
sourceRoot = pluginOpts.moduleRoot
} = rootOpts;
const {
moduleId,
moduleIds = !!moduleId,
getModuleId,
moduleRoot = sourceRoot
} = pluginOpts;
if (!moduleIds) return null;
if (moduleId != null && !getModuleId) {
return moduleId;
}
let moduleName = moduleRoot != null ? moduleRoot + "/" : "";
if (filenameRelative) {
const sourceRootReplacer = sourceRoot != null ? new RegExp("^" + sourceRoot + "/?") : "";
moduleName += filenameRelative.replace(sourceRootReplacer, "").replace(/\.(\w*?)$/, "");
}
moduleName = moduleName.replace(/\\/g, "/");
if (getModuleId) {
return getModuleId(moduleName) || moduleName;
} else {
return moduleName;
}
}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.buildNamespaceInitStatements = buildNamespaceInitStatements;
exports.ensureStatementsHoisted = ensureStatementsHoisted;
Object.defineProperty(exports, "getModuleName", {
enumerable: true,
get: function () {
return _getModuleName.default;
}
});
Object.defineProperty(exports, "hasExports", {
enumerable: true,
get: function () {
return _normalizeAndLoadMetadata.hasExports;
}
});
Object.defineProperty(exports, "isModule", {
enumerable: true,
get: function () {
return _helperModuleImports.isModule;
}
});
Object.defineProperty(exports, "isSideEffectImport", {
enumerable: true,
get: function () {
return _normalizeAndLoadMetadata.isSideEffectImport;
}
});
exports.rewriteModuleStatementsAndPrepareHeader = rewriteModuleStatementsAndPrepareHeader;
Object.defineProperty(exports, "rewriteThis", {
enumerable: true,
get: function () {
return _rewriteThis.default;
}
});
exports.wrapInterop = wrapInterop;
var _assert = require("assert");
var _t = require("@babel/types");
var _template = require("@babel/template");
var _helperModuleImports = require("@babel/helper-module-imports");
var _rewriteThis = require("./rewrite-this");
var _rewriteLiveReferences = require("./rewrite-live-references");
var _normalizeAndLoadMetadata = require("./normalize-and-load-metadata");
var _getModuleName = require("./get-module-name");
const {
booleanLiteral,
callExpression,
cloneNode,
directive,
directiveLiteral,
expressionStatement,
identifier,
isIdentifier,
memberExpression,
stringLiteral,
valueToNode,
variableDeclaration,
variableDeclarator
} = _t;
function rewriteModuleStatementsAndPrepareHeader(path, {
loose,
exportName,
strict,
allowTopLevelThis,
strictMode,
noInterop,
importInterop = noInterop ? "none" : "babel",
lazy,
esNamespaceOnly,
filename,
constantReexports = loose,
enumerableModuleMeta = loose,
noIncompleteNsImportDetection
}) {
(0, _normalizeAndLoadMetadata.validateImportInteropOption)(importInterop);
_assert((0, _helperModuleImports.isModule)(path), "Cannot process module statements in a script");
path.node.sourceType = "script";
const meta = (0, _normalizeAndLoadMetadata.default)(path, exportName, {
importInterop,
initializeReexports: constantReexports,
lazy,
esNamespaceOnly,
filename
});
if (!allowTopLevelThis) {
(0, _rewriteThis.default)(path);
}
(0, _rewriteLiveReferences.default)(path, meta);
if (strictMode !== false) {
const hasStrict = path.node.directives.some(directive => {
return directive.value.value === "use strict";
});
if (!hasStrict) {
path.unshiftContainer("directives", directive(directiveLiteral("use strict")));
}
}
const headers = [];
if ((0, _normalizeAndLoadMetadata.hasExports)(meta) && !strict) {
headers.push(buildESModuleHeader(meta, enumerableModuleMeta));
}
const nameList = buildExportNameListDeclaration(path, meta);
if (nameList) {
meta.exportNameListName = nameList.name;
headers.push(nameList.statement);
}
headers.push(...buildExportInitializationStatements(path, meta, constantReexports, noIncompleteNsImportDetection));
return {
meta,
headers
};
}
function ensureStatementsHoisted(statements) {
statements.forEach(header => {
header._blockHoist = 3;
});
}
function wrapInterop(programPath, expr, type) {
if (type === "none") {
return null;
}
if (type === "node-namespace") {
return callExpression(programPath.hub.addHelper("interopRequireWildcard"), [expr, booleanLiteral(true)]);
} else if (type === "node-default") {
return null;
}
let helper;
if (type === "default") {
helper = "interopRequireDefault";
} else if (type === "namespace") {
helper = "interopRequireWildcard";
} else {
throw new Error(`Unknown interop: ${type}`);
}
return callExpression(programPath.hub.addHelper(helper), [expr]);
}
function buildNamespaceInitStatements(metadata, sourceMetadata, constantReexports = false) {
const statements = [];
let srcNamespace = identifier(sourceMetadata.name);
if (sourceMetadata.lazy) srcNamespace = callExpression(srcNamespace, []);
for (const localName of sourceMetadata.importsNamespace) {
if (localName === sourceMetadata.name) continue;
statements.push(_template.default.statement`var NAME = SOURCE;`({
NAME: localName,
SOURCE: cloneNode(srcNamespace)
}));
}
if (constantReexports) {
statements.push(...buildReexportsFromMeta(metadata, sourceMetadata, true));
}
for (const exportName of sourceMetadata.reexportNamespace) {
statements.push((sourceMetadata.lazy ? _template.default.statement`
Object.defineProperty(EXPORTS, "NAME", {
enumerable: true,
get: function() {
return NAMESPACE;
}
});
` : _template.default.statement`EXPORTS.NAME = NAMESPACE;`)({
EXPORTS: metadata.exportName,
NAME: exportName,
NAMESPACE: cloneNode(srcNamespace)
}));
}
if (sourceMetadata.reexportAll) {
const statement = buildNamespaceReexport(metadata, cloneNode(srcNamespace), constantReexports);
statement.loc = sourceMetadata.reexportAll.loc;
statements.push(statement);
}
return statements;
}
const ReexportTemplate = {
constant: _template.default.statement`EXPORTS.EXPORT_NAME = NAMESPACE_IMPORT;`,
constantComputed: _template.default.statement`EXPORTS["EXPORT_NAME"] = NAMESPACE_IMPORT;`,
spec: _template.default.statement`
Object.defineProperty(EXPORTS, "EXPORT_NAME", {
enumerable: true,
get: function() {
return NAMESPACE_IMPORT;
},
});
`
};
const buildReexportsFromMeta = (meta, metadata, constantReexports) => {
const namespace = metadata.lazy ? callExpression(identifier(metadata.name), []) : identifier(metadata.name);
const {
stringSpecifiers
} = meta;
return Array.from(metadata.reexports, ([exportName, importName]) => {
let NAMESPACE_IMPORT = cloneNode(namespace);
if (importName === "default" && metadata.interop === "node-default") {} else if (stringSpecifiers.has(importName)) {
NAMESPACE_IMPORT = memberExpression(NAMESPACE_IMPORT, stringLiteral(importName), true);
} else {
NAMESPACE_IMPORT = memberExpression(NAMESPACE_IMPORT, identifier(importName));
}
const astNodes = {
EXPORTS: meta.exportName,
EXPORT_NAME: exportName,
NAMESPACE_IMPORT
};
if (constantReexports || isIdentifier(NAMESPACE_IMPORT)) {
if (stringSpecifiers.has(exportName)) {
return ReexportTemplate.constantComputed(astNodes);
} else {
return ReexportTemplate.constant(astNodes);
}
} else {
return ReexportTemplate.spec(astNodes);
}
});
};
function buildESModuleHeader(metadata, enumerableModuleMeta = false) {
return (enumerableModuleMeta ? _template.default.statement`
EXPORTS.__esModule = true;
` : _template.default.statement`
Object.defineProperty(EXPORTS, "__esModule", {
value: true,
});
`)({
EXPORTS: metadata.exportName
});
}
function buildNamespaceReexport(metadata, namespace, constantReexports) {
return (constantReexports ? _template.default.statement`
Object.keys(NAMESPACE).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
VERIFY_NAME_LIST;
if (key in EXPORTS && EXPORTS[key] === NAMESPACE[key]) return;
EXPORTS[key] = NAMESPACE[key];
});
` : _template.default.statement`
Object.keys(NAMESPACE).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
VERIFY_NAME_LIST;
if (key in EXPORTS && EXPORTS[key] === NAMESPACE[key]) return;
Object.defineProperty(EXPORTS, key, {
enumerable: true,
get: function() {
return NAMESPACE[key];
},
});
});
`)({
NAMESPACE: namespace,
EXPORTS: metadata.exportName,
VERIFY_NAME_LIST: metadata.exportNameListName ? (0, _template.default)`
if (Object.prototype.hasOwnProperty.call(EXPORTS_LIST, key)) return;
`({
EXPORTS_LIST: metadata.exportNameListName
}) : null
});
}
function buildExportNameListDeclaration(programPath, metadata) {
const exportedVars = Object.create(null);
for (const data of metadata.local.values()) {
for (const name of data.names) {
exportedVars[name] = true;
}
}
let hasReexport = false;
for (const data of metadata.source.values()) {
for (const exportName of data.reexports.keys()) {
exportedVars[exportName] = true;
}
for (const exportName of data.reexportNamespace) {
exportedVars[exportName] = true;
}
hasReexport = hasReexport || !!data.reexportAll;
}
if (!hasReexport || Object.keys(exportedVars).length === 0) return null;
const name = programPath.scope.generateUidIdentifier("exportNames");
delete exportedVars.default;
return {
name: name.name,
statement: variableDeclaration("var", [variableDeclarator(name, valueToNode(exportedVars))])
};
}
function buildExportInitializationStatements(programPath, metadata, constantReexports = false, noIncompleteNsImportDetection = false) {
const initStatements = [];
for (const [localName, data] of metadata.local) {
if (data.kind === "import") {} else if (data.kind === "hoisted") {
initStatements.push([data.names[0], buildInitStatement(metadata, data.names, identifier(localName))]);
} else if (!noIncompleteNsImportDetection) {
for (const exportName of data.names) {
initStatements.push([exportName, null]);
}
}
}
for (const data of metadata.source.values()) {
if (!constantReexports) {
const reexportsStatements = buildReexportsFromMeta(metadata, data, false);
const reexports = [...data.reexports.keys()];
for (let i = 0; i < reexportsStatements.length; i++) {
initStatements.push([reexports[i], reexportsStatements[i]]);
}
}
if (!noIncompleteNsImportDetection) {
for (const exportName of data.reexportNamespace) {
initStatements.push([exportName, null]);
}
}
}
initStatements.sort(([a], [b]) => {
if (a < b) return -1;
if (b < a) return 1;
return 0;
});
const results = [];
if (noIncompleteNsImportDetection) {
for (const [, initStatement] of initStatements) {
results.push(initStatement);
}
} else {
const chunkSize = 100;
for (let i = 0; i < initStatements.length; i += chunkSize) {
let uninitializedExportNames = [];
for (let j = 0; j < chunkSize && i + j < initStatements.length; j++) {
const [exportName, initStatement] = initStatements[i + j];
if (initStatement !== null) {
if (uninitializedExportNames.length > 0) {
results.push(buildInitStatement(metadata, uninitializedExportNames, programPath.scope.buildUndefinedNode()));
uninitializedExportNames = [];
}
results.push(initStatement);
} else {
uninitializedExportNames.push(exportName);
}
}
if (uninitializedExportNames.length > 0) {
results.push(buildInitStatement(metadata, uninitializedExportNames, programPath.scope.buildUndefinedNode()));
}
}
}
return results;
}
const InitTemplate = {
computed: _template.default.expression`EXPORTS["NAME"] = VALUE`,
default: _template.default.expression`EXPORTS.NAME = VALUE`
};
function buildInitStatement(metadata, exportNames, initExpr) {
const {
stringSpecifiers,
exportName: EXPORTS
} = metadata;
return expressionStatement(exportNames.reduce((acc, exportName) => {
const params = {
EXPORTS,
NAME: exportName,
VALUE: acc
};
if (stringSpecifiers.has(exportName)) {
return InitTemplate.computed(params);
} else {
return InitTemplate.default(params);
}
}, initExpr));
}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = normalizeModuleAndLoadMetadata;
exports.hasExports = hasExports;
exports.isSideEffectImport = isSideEffectImport;
exports.validateImportInteropOption = validateImportInteropOption;
var _path = require("path");
var _helperValidatorIdentifier = require("@babel/helper-validator-identifier");
var _helperSplitExportDeclaration = require("@babel/helper-split-export-declaration");
function hasExports(metadata) {
return metadata.hasExports;
}
function isSideEffectImport(source) {
return source.imports.size === 0 && source.importsNamespace.size === 0 && source.reexports.size === 0 && source.reexportNamespace.size === 0 && !source.reexportAll;
}
function validateImportInteropOption(importInterop) {
if (typeof importInterop !== "function" && importInterop !== "none" && importInterop !== "babel" && importInterop !== "node") {
throw new Error(`.importInterop must be one of "none", "babel", "node", or a function returning one of those values (received ${importInterop}).`);
}
return importInterop;
}
function resolveImportInterop(importInterop, source, filename) {
if (typeof importInterop === "function") {
return validateImportInteropOption(importInterop(source, filename));
}
return importInterop;
}
function normalizeModuleAndLoadMetadata(programPath, exportName, {
importInterop,
initializeReexports = false,
lazy = false,
esNamespaceOnly = false,
filename
}) {
if (!exportName) {
exportName = programPath.scope.generateUidIdentifier("exports").name;
}
const stringSpecifiers = new Set();
nameAnonymousExports(programPath);
const {
local,
source,
hasExports
} = getModuleMetadata(programPath, {
initializeReexports,
lazy
}, stringSpecifiers);
removeModuleDeclarations(programPath);
for (const [, metadata] of source) {
if (metadata.importsNamespace.size > 0) {
metadata.name = metadata.importsNamespace.values().next().value;
}
const resolvedInterop = resolveImportInterop(importInterop, metadata.source, filename);
if (resolvedInterop === "none") {
metadata.interop = "none";
} else if (resolvedInterop === "node" && metadata.interop === "namespace") {
metadata.interop = "node-namespace";
} else if (resolvedInterop === "node" && metadata.interop === "default") {
metadata.interop = "node-default";
} else if (esNamespaceOnly && metadata.interop === "namespace") {
metadata.interop = "default";
}
}
return {
exportName,
exportNameListName: null,
hasExports,
local,
source,
stringSpecifiers
};
}
function getExportSpecifierName(path, stringSpecifiers) {
if (path.isIdentifier()) {
return path.node.name;
} else if (path.isStringLiteral()) {
const stringValue = path.node.value;
if (!(0, _helperValidatorIdentifier.isIdentifierName)(stringValue)) {
stringSpecifiers.add(stringValue);
}
return stringValue;
} else {
throw new Error(`Expected export specifier to be either Identifier or StringLiteral, got ${path.node.type}`);
}
}
function assertExportSpecifier(path) {
if (path.isExportSpecifier()) {
return;
} else if (path.isExportNamespaceSpecifier()) {
throw path.buildCodeFrameError("Export namespace should be first transformed by `@babel/plugin-proposal-export-namespace-from`.");
} else {
throw path.buildCodeFrameError("Unexpected export specifier type");
}
}
function getModuleMetadata(programPath, {
lazy,
initializeReexports
}, stringSpecifiers) {
const localData = getLocalExportMetadata(programPath, initializeReexports, stringSpecifiers);
const sourceData = new Map();
const getData = sourceNode => {
const source = sourceNode.value;
let data = sourceData.get(source);
if (!data) {
data = {
name: programPath.scope.generateUidIdentifier((0, _path.basename)(source, (0, _path.extname)(source))).name,
interop: "none",
loc: null,
imports: new Map(),
importsNamespace: new Set(),
reexports: new Map(),
reexportNamespace: new Set(),
reexportAll: null,
lazy: false,
source
};
sourceData.set(source, data);
}
return data;
};
let hasExports = false;
programPath.get("body").forEach(child => {
if (child.isImportDeclaration()) {
const data = getData(child.node.source);
if (!data.loc) data.loc = child.node.loc;
child.get("specifiers").forEach(spec => {
if (spec.isImportDefaultSpecifier()) {
const localName = spec.get("local").node.name;
data.imports.set(localName, "default");
const reexport = localData.get(localName);
if (reexport) {
localData.delete(localName);
reexport.names.forEach(name => {
data.reexports.set(name, "default");
});
}
} else if (spec.isImportNamespaceSpecifier()) {
const localName = spec.get("local").node.name;
data.importsNamespace.add(localName);
const reexport = localData.get(localName);
if (reexport) {
localData.delete(localName);
reexport.names.forEach(name => {
data.reexportNamespace.add(name);
});
}
} else if (spec.isImportSpecifier()) {
const importName = getExportSpecifierName(spec.get("imported"), stringSpecifiers);
const localName = spec.get("local").node.name;
data.imports.set(localName, importName);
const reexport = localData.get(localName);
if (reexport) {
localData.delete(localName);
reexport.names.forEach(name => {
data.reexports.set(name, importName);
});
}
}
});
} else if (child.isExportAllDeclaration()) {
hasExports = true;
const data = getData(child.node.source);
if (!data.loc) data.loc = child.node.loc;
data.reexportAll = {
loc: child.node.loc
};
} else if (child.isExportNamedDeclaration() && child.node.source) {
hasExports = true;
const data = getData(child.node.source);
if (!data.loc) data.loc = child.node.loc;
child.get("specifiers").forEach(spec => {
assertExportSpecifier(spec);
const importName = getExportSpecifierName(spec.get("local"), stringSpecifiers);
const exportName = getExportSpecifierName(spec.get("exported"), stringSpecifiers);
data.reexports.set(exportName, importName);
if (exportName === "__esModule") {
throw spec.get("exported").buildCodeFrameError('Illegal export "__esModule".');
}
});
} else if (child.isExportNamedDeclaration() || child.isExportDefaultDeclaration()) {
hasExports = true;
}
});
for (const metadata of sourceData.values()) {
let needsDefault = false;
let needsNamed = false;
if (metadata.importsNamespace.size > 0) {
needsDefault = true;
needsNamed = true;
}
if (metadata.reexportAll) {
needsNamed = true;
}
for (const importName of metadata.imports.values()) {
if (importName === "default") needsDefault = true;else needsNamed = true;
}
for (const importName of metadata.reexports.values()) {
if (importName === "default") needsDefault = true;else needsNamed = true;
}
if (needsDefault && needsNamed) {
metadata.interop = "namespace";
} else if (needsDefault) {
metadata.interop = "default";
}
}
for (const [source, metadata] of sourceData) {
if (lazy !== false && !(isSideEffectImport(metadata) || metadata.reexportAll)) {
if (lazy === true) {
metadata.lazy = !/\./.test(source);
} else if (Array.isArray(lazy)) {
metadata.lazy = lazy.indexOf(source) !== -1;
} else if (typeof lazy === "function") {
metadata.lazy = lazy(source);
} else {
throw new Error(`.lazy must be a boolean, string array, or function`);
}
}
}
return {
hasExports,
local: localData,
source: sourceData
};
}
function getLocalExportMetadata(programPath, initializeReexports, stringSpecifiers) {
const bindingKindLookup = new Map();
programPath.get("body").forEach(child => {
let kind;
if (child.isImportDeclaration()) {
kind = "import";
} else {
if (child.isExportDefaultDeclaration()) {
child = child.get("declaration");
}
if (child.isExportNamedDeclaration()) {
if (child.node.declaration) {
child = child.get("declaration");
} else if (initializeReexports && child.node.source && child.get("source").isStringLiteral()) {
child.get("specifiers").forEach(spec => {
assertExportSpecifier(spec);
bindingKindLookup.set(spec.get("local").node.name, "block");
});
return;
}
}
if (child.isFunctionDeclaration()) {
kind = "hoisted";
} else if (child.isClassDeclaration()) {
kind = "block";
} else if (child.isVariableDeclaration({
kind: "var"
})) {
kind = "var";
} else if (child.isVariableDeclaration()) {
kind = "block";
} else {
return;
}
}
Object.keys(child.getOuterBindingIdentifiers()).forEach(name => {
bindingKindLookup.set(name, kind);
});
});
const localMetadata = new Map();
const getLocalMetadata = idPath => {
const localName = idPath.node.name;
let metadata = localMetadata.get(localName);
if (!metadata) {
const kind = bindingKindLookup.get(localName);
if (kind === undefined) {
throw idPath.buildCodeFrameError(`Exporting local "${localName}", which is not declared.`);
}
metadata = {
names: [],
kind
};
localMetadata.set(localName, metadata);
}
return metadata;
};
programPath.get("body").forEach(child => {
if (child.isExportNamedDeclaration() && (initializeReexports || !child.node.source)) {
if (child.node.declaration) {
const declaration = child.get("declaration");
const ids = declaration.getOuterBindingIdentifierPaths();
Object.keys(ids).forEach(name => {
if (name === "__esModule") {
throw declaration.buildCodeFrameError('Illegal export "__esModule".');
}
getLocalMetadata(ids[name]).names.push(name);
});
} else {
child.get("specifiers").forEach(spec => {
const local = spec.get("local");
const exported = spec.get("exported");
const localMetadata = getLocalMetadata(local);
const exportName = getExportSpecifierName(exported, stringSpecifiers);
if (exportName === "__esModule") {
throw exported.buildCodeFrameError('Illegal export "__esModule".');
}
localMetadata.names.push(exportName);
});
}
} else if (child.isExportDefaultDeclaration()) {
const declaration = child.get("declaration");
if (declaration.isFunctionDeclaration() || declaration.isClassDeclaration()) {
getLocalMetadata(declaration.get("id")).names.push("default");
} else {
throw declaration.buildCodeFrameError("Unexpected default expression export.");
}
}
});
return localMetadata;
}
function nameAnonymousExports(programPath) {
programPath.get("body").forEach(child => {
if (!child.isExportDefaultDeclaration()) return;
(0, _helperSplitExportDeclaration.default)(child);
});
}
function removeModuleDeclarations(programPath) {
programPath.get("body").forEach(child => {
if (child.isImportDeclaration()) {
child.remove();
} else if (child.isExportNamedDeclaration()) {
if (child.node.declaration) {
child.node.declaration._blockHoist = child.node._blockHoist;
child.replaceWith(child.node.declaration);
} else {
child.remove();
}
} else if (child.isExportDefaultDeclaration()) {
const declaration = child.get("declaration");
if (declaration.isFunctionDeclaration() || declaration.isClassDeclaration()) {
declaration._blockHoist = child.node._blockHoist;
child.replaceWith(declaration);
} else {
throw declaration.buildCodeFrameError("Unexpected default expression export.");
}
} else if (child.isExportAllDeclaration()) {
child.remove();
}
});
}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = rewriteLiveReferences;
var _assert = require("assert");
var _t = require("@babel/types");
var _template = require("@babel/template");
var _helperSimpleAccess = require("@babel/helper-simple-access");
const {
assignmentExpression,
callExpression,
cloneNode,
expressionStatement,
getOuterBindingIdentifiers,
identifier,
isMemberExpression,
isVariableDeclaration,
jsxIdentifier,
jsxMemberExpression,
memberExpression,
numericLiteral,
sequenceExpression,
stringLiteral,
variableDeclaration,
variableDeclarator
} = _t;
function isInType(path) {
do {
switch (path.parent.type) {
case "TSTypeAnnotation":
case "TSTypeAliasDeclaration":
case "TSTypeReference":
case "TypeAnnotation":
case "TypeAlias":
return true;
case "ExportSpecifier":
return path.parentPath.parent.exportKind === "type";
default:
if (path.parentPath.isStatement() || path.parentPath.isExpression()) {
return false;
}
}
} while (path = path.parentPath);
}
function rewriteLiveReferences(programPath, metadata) {
const imported = new Map();
const exported = new Map();
const requeueInParent = path => {
programPath.requeue(path);
};
for (const [source, data] of metadata.source) {
for (const [localName, importName] of data.imports) {
imported.set(localName, [source, importName, null]);
}
for (const localName of data.importsNamespace) {
imported.set(localName, [source, null, localName]);
}
}
for (const [local, data] of metadata.local) {
let exportMeta = exported.get(local);
if (!exportMeta) {
exportMeta = [];
exported.set(local, exportMeta);
}
exportMeta.push(...data.names);
}
const rewriteBindingInitVisitorState = {
metadata,
requeueInParent,
scope: programPath.scope,
exported
};
programPath.traverse(rewriteBindingInitVisitor, rewriteBindingInitVisitorState);
(0, _helperSimpleAccess.default)(programPath, new Set([...Array.from(imported.keys()), ...Array.from(exported.keys())]), false);
const rewriteReferencesVisitorState = {
seen: new WeakSet(),
metadata,
requeueInParent,
scope: programPath.scope,
imported,
exported,
buildImportReference: ([source, importName, localName], identNode) => {
const meta = metadata.source.get(source);
if (localName) {
if (meta.lazy) {
identNode = callExpression(identNode, []);
}
return identNode;
}
let namespace = identifier(meta.name);
if (meta.lazy) namespace = callExpression(namespace, []);
if (importName === "default" && meta.interop === "node-default") {
return namespace;
}
const computed = metadata.stringSpecifiers.has(importName);
return memberExpression(namespace, computed ? stringLiteral(importName) : identifier(importName), computed);
}
};
programPath.traverse(rewriteReferencesVisitor, rewriteReferencesVisitorState);
}
const rewriteBindingInitVisitor = {
Scope(path) {
path.skip();
},
ClassDeclaration(path) {
const {
requeueInParent,
exported,
metadata
} = this;
const {
id
} = path.node;
if (!id) throw new Error("Expected class to have a name");
const localName = id.name;
const exportNames = exported.get(localName) || [];
if (exportNames.length > 0) {
const statement = expressionStatement(buildBindingExportAssignmentExpression(metadata, exportNames, identifier(localName)));
statement._blockHoist = path.node._blockHoist;
requeueInParent(path.insertAfter(statement)[0]);
}
},
VariableDeclaration(path) {
const {
requeueInParent,
exported,
metadata
} = this;
Object.keys(path.getOuterBindingIdentifiers()).forEach(localName => {
const exportNames = exported.get(localName) || [];
if (exportNames.length > 0) {
const statement = expressionStatement(buildBindingExportAssignmentExpression(metadata, exportNames, identifier(localName)));
statement._blockHoist = path.node._blockHoist;
requeueInParent(path.insertAfter(statement)[0]);
}
});
}
};
const buildBindingExportAssignmentExpression = (metadata, exportNames, localExpr) => {
return (exportNames || []).reduce((expr, exportName) => {
const {
stringSpecifiers
} = metadata;
const computed = stringSpecifiers.has(exportName);
return assignmentExpression("=", memberExpression(identifier(metadata.exportName), computed ? stringLiteral(exportName) : identifier(exportName), computed), expr);
}, localExpr);
};
const buildImportThrow = localName => {
return _template.default.expression.ast`
(function() {
throw new Error('"' + '${localName}' + '" is read-only.');
})()
`;
};
const rewriteReferencesVisitor = {
ReferencedIdentifier(path) {
const {
seen,
buildImportReference,
scope,
imported,
requeueInParent
} = this;
if (seen.has(path.node)) return;
seen.add(path.node);
const localName = path.node.name;
const importData = imported.get(localName);
if (importData) {
if (isInType(path)) {
throw path.buildCodeFrameError(`Cannot transform the imported binding "${localName}" since it's also used in a type annotation. ` + `Please strip type annotations using @babel/preset-typescript or @babel/preset-flow.`);
}
const localBinding = path.scope.getBinding(localName);
const rootBinding = scope.getBinding(localName);
if (rootBinding !== localBinding) return;
const ref = buildImportReference(importData, path.node);
ref.loc = path.node.loc;
if ((path.parentPath.isCallExpression({
callee: path.node
}) || path.parentPath.isOptionalCallExpression({
callee: path.node
}) || path.parentPath.isTaggedTemplateExpression({
tag: path.node
})) && isMemberExpression(ref)) {
path.replaceWith(sequenceExpression([numericLiteral(0), ref]));
} else if (path.isJSXIdentifier() && isMemberExpression(ref)) {
const {
object,
property
} = ref;
path.replaceWith(jsxMemberExpression(jsxIdentifier(object.name), jsxIdentifier(property.name)));
} else {
path.replaceWith(ref);
}
requeueInParent(path);
path.skip();
}
},
UpdateExpression(path) {
const {
scope,
seen,
imported,
exported,
requeueInParent,
buildImportReference
} = this;
if (seen.has(path.node)) return;
seen.add(path.node);
const arg = path.get("argument");
if (arg.isMemberExpression()) return;
const update = path.node;
if (arg.isIdentifier()) {
const localName = arg.node.name;
if (scope.getBinding(localName) !== path.scope.getBinding(localName)) {
return;
}
const exportedNames = exported.get(localName);
const importData = imported.get(localName);
if ((exportedNames == null ? void 0 : exportedNames.length) > 0 || importData) {
if (importData) {
path.replaceWith(assignmentExpression(update.operator[0] + "=", buildImportReference(importData, arg.node), buildImportThrow(localName)));
} else if (update.prefix) {
path.replaceWith(buildBindingExportAssignmentExpression(this.metadata, exportedNames, cloneNode(update)));
} else {
const ref = scope.generateDeclaredUidIdentifier(localName);
path.replaceWith(sequenceExpression([assignmentExpression("=", cloneNode(ref), cloneNode(update)), buildBindingExportAssignmentExpression(this.metadata, exportedNames, identifier(localName)), cloneNode(ref)]));
}
}
}
requeueInParent(path);
path.skip();
},
AssignmentExpression: {
exit(path) {
const {
scope,
seen,
imported,
exported,
requeueInParent,
buildImportReference
} = this;
if (seen.has(path.node)) return;
seen.add(path.node);
const left = path.get("left");
if (left.isMemberExpression()) return;
if (left.isIdentifier()) {
const localName = left.node.name;
if (scope.getBinding(localName) !== path.scope.getBinding(localName)) {
return;
}
const exportedNames = exported.get(localName);
const importData = imported.get(localName);
if ((exportedNames == null ? void 0 : exportedNames.length) > 0 || importData) {
_assert(path.node.operator === "=", "Path was not simplified");
const assignment = path.node;
if (importData) {
assignment.left = buildImportReference(importData, left.node);
assignment.right = sequenceExpression([assignment.right, buildImportThrow(localName)]);
}
path.replaceWith(buildBindingExportAssignmentExpression(this.metadata, exportedNames, assignment));
requeueInParent(path);
}
} else {
const ids = left.getOuterBindingIdentifiers();
const programScopeIds = Object.keys(ids).filter(localName => scope.getBinding(localName) === path.scope.getBinding(localName));
const id = programScopeIds.find(localName => imported.has(localName));
if (id) {
path.node.right = sequenceExpression([path.node.right, buildImportThrow(id)]);
}
const items = [];
programScopeIds.forEach(localName => {
const exportedNames = exported.get(localName) || [];
if (exportedNames.length > 0) {
items.push(buildBindingExportAssignmentExpression(this.metadata, exportedNames, identifier(localName)));
}
});
if (items.length > 0) {
let node = sequenceExpression(items);
if (path.parentPath.isExpressionStatement()) {
node = expressionStatement(node);
node._blockHoist = path.parentPath.node._blockHoist;
}
const statement = path.insertAfter(node)[0];
requeueInParent(statement);
}
}
}
},
"ForOfStatement|ForInStatement"(path) {
const {
scope,
node
} = path;
const {
left
} = node;
const {
exported,
imported,
scope: programScope
} = this;
if (!isVariableDeclaration(left)) {
let didTransformExport = false,
importConstViolationName;
const loopBodyScope = path.get("body").scope;
for (const name of Object.keys(getOuterBindingIdentifiers(left))) {
if (programScope.getBinding(name) === scope.getBinding(name)) {
if (exported.has(name)) {
didTransformExport = true;
if (loopBodyScope.hasOwnBinding(name)) {
loopBodyScope.rename(name);
}
}
if (imported.has(name) && !importConstViolationName) {
importConstViolationName = name;
}
}
}
if (!didTransformExport && !importConstViolationName) {
return;
}
path.ensureBlock();
const bodyPath = path.get("body");
const newLoopId = scope.generateUidIdentifierBasedOnNode(left);
path.get("left").replaceWith(variableDeclaration("let", [variableDeclarator(cloneNode(newLoopId))]));
scope.registerDeclaration(path.get("left"));
if (didTransformExport) {
bodyPath.unshiftContainer("body", expressionStatement(assignmentExpression("=", left, newLoopId)));
}
if (importConstViolationName) {
bodyPath.unshiftContainer("body", expressionStatement(buildImportThrow(importConstViolationName)));
}
}
}
};
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = rewriteThis;
var _helperEnvironmentVisitor = require("@babel/helper-environment-visitor");
var _traverse = require("@babel/traverse");
var _t = require("@babel/types");
const {
numericLiteral,
unaryExpression
} = _t;
function rewriteThis(programPath) {
(0, _traverse.default)(programPath.node, Object.assign({}, rewriteThisVisitor, {
noScope: true
}));
}
const rewriteThisVisitor = _traverse.default.visitors.merge([_helperEnvironmentVisitor.default, {
ThisExpression(path) {
path.replaceWith(unaryExpression("void", numericLiteral(0), true));
}
}]);
\ No newline at end of file
{
"name": "@babel/helper-module-transforms",
"version": "7.18.6",
"description": "Babel helper functions for implementing ES6 module transformations",
"author": "The Babel Team (https://babel.dev/team)",
"homepage": "https://babel.dev/docs/en/next/babel-helper-module-transforms",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/babel/babel.git",
"directory": "packages/babel-helper-module-transforms"
},
"main": "./lib/index.js",
"dependencies": {
"@babel/helper-environment-visitor": "^7.18.6",
"@babel/helper-module-imports": "^7.18.6",
"@babel/helper-simple-access": "^7.18.6",
"@babel/helper-split-export-declaration": "^7.18.6",
"@babel/helper-validator-identifier": "^7.18.6",
"@babel/template": "^7.18.6",
"@babel/traverse": "^7.18.6",
"@babel/types": "^7.18.6"
},
"engines": {
"node": ">=6.9.0"
},
"type": "commonjs"
}
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment