Socket
Socket
Sign inDemoInstall

@babel/helper-module-transforms

Package Overview
Dependencies
Maintainers
4
Versions
119
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@babel/helper-module-transforms - npm Package Compare versions

Comparing version 7.22.9 to 8.0.0-alpha.0

39

lib/dynamic-import.js

@@ -1,23 +0,8 @@

"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.buildDynamicImport = buildDynamicImport;
var _core = require("@babel/core");
{
{
{
exports.getDynamicImportSource = function getDynamicImportSource(node) {
const [source] = node.arguments;
return _core.types.isStringLiteral(source) || _core.types.isTemplateLiteral(source) ? source : _core.template.expression.ast`\`\${${source}}\``;
};
}
}
}
function buildDynamicImport(node, deferToThen, wrapWithPromise, builder) {
import { types as t, template } from "@babel/core";
;
export function buildDynamicImport(node, deferToThen, wrapWithPromise, builder) {
const [specifier] = node.arguments;
if (_core.types.isStringLiteral(specifier) || _core.types.isTemplateLiteral(specifier) && specifier.quasis.length === 0) {
if (t.isStringLiteral(specifier) || t.isTemplateLiteral(specifier) && specifier.quasis.length === 0) {
if (deferToThen) {
return _core.template.expression.ast`
return template.expression.ast`
Promise.resolve().then(() => ${builder(specifier)})

@@ -27,16 +12,16 @@ `;

}
const specifierToString = _core.types.isTemplateLiteral(specifier) ? _core.types.identifier("specifier") : _core.types.templateLiteral([_core.types.templateElement({
const specifierToString = t.isTemplateLiteral(specifier) ? t.identifier("specifier") : t.templateLiteral([t.templateElement({
raw: ""
}), _core.types.templateElement({
}), t.templateElement({
raw: ""
})], [_core.types.identifier("specifier")]);
})], [t.identifier("specifier")]);
if (deferToThen) {
return _core.template.expression.ast`
return template.expression.ast`
(specifier =>
new Promise(r => r(${specifierToString}))
.then(s => ${builder(_core.types.identifier("s"))})
.then(s => ${builder(t.identifier("s"))})
)(${specifier})
`;
} else if (wrapWithPromise) {
return _core.template.expression.ast`
return template.expression.ast`
(specifier =>

@@ -47,3 +32,3 @@ new Promise(r => r(${builder(specifierToString)}))

} else {
return _core.template.expression.ast`
return template.expression.ast`
(specifier => ${builder(specifierToString)})(${specifier})

@@ -50,0 +35,0 @@ `;

@@ -1,20 +0,3 @@

"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) {
;
export default function getModuleName(rootOpts, pluginOpts) {
const {

@@ -21,0 +4,0 @@ filename,

@@ -1,54 +0,769 @@

"use strict";
import assert from 'assert';
import { traverse, types, template } from '@babel/core';
import { isModule } from '@babel/helper-module-imports';
export { isModule } from '@babel/helper-module-imports';
import environmentVisitor from '@babel/helper-environment-visitor';
import simplifyAccess from '@babel/helper-simple-access';
import { basename, extname } from 'path';
import { isIdentifierName } from '@babel/helper-validator-identifier';
import splitExportDeclaration from '@babel/helper-split-export-declaration';
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "buildDynamicImport", {
enumerable: true,
get: function () {
return _dynamicImport.buildDynamicImport;
const {
numericLiteral: numericLiteral$1,
unaryExpression
} = types;
const rewriteThisVisitor = traverse.visitors.merge([environmentVisitor, {
ThisExpression(path) {
path.replaceWith(unaryExpression("void", numericLiteral$1(0), true));
}
});
exports.buildNamespaceInitStatements = buildNamespaceInitStatements;
exports.ensureStatementsHoisted = ensureStatementsHoisted;
Object.defineProperty(exports, "getModuleName", {
enumerable: true,
get: function () {
return _getModuleName.default;
}]);
function rewriteThis(programPath) {
traverse(programPath.node, Object.assign({}, rewriteThisVisitor, {
noScope: true
}));
}
const {
assignmentExpression,
callExpression: callExpression$1,
cloneNode: cloneNode$1,
expressionStatement: expressionStatement$1,
getOuterBindingIdentifiers,
identifier: identifier$1,
isMemberExpression,
isVariableDeclaration,
jsxIdentifier,
jsxMemberExpression,
memberExpression: memberExpression$1,
numericLiteral,
sequenceExpression,
stringLiteral: stringLiteral$1,
variableDeclaration: variableDeclaration$1,
variableDeclarator: variableDeclarator$1
} = types;
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]);
}
}
});
Object.defineProperty(exports, "hasExports", {
enumerable: true,
get: function () {
return _normalizeAndLoadMetadata.hasExports;
for (const [local, data] of metadata.local) {
let exportMeta = exported.get(local);
if (!exportMeta) {
exportMeta = [];
exported.set(local, exportMeta);
}
exportMeta.push(...data.names);
}
});
Object.defineProperty(exports, "isModule", {
enumerable: true,
get: function () {
return _helperModuleImports.isModule;
const rewriteBindingInitVisitorState = {
metadata,
requeueInParent,
scope: programPath.scope,
exported
};
programPath.traverse(rewriteBindingInitVisitor, rewriteBindingInitVisitorState);
const bindingNames = new Set([...Array.from(imported.keys()), ...Array.from(exported.keys())]);
{
simplifyAccess(programPath, bindingNames);
}
});
Object.defineProperty(exports, "isSideEffectImport", {
enumerable: true,
get: function () {
return _normalizeAndLoadMetadata.isSideEffectImport;
const rewriteReferencesVisitorState = {
seen: new WeakSet(),
metadata,
requeueInParent,
scope: programPath.scope,
imported,
exported,
buildImportReference: ([source, importName, localName], identNode) => {
const meta = metadata.source.get(source);
meta.referenced = true;
if (localName) {
if (meta.lazy) {
identNode = callExpression$1(identNode, []);
}
return identNode;
}
let namespace = identifier$1(meta.name);
if (meta.lazy) namespace = callExpression$1(namespace, []);
if (importName === "default" && meta.interop === "node-default") {
return namespace;
}
const computed = metadata.stringSpecifiers.has(importName);
return memberExpression$1(namespace, computed ? stringLiteral$1(importName) : identifier$1(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$1(buildBindingExportAssignmentExpression(metadata, exportNames, identifier$1(localName), path.scope));
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$1(buildBindingExportAssignmentExpression(metadata, exportNames, identifier$1(localName), path.scope));
statement._blockHoist = path.node._blockHoist;
requeueInParent(path.insertAfter(statement)[0]);
}
});
}
});
exports.rewriteModuleStatementsAndPrepareHeader = rewriteModuleStatementsAndPrepareHeader;
Object.defineProperty(exports, "rewriteThis", {
enumerable: true,
get: function () {
return _rewriteThis.default;
};
const buildBindingExportAssignmentExpression = (metadata, exportNames, localExpr, scope) => {
const exportsObjectName = metadata.exportName;
for (let currentScope = scope; currentScope != null; currentScope = currentScope.parent) {
if (currentScope.hasOwnBinding(exportsObjectName)) {
currentScope.rename(exportsObjectName);
}
}
});
exports.wrapInterop = wrapInterop;
var _assert = require("assert");
var _core = require("@babel/core");
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 _dynamicImport = require("./dynamic-import");
var _getModuleName = require("./get-module-name");
return (exportNames || []).reduce((expr, exportName) => {
const {
stringSpecifiers
} = metadata;
const computed = stringSpecifiers.has(exportName);
return assignmentExpression("=", memberExpression$1(identifier$1(exportsObjectName), computed ? stringLiteral$1(exportName) : identifier$1(exportName), computed), expr);
}, localExpr);
};
const buildImportThrow = localName => {
return template.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?.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$1(update), path.scope));
} else {
const ref = scope.generateDeclaredUidIdentifier(localName);
path.replaceWith(sequenceExpression([assignmentExpression("=", cloneNode$1(ref), cloneNode$1(update)), buildBindingExportAssignmentExpression(this.metadata, exportedNames, identifier$1(localName), path.scope), cloneNode$1(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?.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, path.scope));
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$1(localName), path.scope));
}
});
if (items.length > 0) {
let node = sequenceExpression(items);
if (path.parentPath.isExpressionStatement()) {
node = expressionStatement$1(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$1("let", [variableDeclarator$1(cloneNode$1(newLoopId))]));
scope.registerDeclaration(path.get("left"));
if (didTransformExport) {
bodyPath.unshiftContainer("body", expressionStatement$1(assignmentExpression("=", left, newLoopId)));
}
if (importConstViolationName) {
bodyPath.unshiftContainer("body", expressionStatement$1(buildImportThrow(importConstViolationName)));
}
}
}
};
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,
sources,
hasExports
} = getModuleMetadata(programPath, {
initializeReexports,
lazy
}, stringSpecifiers);
removeImportExportDeclarations(programPath);
for (const [source, metadata] of sources) {
if (metadata.importsNamespace.size > 0) {
metadata.name = metadata.importsNamespace.values().next().value;
}
const resolvedInterop = resolveImportInterop(importInterop, 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: sources,
stringSpecifiers
};
}
function getExportSpecifierName(path, stringSpecifiers) {
if (path.isIdentifier()) {
return path.node.name;
} else if (path.isStringLiteral()) {
const stringValue = path.node.value;
if (!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-transform-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(basename(source, extname(source))).name,
interop: "none",
loc: null,
imports: new Map(),
importsNamespace: new Set(),
reexports: new Map(),
reexportNamespace: new Set(),
reexportAll: null,
lazy: false,
referenced: false
};
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");
});
data.referenced = true;
}
} 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);
});
data.referenced = true;
}
} 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);
});
data.referenced = true;
}
}
});
} 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
};
data.referenced = true;
} 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);
data.referenced = true;
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,
sources: 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;
splitExportDeclaration(child);
});
}
function removeImportExportDeclarations(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();
}
});
}
function buildDynamicImport(node, deferToThen, wrapWithPromise, builder) {
const [specifier] = node.arguments;
if (types.isStringLiteral(specifier) || types.isTemplateLiteral(specifier) && specifier.quasis.length === 0) {
if (deferToThen) {
return template.expression.ast`
Promise.resolve().then(() => ${builder(specifier)})
`;
} else return builder(specifier);
}
const specifierToString = types.isTemplateLiteral(specifier) ? types.identifier("specifier") : types.templateLiteral([types.templateElement({
raw: ""
}), types.templateElement({
raw: ""
})], [types.identifier("specifier")]);
if (deferToThen) {
return template.expression.ast`
(specifier =>
new Promise(r => r(${specifierToString}))
.then(s => ${builder(types.identifier("s"))})
)(${specifier})
`;
} else if (wrapWithPromise) {
return template.expression.ast`
(specifier =>
new Promise(r => r(${builder(specifierToString)}))
)(${specifier})
`;
} else {
return template.expression.ast`
(specifier => ${builder(specifierToString)})(${specifier})
`;
}
}
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;
}
}
const {

@@ -68,10 +783,3 @@ booleanLiteral,

variableDeclarator
} = _core.types;
{
{
{
exports.getDynamicImportSource = require("./dynamic-import").getDynamicImportSource;
}
}
}
} = types;
function rewriteModuleStatementsAndPrepareHeader(path, {

@@ -87,10 +795,10 @@ exportName,

filename,
constantReexports = arguments[1].loose,
enumerableModuleMeta = arguments[1].loose,
constantReexports = undefined,
enumerableModuleMeta = undefined,
noIncompleteNsImportDetection
}) {
(0, _normalizeAndLoadMetadata.validateImportInteropOption)(importInterop);
_assert((0, _helperModuleImports.isModule)(path), "Cannot process module statements in a script");
validateImportInteropOption(importInterop);
assert(isModule(path), "Cannot process module statements in a script");
path.node.sourceType = "script";
const meta = (0, _normalizeAndLoadMetadata.default)(path, exportName, {
const meta = normalizeModuleAndLoadMetadata(path, exportName, {
importInterop,

@@ -103,5 +811,5 @@ initializeReexports: constantReexports,

if (!allowTopLevelThis) {
(0, _rewriteThis.default)(path);
rewriteThis(path);
}
(0, _rewriteLiveReferences.default)(path, meta);
rewriteLiveReferences(path, meta);
if (strictMode !== false) {

@@ -116,3 +824,3 @@ const hasStrict = path.node.directives.some(directive => {

const headers = [];
if ((0, _normalizeAndLoadMetadata.hasExports)(meta) && !strict) {
if (hasExports(meta) && !strict) {
headers.push(buildESModuleHeader(meta, enumerableModuleMeta));

@@ -161,3 +869,3 @@ }

if (localName === sourceMetadata.name) continue;
statements.push(_core.template.statement`var NAME = SOURCE;`({
statements.push(template.statement`var NAME = SOURCE;`({
NAME: localName,

@@ -171,3 +879,3 @@ SOURCE: cloneNode(srcNamespace)

for (const exportName of sourceMetadata.reexportNamespace) {
statements.push((sourceMetadata.lazy ? _core.template.statement`
statements.push((sourceMetadata.lazy ? template.statement`
Object.defineProperty(EXPORTS, "NAME", {

@@ -179,3 +887,3 @@ enumerable: true,

});
` : _core.template.statement`EXPORTS.NAME = NAMESPACE;`)({
` : template.statement`EXPORTS.NAME = NAMESPACE;`)({
EXPORTS: metadata.exportName,

@@ -194,5 +902,5 @@ NAME: exportName,

const ReexportTemplate = {
constant: _core.template.statement`EXPORTS.EXPORT_NAME = NAMESPACE_IMPORT;`,
constantComputed: _core.template.statement`EXPORTS["EXPORT_NAME"] = NAMESPACE_IMPORT;`,
spec: _core.template.statement`
constant: template.statement`EXPORTS.EXPORT_NAME = NAMESPACE_IMPORT;`,
constantComputed: template.statement`EXPORTS["EXPORT_NAME"] = NAMESPACE_IMPORT;`,
spec: template.statement`
Object.defineProperty(EXPORTS, "EXPORT_NAME", {

@@ -213,3 +921,3 @@ enumerable: true,

let NAMESPACE_IMPORT = cloneNode(namespace);
if (importName === "default" && metadata.interop === "node-default") {} else if (stringSpecifiers.has(importName)) {
if (importName === "default" && metadata.interop === "node-default") ; else if (stringSpecifiers.has(importName)) {
NAMESPACE_IMPORT = memberExpression(NAMESPACE_IMPORT, stringLiteral(importName), true);

@@ -236,5 +944,5 @@ } else {

function buildESModuleHeader(metadata, enumerableModuleMeta = false) {
return (enumerableModuleMeta ? _core.template.statement`
return (enumerableModuleMeta ? template.statement`
EXPORTS.__esModule = true;
` : _core.template.statement`
` : template.statement`
Object.defineProperty(EXPORTS, "__esModule", {

@@ -248,3 +956,3 @@ value: true,

function buildNamespaceReexport(metadata, namespace, constantReexports) {
return (constantReexports ? _core.template.statement`
return (constantReexports ? template.statement`
Object.keys(NAMESPACE).forEach(function(key) {

@@ -257,3 +965,3 @@ if (key === "default" || key === "__esModule") return;

});
` : _core.template.statement`
` : template.statement`
Object.keys(NAMESPACE).forEach(function(key) {

@@ -274,3 +982,3 @@ if (key === "default" || key === "__esModule") return;

EXPORTS: metadata.exportName,
VERIFY_NAME_LIST: metadata.exportNameListName ? (0, _core.template)`
VERIFY_NAME_LIST: metadata.exportNameListName ? template`
if (Object.prototype.hasOwnProperty.call(EXPORTS_LIST, key)) return;

@@ -310,3 +1018,3 @@ `({

for (const [localName, data] of metadata.local) {
if (data.kind === "import") {} else if (data.kind === "hoisted") {
if (data.kind === "import") ; else if (data.kind === "hoisted") {
initStatements.push([data.names[0], buildInitStatement(metadata, data.names, identifier(localName))]);

@@ -367,4 +1075,4 @@ } else if (!noIncompleteNsImportDetection) {

const InitTemplate = {
computed: _core.template.expression`EXPORTS["NAME"] = VALUE`,
default: _core.template.expression`EXPORTS.NAME = VALUE`
computed: template.expression`EXPORTS["NAME"] = VALUE`,
default: template.expression`EXPORTS.NAME = VALUE`
};

@@ -390,2 +1098,3 @@ function buildInitStatement(metadata, exportNames, initExpr) {

export { buildDynamicImport, buildNamespaceInitStatements, ensureStatementsHoisted, getModuleName, hasExports, isSideEffectImport, rewriteModuleStatementsAndPrepareHeader, rewriteThis, wrapInterop };
//# sourceMappingURL=index.js.map

@@ -1,20 +0,11 @@

"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) {
import { basename, extname } from "path";
import { isIdentifierName } from "@babel/helper-validator-identifier";
import splitExportDeclaration from "@babel/helper-split-export-declaration";
export function hasExports(metadata) {
return metadata.hasExports;
}
function isSideEffectImport(source) {
export 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) {
export function validateImportInteropOption(importInterop) {
if (typeof importInterop !== "function" && importInterop !== "none" && importInterop !== "babel" && importInterop !== "node") {

@@ -31,3 +22,3 @@ throw new Error(`.importInterop must be one of "none", "babel", "node", or a function returning one of those values (received ${importInterop}).`);

}
function normalizeModuleAndLoadMetadata(programPath, exportName, {
export default function normalizeModuleAndLoadMetadata(programPath, exportName, {
importInterop,

@@ -82,3 +73,3 @@ initializeReexports = false,

const stringValue = path.node.value;
if (!(0, _helperValidatorIdentifier.isIdentifierName)(stringValue)) {
if (!isIdentifierName(stringValue)) {
stringSpecifiers.add(stringValue);

@@ -111,3 +102,3 @@ }

data = {
name: programPath.scope.generateUidIdentifier((0, _path.basename)(source, (0, _path.extname)(source))).name,
name: programPath.scope.generateUidIdentifier(basename(source, extname(source))).name,
interop: "none",

@@ -329,3 +320,3 @@ loc: null,

if (!child.isExportDefaultDeclaration()) return;
(0, _helperSplitExportDeclaration.default)(child);
splitExportDeclaration(child);
});

@@ -332,0 +323,0 @@ }

@@ -1,10 +0,4 @@

"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = rewriteLiveReferences;
var _assert = require("assert");
var _core = require("@babel/core");
var _helperSimpleAccess = require("@babel/helper-simple-access");
import assert from "assert";
import { template, types as t } from "@babel/core";
import simplifyAccess from "@babel/helper-simple-access";
const {

@@ -27,3 +21,3 @@ assignmentExpression,

variableDeclarator
} = _core.types;
} = t;
function isInType(path) {

@@ -47,3 +41,3 @@ do {

}
function rewriteLiveReferences(programPath, metadata) {
export default function rewriteLiveReferences(programPath, metadata) {
const imported = new Map();

@@ -79,3 +73,3 @@ const exported = new Map();

{
(0, _helperSimpleAccess.default)(programPath, bindingNames, false);
simplifyAccess(programPath, bindingNames);
}

@@ -163,3 +157,3 @@ const rewriteReferencesVisitorState = {

const buildImportThrow = localName => {
return _core.template.expression.ast`
return template.expression.ast`
(function() {

@@ -234,3 +228,3 @@ throw new Error('"' + '${localName}' + '" is read-only.');

const importData = imported.get(localName);
if ((exportedNames == null ? void 0 : exportedNames.length) > 0 || importData) {
if (exportedNames?.length > 0 || importData) {
if (importData) {

@@ -270,4 +264,4 @@ path.replaceWith(assignmentExpression(update.operator[0] + "=", buildImportReference(importData, arg.node), buildImportThrow(localName)));

const importData = imported.get(localName);
if ((exportedNames == null ? void 0 : exportedNames.length) > 0 || importData) {
_assert(path.node.operator === "=", "Path was not simplified");
if (exportedNames?.length > 0 || importData) {
assert(path.node.operator === "=", "Path was not simplified");
const assignment = path.node;

@@ -274,0 +268,0 @@ if (importData) {

@@ -1,14 +0,8 @@

"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = rewriteThis;
var _helperEnvironmentVisitor = require("@babel/helper-environment-visitor");
var _core = require("@babel/core");
import environmentVisitor from "@babel/helper-environment-visitor";
import { traverse, types as t } from "@babel/core";
const {
numericLiteral,
unaryExpression
} = _core.types;
const rewriteThisVisitor = _core.traverse.visitors.merge([_helperEnvironmentVisitor.default, {
} = t;
const rewriteThisVisitor = traverse.visitors.merge([environmentVisitor, {
ThisExpression(path) {

@@ -18,4 +12,4 @@ path.replaceWith(unaryExpression("void", numericLiteral(0), true));

}]);
function rewriteThis(programPath) {
(0, _core.traverse)(programPath.node, Object.assign({}, rewriteThisVisitor, {
export default function rewriteThis(programPath) {
traverse(programPath.node, Object.assign({}, rewriteThisVisitor, {
noScope: true

@@ -22,0 +16,0 @@ }));

{
"name": "@babel/helper-module-transforms",
"version": "7.22.9",
"version": "8.0.0-alpha.0",
"description": "Babel helper functions for implementing ES6 module transformations",

@@ -18,19 +18,23 @@ "author": "The Babel Team (https://babel.dev/team)",

"dependencies": {
"@babel/helper-environment-visitor": "^7.22.5",
"@babel/helper-module-imports": "^7.22.5",
"@babel/helper-simple-access": "^7.22.5",
"@babel/helper-split-export-declaration": "^7.22.6",
"@babel/helper-validator-identifier": "^7.22.5"
"@babel/helper-environment-visitor": "^8.0.0-alpha.0",
"@babel/helper-module-imports": "^8.0.0-alpha.0",
"@babel/helper-simple-access": "^8.0.0-alpha.0",
"@babel/helper-split-export-declaration": "^8.0.0-alpha.0",
"@babel/helper-validator-identifier": "^8.0.0-alpha.0"
},
"devDependencies": {
"@babel/core": "^7.22.9",
"@babel/traverse": "^7.22.8"
"@babel/core": "^8.0.0-alpha.0",
"@babel/traverse": "^8.0.0-alpha.0"
},
"peerDependencies": {
"@babel/core": "^7.0.0"
"@babel/core": "^8.0.0-alpha.0"
},
"engines": {
"node": ">=6.9.0"
"node": "^16.20.0 || ^18.16.0 || >=20.0.0"
},
"type": "commonjs"
"exports": {
".": "./lib/index.js",
"./package.json": "./package.json"
},
"type": "module"
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc