Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@rollup/plugin-commonjs

Package Overview
Dependencies
Maintainers
4
Versions
73
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@rollup/plugin-commonjs - npm Package Compare versions

Comparing version 17.1.0 to 18.0.0-0

625

dist/index.es.js

@@ -12,3 +12,3 @@ import { basename, extname, dirname, sep, join, resolve } from 'path';

var peerDependencies = {
rollup: "^2.30.0"
rollup: "^2.38.0"
};

@@ -87,2 +87,4 @@

const EXTERNAL_SUFFIX = '?commonjs-external';
const EXPORTS_SUFFIX = '?commonjs-exports';
const MODULE_SUFFIX = '?commonjs-module';

@@ -132,7 +134,2 @@ const DYNAMIC_REGISTER_SUFFIX = '?commonjs-dynamic-register';

const HELPER_NON_DYNAMIC = `
export function createCommonjsModule(fn) {
var module = { exports: {} }
return fn(module, module.exports), module.exports;
}
export function commonjsRequire (target) {

@@ -144,10 +141,10 @@ throw new Error('Could not dynamically require "' + target + '". Please configure the dynamicRequireTargets option of @rollup/plugin-commonjs appropriately for this require call to behave properly.');

const HELPERS_DYNAMIC = `
export function createCommonjsModule(fn, basedir, module) {
return module = {
path: basedir,
export function createModule(modulePath) {
return {
path: modulePath,
exports: {},
require: function (path, base) {
return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
return commonjsRequire(path, base == null ? modulePath : base);
}
}, fn(module, module.exports), module.exports;
};
}

@@ -343,2 +340,20 @@

function deconflictScopes(scopes, globals, identifier) {
let i = 1;
let deconflicted = makeLegalIdentifier(identifier);
const hasConflicts = () =>
scopes.some((scope) => scope.contains(deconflicted)) || globals.has(deconflicted);
while (hasConflicts()) {
deconflicted = makeLegalIdentifier(`${identifier}_${i}`);
i += 1;
}
for (const scope of scopes) {
scope.declarations[deconflicted] = true;
}
return deconflicted;
}
function getName(id) {

@@ -401,7 +416,9 @@ const name = makeLegalIdentifier(basename(id, extname(id)));

dynamicRequireModuleSet,
(dynamicId) => `require(${JSON.stringify(wrapModuleRegisterProxy(dynamicId))});`
(dynamicId) => `require(${JSON.stringify(wrapId(dynamicId, DYNAMIC_REGISTER_SUFFIX))});`
).join('\n');
if (dynamicRequireModuleDirPaths.length) {
dynamicImports += `require(${JSON.stringify(wrapModuleRegisterProxy(DYNAMIC_PACKAGES_ID))});`;
dynamicImports += `require(${JSON.stringify(
wrapId(DYNAMIC_PACKAGES_ID, DYNAMIC_REGISTER_SUFFIX)
)});`;
}

@@ -412,14 +429,2 @@

function wrapModuleRegisterProxy(id) {
return wrapId(id, DYNAMIC_REGISTER_SUFFIX);
}
function unwrapModuleRegisterProxy(id) {
return unwrapId(id, DYNAMIC_REGISTER_SUFFIX);
}
function isModuleRegisterProxy(id) {
return isWrappedId(id, DYNAMIC_REGISTER_SUFFIX);
}
function isDynamicModuleImport(id, dynamicRequireModuleSet) {

@@ -457,16 +462,16 @@ const normalizedPath = normalizePathSlashes(id);

const isCjsPromises = new Map();
const commonJSMetaPromises = new Map();
function getIsCjsPromise(id) {
let isCjsPromise = isCjsPromises.get(id);
if (isCjsPromise) return isCjsPromise.promise;
function getCommonJSMetaPromise(id) {
let commonJSMetaPromise = commonJSMetaPromises.get(id);
if (commonJSMetaPromise) return commonJSMetaPromise.promise;
const promise = new Promise((resolve) => {
isCjsPromise = {
commonJSMetaPromise = {
resolve,
promise: null
};
isCjsPromises.set(id, isCjsPromise);
commonJSMetaPromises.set(id, commonJSMetaPromise);
});
isCjsPromise.promise = promise;
commonJSMetaPromise.promise = promise;

@@ -476,11 +481,11 @@ return promise;

function setIsCjsPromise(id, resolution) {
const isCjsPromise = isCjsPromises.get(id);
if (isCjsPromise) {
if (isCjsPromise.resolve) {
isCjsPromise.resolve(resolution);
isCjsPromise.resolve = null;
function setCommonJSMetaPromise(id, commonjsMeta) {
const commonJSMetaPromise = commonJSMetaPromises.get(id);
if (commonJSMetaPromise) {
if (commonJSMetaPromise.resolve) {
commonJSMetaPromise.resolve(commonjsMeta);
commonJSMetaPromise.resolve = null;
}
} else {
isCjsPromises.set(id, { promise: Promise.resolve(resolution), resolve: null });
commonJSMetaPromises.set(id, { promise: Promise.resolve(commonjsMeta), resolve: null });
}

@@ -491,3 +496,3 @@ }

function getSpecificHelperProxy(id) {
return `export {${id.split('?')[1]} as default} from '${HELPERS_ID}';`;
return `export {${id.split('?')[1]} as default} from "${HELPERS_ID}";`;
}

@@ -535,9 +540,9 @@

const name = getName(id);
const isCjs = await getIsCjsPromise(id);
if (isCjs) {
return `import { __moduleExports } from ${JSON.stringify(id)}; export default __moduleExports;`;
} else if (isCjs === null) {
const commonjsMeta = await getCommonJSMetaPromise(id);
if (commonjsMeta && commonjsMeta.isCommonJS) {
return `export { __moduleExports as default } from ${JSON.stringify(id)};`;
} else if (commonjsMeta === null) {
return getUnknownRequireProxy(id, requireReturnsDefault);
} else if (!requireReturnsDefault) {
return `import {getAugmentedNamespace} from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(
return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(
id

@@ -553,3 +558,3 @@ )}; export default /*@__PURE__*/getAugmentedNamespace(${name});`;

}
return `export {default} from ${JSON.stringify(id)};`;
return `export { default } from ${JSON.stringify(id)};`;
}

@@ -591,8 +596,13 @@

return function resolveId(importee, rawImporter) {
if (isWrappedId(importee, MODULE_SUFFIX) || isWrappedId(importee, EXPORTS_SUFFIX)) {
return importee;
}
const importer =
rawImporter && isModuleRegisterProxy(rawImporter)
? unwrapModuleRegisterProxy(rawImporter)
rawImporter && isWrappedId(rawImporter, DYNAMIC_REGISTER_SUFFIX)
? unwrapId(rawImporter, DYNAMIC_REGISTER_SUFFIX)
: rawImporter;
// Proxies are only importing resolved ids, no need to resolve again
// Except for exports, proxies are only importing resolved ids,
// no need to resolve again
if (importer && isWrappedId(importer, PROXY_SUFFIX)) {

@@ -611,5 +621,5 @@ return importee;

isModuleRegistration = isModuleRegisterProxy(importee);
isModuleRegistration = isWrappedId(importee, DYNAMIC_REGISTER_SUFFIX);
if (isModuleRegistration) {
importee = unwrapModuleRegisterProxy(importee);
importee = unwrapId(importee, DYNAMIC_REGISTER_SUFFIX);
}

@@ -641,3 +651,3 @@ }

} else if (resolved && isModuleRegistration) {
resolved.id = wrapModuleRegisterProxy(resolved.id);
resolved.id = wrapId(resolved.id, DYNAMIC_REGISTER_SUFFIX);
} else if (!resolved && (isProxyModule || isRequiredModule)) {

@@ -742,4 +752,2 @@ return { id: wrapId(importee, EXTERNAL_SUFFIX), external: false };

function getDefinePropertyCallName(node, targetName) {
const targetNames = targetName.split('.');
const {

@@ -752,2 +760,3 @@ callee: { object, property }

const targetNames = targetName.split('.');
const [target, key, value] = node.arguments;

@@ -794,11 +803,17 @@ if (targetNames.length === 1) {

function wrapCode(magicString, uses, moduleName, HELPERS_NAME, virtualDynamicRequirePath) {
const args = `module${uses.exports ? ', exports' : ''}`;
function wrapCode(magicString, uses, moduleName, exportsName) {
const args = [];
const passedArgs = [];
if (uses.module) {
args.push('module');
passedArgs.push(moduleName);
}
if (uses.exports) {
args.push('exports');
passedArgs.push(exportsName);
}
magicString
.trim()
.prepend(`var ${moduleName} = ${HELPERS_NAME}.createCommonjsModule(function (${args}) {\n`)
.append(
`\n}${virtualDynamicRequirePath ? `, ${JSON.stringify(virtualDynamicRequirePath)}` : ''});`
);
.prepend(`(function (${args.join(', ')}) {\n`)
.append(`\n}(${passedArgs.join(', ')}));`);
}

@@ -809,84 +824,151 @@

moduleName,
exportsName,
wrapped,
topLevelModuleExportsAssignments,
topLevelExportsAssignmentsByName,
moduleExportsAssignments,
firstTopLevelModuleExportsAssignment,
exportsAssignmentsByName,
topLevelAssignments,
defineCompiledEsmExpressions,
deconflict,
isRestorableCompiledEsm,
deconflictedExportNames,
code,
uses,
HELPERS_NAME
HELPERS_NAME,
exportMode,
detectWrappedDefault
) {
const namedExportDeclarations = [`export { ${moduleName} as __moduleExports };`];
const moduleExportsPropertyAssignments = [];
let deconflictedDefaultExportName;
const exports = [];
const exportDeclarations = [];
if (!wrapped) {
let hasModuleExportsAssignment = false;
const namedExportProperties = [];
// Collect and rewrite module.exports assignments
for (const { left } of topLevelModuleExportsAssignments) {
hasModuleExportsAssignment = true;
magicString.overwrite(left.start, left.end, `var ${moduleName}`);
if (exportMode === 'replace') {
getExportsForReplacedModuleExports(
magicString,
exports,
moduleExportsAssignments,
firstTopLevelModuleExportsAssignment,
exportsName
);
} else {
exports.push(`${exportsName} as __moduleExports`);
if (wrapped) {
getExportsWhenWrapping(
exports,
exportDeclarations,
exportsName,
detectWrappedDefault,
HELPERS_NAME
);
} else {
getExports(
magicString,
exports,
exportDeclarations,
moduleExportsAssignments,
exportsAssignmentsByName,
deconflictedExportNames,
topLevelAssignments,
moduleName,
exportsName,
defineCompiledEsmExpressions,
HELPERS_NAME
);
}
}
if (exports.length) {
exportDeclarations.push(`export { ${exports.join(', ')} };`);
}
// Collect and rewrite named exports
for (const [exportName, node] of topLevelExportsAssignmentsByName) {
const deconflicted = deconflict(exportName);
magicString.overwrite(node.start, node.left.end, `var ${deconflicted}`);
return `\n\n${exportDeclarations.join('\n')}`;
}
if (exportName === 'default') {
deconflictedDefaultExportName = deconflicted;
} else {
namedExportDeclarations.push(
exportName === deconflicted
? `export { ${exportName} };`
: `export { ${deconflicted} as ${exportName} };`
);
}
function getExportsForReplacedModuleExports(
magicString,
exports,
moduleExportsAssignments,
firstTopLevelModuleExportsAssignment,
exportsName
) {
for (const { left } of moduleExportsAssignments) {
magicString.overwrite(left.start, left.end, exportsName);
}
magicString.prependRight(firstTopLevelModuleExportsAssignment.left.start, 'var ');
exports.push(`${exportsName} as __moduleExports`, `${exportsName} as default`);
}
if (hasModuleExportsAssignment) {
moduleExportsPropertyAssignments.push(`${moduleName}.${exportName} = ${deconflicted};`);
} else {
namedExportProperties.push(`\t${exportName}: ${deconflicted}`);
function getExportsWhenWrapping(
exports,
exportDeclarations,
exportsName,
detectWrappedDefault,
HELPERS_NAME
) {
if (detectWrappedDefault) {
exportDeclarations.push(
`export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportsName});`
);
} else {
exports.push(`${exportsName} as default`);
}
}
function getExports(
magicString,
exports,
exportDeclarations,
moduleExportsAssignments,
exportsAssignmentsByName,
deconflictedExportNames,
topLevelAssignments,
moduleName,
exportsName,
defineCompiledEsmExpressions,
HELPERS_NAME
) {
let deconflictedDefaultExportName;
// Collect and rewrite module.exports assignments
for (const { left } of moduleExportsAssignments) {
magicString.overwrite(left.start, left.end, `${moduleName}.exports`);
}
// Collect and rewrite named exports
for (const [exportName, { nodes }] of exportsAssignmentsByName) {
const deconflicted = deconflictedExportNames[exportName];
let needsDeclaration = true;
for (const node of nodes) {
let replacement = `${deconflicted} = ${exportsName}.${exportName}`;
if (needsDeclaration && topLevelAssignments.has(node)) {
replacement = `var ${replacement}`;
needsDeclaration = false;
}
magicString.overwrite(node.start, node.left.end, replacement);
}
if (needsDeclaration) {
magicString.prepend(`var ${deconflicted};\n`);
}
// Regenerate CommonJS namespace
if (!hasModuleExportsAssignment) {
const moduleExports = `{\n${namedExportProperties.join(',\n')}\n}`;
magicString
.trim()
.append(
`\n\nvar ${moduleName} = ${
isRestorableCompiledEsm
? `/*#__PURE__*/Object.defineProperty(${moduleExports}, '__esModule', {value: true})`
: moduleExports
};`
);
if (exportName === 'default') {
deconflictedDefaultExportName = deconflicted;
} else {
exports.push(exportName === deconflicted ? exportName : `${deconflicted} as ${exportName}`);
}
}
// Generate default export
const defaultExport = [];
// Collect and rewrite exports.__esModule assignments
let isRestorableCompiledEsm = false;
for (const expression of defineCompiledEsmExpressions) {
isRestorableCompiledEsm = true;
const moduleExportsExpression =
expression.type === 'CallExpression' ? expression.arguments[0] : expression.left.object;
magicString.overwrite(moduleExportsExpression.start, moduleExportsExpression.end, exportsName);
}
if (isRestorableCompiledEsm) {
defaultExport.push(`export default ${deconflictedDefaultExportName || moduleName};`);
} else if (
(wrapped || deconflictedDefaultExportName) &&
(defineCompiledEsmExpressions.length > 0 || code.indexOf('__esModule') >= 0)
) {
// eslint-disable-next-line no-param-reassign
uses.commonjsHelpers = true;
defaultExport.push(
`export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${moduleName});`
);
if (moduleExportsAssignments.length === 0) {
exports.push(`${deconflictedDefaultExportName || exportsName} as default`);
} else {
exportDeclarations.push(
`export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportsName});`
);
}
} else {
defaultExport.push(`export default ${moduleName};`);
exports.push(`${exportsName} as default`);
}
return `\n\n${defaultExport
.concat(namedExportDeclarations)
.concat(moduleExportsPropertyAssignments)
.join('\n')}`;
}

@@ -1009,4 +1091,8 @@

reassignedNames,
helpersNameIfUsed,
dynamicRegisterSources
helpersName,
dynamicRegisterSources,
moduleName,
exportsName,
id,
exportMode
) {

@@ -1024,26 +1110,30 @@ const removedDeclarators = getDeclaratorsReplacedByImportsAndSetImportNames(

removeDeclaratorsFromDeclarations(topLevelDeclarations, removedDeclarators, magicString);
const importBlock = `${(helpersNameIfUsed
? [`import * as ${helpersNameIfUsed} from '${HELPERS_ID}';`]
: []
)
.concat(
// dynamic registers first, as the may be required in the other modules
[...dynamicRegisterSources].map((source) => `import '${wrapId(source, REQUIRE_SUFFIX)}';`),
// now the actual modules so that they are analyzed before creating the proxies;
// no need to do this for virtual modules as we never proxy them
requiredSources
.filter((source) => !source.startsWith('\0'))
.map((source) => `import '${wrapId(source, REQUIRE_SUFFIX)}';`),
// now the proxy modules
requiredSources.map((source) => {
const { name, nodesUsingRequired } = requiredBySource[source];
return `import ${nodesUsingRequired.length ? `${name} from ` : ``}'${
source.startsWith('\0') ? source : wrapId(source, PROXY_SUFFIX)
}';`;
})
)
.join('\n')}`;
return importBlock ? `${importBlock}\n\n` : '';
const imports = [];
imports.push(`import * as ${helpersName} from "${HELPERS_ID}";`);
if (exportMode === 'module') {
imports.push(
`import { __module as ${moduleName}, exports as ${exportsName} } from ${JSON.stringify(
wrapId(id, MODULE_SUFFIX)
)}`
);
} else if (exportMode === 'exports') {
imports.push(
`import { __exports as ${exportsName} } from ${JSON.stringify(wrapId(id, EXPORTS_SUFFIX))}`
);
}
for (const source of dynamicRegisterSources) {
imports.push(`import ${JSON.stringify(wrapId(source, REQUIRE_SUFFIX))};`);
}
for (const source of requiredSources) {
if (!source.startsWith('\0')) {
imports.push(`import ${JSON.stringify(wrapId(source, REQUIRE_SUFFIX))};`);
}
const { name, nodesUsingRequired } = requiredBySource[source];
imports.push(
`import ${nodesUsingRequired.length ? `${name} from ` : ''}${JSON.stringify(
source.startsWith('\0') ? source : wrapId(source, PROXY_SUFFIX)
)};`
);
}
return imports.length ? `${imports.join('\n')}\n\n` : '';
}

@@ -1149,5 +1239,5 @@

global: false,
require: false,
commonjsHelpers: false
require: false
};
let usesDynamicRequire = false;
const virtualDynamicRequirePath =

@@ -1160,3 +1250,2 @@ isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(dirname(id), commonDir);

let shouldWrap = false;
const defineCompiledEsmExpressions = [];

@@ -1167,3 +1256,2 @@ const globals = new Set();

const HELPERS_NAME = deconflict(scope, globals, 'commonjsHelpers');
const namedExports = {};
const dynamicRegisterSources = new Set();

@@ -1185,4 +1273,9 @@ let hasRemovedRequire = false;

const skippedNodes = new Set();
const topLevelModuleExportsAssignments = [];
const topLevelExportsAssignmentsByName = new Map();
const moduleAccessScopes = new Set([scope]);
const exportsAccessScopes = new Set([scope]);
const moduleExportsAssignments = [];
let firstTopLevelModuleExportsAssignment = null;
const exportsAssignmentsByName = new Map();
const topLevelAssignments = new Set();
const topLevelDefineCompiledEsmExpressions = [];

@@ -1227,26 +1320,30 @@ walk(ast, {

// we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` –
if (programDepth > 3) {
shouldWrap = true;
if (flattened.keypath === 'module.exports') {
moduleExportsAssignments.push(node);
if (programDepth > 3) {
moduleAccessScopes.add(scope);
} else if (!firstTopLevelModuleExportsAssignment) {
firstTopLevelModuleExportsAssignment = node;
}
} else if (exportName === KEY_COMPILED_ESM) {
defineCompiledEsmExpressions.push(parent);
} else if (flattened.keypath === 'module.exports') {
topLevelModuleExportsAssignments.push(node);
} else if (!topLevelExportsAssignmentsByName.has(exportName)) {
topLevelExportsAssignmentsByName.set(exportName, node);
if (programDepth > 3) {
shouldWrap = true;
} else {
topLevelDefineCompiledEsmExpressions.push(node);
}
} else {
shouldWrap = true;
const exportsAssignments = exportsAssignmentsByName.get(exportName) || {
nodes: [],
scopes: new Set()
};
exportsAssignments.nodes.push(node);
exportsAssignments.scopes.add(scope);
exportsAccessScopes.add(scope);
exportsAssignmentsByName.set(exportName, exportsAssignments);
if (programDepth <= 3) {
topLevelAssignments.add(node);
}
}
skippedNodes.add(node.left);
if (flattened.keypath === 'module.exports' && node.right.type === 'ObjectExpression') {
node.right.properties.forEach((prop) => {
if (prop.computed || !('key' in prop) || prop.key.type !== 'Identifier') return;
const { name } = prop.key;
if (name === makeLegalIdentifier(name)) namedExports[name] = true;
});
return;
}
if (exportsPatternMatch[1]) namedExports[exportsPatternMatch[1]] = true;
} else {

@@ -1263,3 +1360,3 @@ for (const name of extractAssignedNames(node.left)) {

skippedNodes.add(node.arguments[0]);
defineCompiledEsmExpressions.push(parent);
topLevelDefineCompiledEsmExpressions.push(node);
} else {

@@ -1292,3 +1389,2 @@ shouldWrap = true;

);
uses.commonjsHelpers = true;
return;

@@ -1320,9 +1416,9 @@ }

let sourceId = getRequireStringArg(node);
const isDynamicRegister = isModuleRegisterProxy(sourceId);
const isDynamicRegister = isWrappedId(sourceId, DYNAMIC_REGISTER_SUFFIX);
if (isDynamicRegister) {
sourceId = unwrapModuleRegisterProxy(sourceId);
sourceId = unwrapId(sourceId, DYNAMIC_REGISTER_SUFFIX);
if (sourceId.endsWith('.json')) {
sourceId = DYNAMIC_JSON_PREFIX + sourceId;
}
dynamicRegisterSources.add(wrapModuleRegisterProxy(sourceId));
dynamicRegisterSources.add(wrapId(sourceId, DYNAMIC_REGISTER_SUFFIX));
} else {

@@ -1345,3 +1441,3 @@ if (

);
uses.commonjsHelpers = true;
usesDynamicRequire = true;
}

@@ -1403,3 +1499,2 @@ return;

});
uses.commonjsHelpers = true;
}

@@ -1426,4 +1521,3 @@ }

}
uses.commonjsHelpers = true;
usesDynamicRequire = true;
return;

@@ -1441,7 +1535,8 @@ case 'module':

});
uses.commonjsHelpers = true;
}
return;
case 'define':
magicString.overwrite(node.start, node.end, 'undefined', { storeName: true });
magicString.overwrite(node.start, node.end, 'undefined', {
storeName: true
});
return;

@@ -1458,3 +1553,2 @@ default:

});
uses.commonjsHelpers = true;
skippedNodes.add(node.object);

@@ -1478,3 +1572,2 @@ skippedNodes.add(node.property);

});
uses.commonjsHelpers = true;
}

@@ -1496,3 +1589,5 @@ }

) {
magicString.overwrite(node.start, node.end, `'object'`, { storeName: false });
magicString.overwrite(node.start, node.end, `'object'`, {
storeName: false
});
}

@@ -1515,19 +1610,18 @@ }

let isRestorableCompiledEsm = false;
if (defineCompiledEsmExpressions.length > 0) {
if (!shouldWrap && defineCompiledEsmExpressions.length === 1) {
isRestorableCompiledEsm = true;
magicString.remove(
defineCompiledEsmExpressions[0].start,
defineCompiledEsmExpressions[0].end
);
} else {
shouldWrap = true;
uses.exports = true;
}
const nameBase = getName(id);
const exportsName = deconflictScopes([...exportsAccessScopes], globals, nameBase);
const moduleName = deconflictScopes([...moduleAccessScopes], globals, `${nameBase}Module`);
const deconflictedExportNames = Object.create(null);
for (const [exportName, { scopes }] of exportsAssignmentsByName) {
deconflictedExportNames[exportName] = deconflictScopes([...scopes], globals, exportName);
}
// We cannot wrap ES/mixed modules
shouldWrap = shouldWrap && !disableWrap && !isEsModule;
uses.commonjsHelpers = uses.commonjsHelpers || shouldWrap;
shouldWrap =
!isEsModule &&
!disableWrap &&
(shouldWrap || (uses.exports && moduleExportsAssignments.length > 0));
const detectWrappedDefault =
shouldWrap &&
(topLevelDefineCompiledEsmExpressions.length > 0 || code.indexOf('__esModule') >= 0);

@@ -1541,3 +1635,3 @@ if (

uses.require ||
uses.commonjsHelpers ||
usesDynamicRequire ||
hasRemovedRequire

@@ -1550,4 +1644,2 @@ ) &&

const moduleName = deconflict(scope, globals, getName(id));
let leadingComment = '';

@@ -1560,2 +1652,27 @@ if (code.startsWith('/*')) {

const exportMode = shouldWrap
? uses.module
? 'module'
: 'exports'
: firstTopLevelModuleExportsAssignment
? exportsAssignmentsByName.size === 0 && topLevelDefineCompiledEsmExpressions.length === 0
? 'replace'
: 'module'
: moduleExportsAssignments.length === 0
? 'exports'
: 'module';
const importBlock = rewriteRequireExpressionsAndGetImportBlock(
magicString,
topLevelDeclarations,
topLevelRequireDeclarators,
reassignedNames,
HELPERS_NAME,
dynamicRegisterSources,
moduleName,
exportsName,
id,
exportMode
);
const exportBlock = isEsModule

@@ -1566,24 +1683,18 @@ ? ''

moduleName,
exportsName,
shouldWrap,
topLevelModuleExportsAssignments,
topLevelExportsAssignmentsByName,
defineCompiledEsmExpressions,
(name) => deconflict(scope, globals, name),
isRestorableCompiledEsm,
moduleExportsAssignments,
firstTopLevelModuleExportsAssignment,
exportsAssignmentsByName,
topLevelAssignments,
topLevelDefineCompiledEsmExpressions,
deconflictedExportNames,
code,
uses,
HELPERS_NAME
HELPERS_NAME,
exportMode,
detectWrappedDefault
);
const importBlock = rewriteRequireExpressionsAndGetImportBlock(
magicString,
topLevelDeclarations,
topLevelRequireDeclarators,
reassignedNames,
uses.commonjsHelpers && HELPERS_NAME,
dynamicRegisterSources
);
if (shouldWrap) {
wrapCode(magicString, uses, moduleName, HELPERS_NAME, virtualDynamicRequirePath);
wrapCode(magicString, uses, moduleName, exportsName);
}

@@ -1662,2 +1773,3 @@

if (isDynamicRequireModulesEnabled && this.getModuleInfo(id).isEntry) {
// eslint-disable-next-line no-param-reassign
code =

@@ -1686,8 +1798,7 @@ getDynamicPackagesEntryIntro(dynamicRequireModuleDirPaths, dynamicRequireModuleSet) + code;

let disableWrap = false;
// avoid wrapping in createCommonjsModule, as this is a commonjsRegister call
if (isModuleRegisterProxy(id)) {
disableWrap = true;
id = unwrapModuleRegisterProxy(id);
// avoid wrapping as this is a commonjsRegister call
const disableWrap = isWrappedId(id, DYNAMIC_REGISTER_SUFFIX);
if (disableWrap) {
// eslint-disable-next-line no-param-reassign
id = unwrapId(id, DYNAMIC_REGISTER_SUFFIX);
}

@@ -1735,2 +1846,35 @@

if (isWrappedId(id, MODULE_SUFFIX)) {
const actualId = unwrapId(id, MODULE_SUFFIX);
let name = getName(actualId);
let code;
if (isDynamicRequireModulesEnabled) {
if (['modulePath', 'commonjsRequire', 'createModule'].includes(name)) {
name = `${name}_`;
}
code =
`import {commonjsRequire, createModule} from "${HELPERS_ID}";\n` +
`var ${name} = createModule(${JSON.stringify(
getVirtualPathForDynamicRequirePath(dirname(actualId), commonDir)
)});\n` +
`export {${name} as __module}`;
} else {
code = `var ${name} = {exports: {}}; export {${name} as __module}`;
}
return {
code,
syntheticNamedExports: '__module',
meta: { commonjs: { isCommonJS: false } }
};
}
if (isWrappedId(id, EXPORTS_SUFFIX)) {
const actualId = unwrapId(id, EXPORTS_SUFFIX);
const name = getName(actualId);
return {
code: `var ${name} = {}; export {${name} as __exports}`,
meta: { commonjs: { isCommonJS: false } }
};
}
if (isWrappedId(id, EXTERNAL_SUFFIX)) {

@@ -1756,5 +1900,5 @@ const actualId = unwrapId(id, EXTERNAL_SUFFIX);

if (isModuleRegisterProxy(id)) {
if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) {
return getDynamicRequireProxy(
normalizePathSlashes(unwrapModuleRegisterProxy(id)),
normalizePathSlashes(unwrapId(id, DYNAMIC_REGISTER_SUFFIX)),
commonDir

@@ -1780,4 +1924,4 @@ );

if (isModuleRegisterProxy(id)) {
id = unwrapModuleRegisterProxy(id);
if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) {
id = unwrapId(id, DYNAMIC_REGISTER_SUFFIX);
}

@@ -1802,11 +1946,8 @@

moduleParsed({ id, meta: { commonjs } }) {
if (commonjs) {
const isCjs = commonjs.isCommonJS;
if (isCjs != null) {
setIsCjsPromise(id, isCjs);
return;
}
moduleParsed({ id, meta: { commonjs: commonjsMeta } }) {
if (commonjsMeta && commonjsMeta.isCommonJS != null) {
setCommonJSMetaPromise(id, commonjsMeta);
return;
}
setIsCjsPromise(id, null);
setCommonJSMetaPromise(id, null);
}

@@ -1813,0 +1954,0 @@ };

@@ -21,3 +21,3 @@ 'use strict';

var peerDependencies = {
rollup: "^2.30.0"
rollup: "^2.38.0"
};

@@ -96,2 +96,4 @@

const EXTERNAL_SUFFIX = '?commonjs-external';
const EXPORTS_SUFFIX = '?commonjs-exports';
const MODULE_SUFFIX = '?commonjs-module';

@@ -141,7 +143,2 @@ const DYNAMIC_REGISTER_SUFFIX = '?commonjs-dynamic-register';

const HELPER_NON_DYNAMIC = `
export function createCommonjsModule(fn) {
var module = { exports: {} }
return fn(module, module.exports), module.exports;
}
export function commonjsRequire (target) {

@@ -153,10 +150,10 @@ throw new Error('Could not dynamically require "' + target + '". Please configure the dynamicRequireTargets option of @rollup/plugin-commonjs appropriately for this require call to behave properly.');

const HELPERS_DYNAMIC = `
export function createCommonjsModule(fn, basedir, module) {
return module = {
path: basedir,
export function createModule(modulePath) {
return {
path: modulePath,
exports: {},
require: function (path, base) {
return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
return commonjsRequire(path, base == null ? modulePath : base);
}
}, fn(module, module.exports), module.exports;
};
}

@@ -352,2 +349,20 @@

function deconflictScopes(scopes, globals, identifier) {
let i = 1;
let deconflicted = pluginutils.makeLegalIdentifier(identifier);
const hasConflicts = () =>
scopes.some((scope) => scope.contains(deconflicted)) || globals.has(deconflicted);
while (hasConflicts()) {
deconflicted = pluginutils.makeLegalIdentifier(`${identifier}_${i}`);
i += 1;
}
for (const scope of scopes) {
scope.declarations[deconflicted] = true;
}
return deconflicted;
}
function getName(id) {

@@ -410,7 +425,9 @@ const name = pluginutils.makeLegalIdentifier(path.basename(id, path.extname(id)));

dynamicRequireModuleSet,
(dynamicId) => `require(${JSON.stringify(wrapModuleRegisterProxy(dynamicId))});`
(dynamicId) => `require(${JSON.stringify(wrapId(dynamicId, DYNAMIC_REGISTER_SUFFIX))});`
).join('\n');
if (dynamicRequireModuleDirPaths.length) {
dynamicImports += `require(${JSON.stringify(wrapModuleRegisterProxy(DYNAMIC_PACKAGES_ID))});`;
dynamicImports += `require(${JSON.stringify(
wrapId(DYNAMIC_PACKAGES_ID, DYNAMIC_REGISTER_SUFFIX)
)});`;
}

@@ -421,14 +438,2 @@

function wrapModuleRegisterProxy(id) {
return wrapId(id, DYNAMIC_REGISTER_SUFFIX);
}
function unwrapModuleRegisterProxy(id) {
return unwrapId(id, DYNAMIC_REGISTER_SUFFIX);
}
function isModuleRegisterProxy(id) {
return isWrappedId(id, DYNAMIC_REGISTER_SUFFIX);
}
function isDynamicModuleImport(id, dynamicRequireModuleSet) {

@@ -466,16 +471,16 @@ const normalizedPath = normalizePathSlashes(id);

const isCjsPromises = new Map();
const commonJSMetaPromises = new Map();
function getIsCjsPromise(id) {
let isCjsPromise = isCjsPromises.get(id);
if (isCjsPromise) return isCjsPromise.promise;
function getCommonJSMetaPromise(id) {
let commonJSMetaPromise = commonJSMetaPromises.get(id);
if (commonJSMetaPromise) return commonJSMetaPromise.promise;
const promise = new Promise((resolve) => {
isCjsPromise = {
commonJSMetaPromise = {
resolve,
promise: null
};
isCjsPromises.set(id, isCjsPromise);
commonJSMetaPromises.set(id, commonJSMetaPromise);
});
isCjsPromise.promise = promise;
commonJSMetaPromise.promise = promise;

@@ -485,11 +490,11 @@ return promise;

function setIsCjsPromise(id, resolution) {
const isCjsPromise = isCjsPromises.get(id);
if (isCjsPromise) {
if (isCjsPromise.resolve) {
isCjsPromise.resolve(resolution);
isCjsPromise.resolve = null;
function setCommonJSMetaPromise(id, commonjsMeta) {
const commonJSMetaPromise = commonJSMetaPromises.get(id);
if (commonJSMetaPromise) {
if (commonJSMetaPromise.resolve) {
commonJSMetaPromise.resolve(commonjsMeta);
commonJSMetaPromise.resolve = null;
}
} else {
isCjsPromises.set(id, { promise: Promise.resolve(resolution), resolve: null });
commonJSMetaPromises.set(id, { promise: Promise.resolve(commonjsMeta), resolve: null });
}

@@ -500,3 +505,3 @@ }

function getSpecificHelperProxy(id) {
return `export {${id.split('?')[1]} as default} from '${HELPERS_ID}';`;
return `export {${id.split('?')[1]} as default} from "${HELPERS_ID}";`;
}

@@ -544,9 +549,9 @@

const name = getName(id);
const isCjs = await getIsCjsPromise(id);
if (isCjs) {
return `import { __moduleExports } from ${JSON.stringify(id)}; export default __moduleExports;`;
} else if (isCjs === null) {
const commonjsMeta = await getCommonJSMetaPromise(id);
if (commonjsMeta && commonjsMeta.isCommonJS) {
return `export { __moduleExports as default } from ${JSON.stringify(id)};`;
} else if (commonjsMeta === null) {
return getUnknownRequireProxy(id, requireReturnsDefault);
} else if (!requireReturnsDefault) {
return `import {getAugmentedNamespace} from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(
return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(
id

@@ -562,3 +567,3 @@ )}; export default /*@__PURE__*/getAugmentedNamespace(${name});`;

}
return `export {default} from ${JSON.stringify(id)};`;
return `export { default } from ${JSON.stringify(id)};`;
}

@@ -600,8 +605,13 @@

return function resolveId(importee, rawImporter) {
if (isWrappedId(importee, MODULE_SUFFIX) || isWrappedId(importee, EXPORTS_SUFFIX)) {
return importee;
}
const importer =
rawImporter && isModuleRegisterProxy(rawImporter)
? unwrapModuleRegisterProxy(rawImporter)
rawImporter && isWrappedId(rawImporter, DYNAMIC_REGISTER_SUFFIX)
? unwrapId(rawImporter, DYNAMIC_REGISTER_SUFFIX)
: rawImporter;
// Proxies are only importing resolved ids, no need to resolve again
// Except for exports, proxies are only importing resolved ids,
// no need to resolve again
if (importer && isWrappedId(importer, PROXY_SUFFIX)) {

@@ -620,5 +630,5 @@ return importee;

isModuleRegistration = isModuleRegisterProxy(importee);
isModuleRegistration = isWrappedId(importee, DYNAMIC_REGISTER_SUFFIX);
if (isModuleRegistration) {
importee = unwrapModuleRegisterProxy(importee);
importee = unwrapId(importee, DYNAMIC_REGISTER_SUFFIX);
}

@@ -650,3 +660,3 @@ }

} else if (resolved && isModuleRegistration) {
resolved.id = wrapModuleRegisterProxy(resolved.id);
resolved.id = wrapId(resolved.id, DYNAMIC_REGISTER_SUFFIX);
} else if (!resolved && (isProxyModule || isRequiredModule)) {

@@ -751,4 +761,2 @@ return { id: wrapId(importee, EXTERNAL_SUFFIX), external: false };

function getDefinePropertyCallName(node, targetName) {
const targetNames = targetName.split('.');
const {

@@ -761,2 +769,3 @@ callee: { object, property }

const targetNames = targetName.split('.');
const [target, key, value] = node.arguments;

@@ -803,11 +812,17 @@ if (targetNames.length === 1) {

function wrapCode(magicString, uses, moduleName, HELPERS_NAME, virtualDynamicRequirePath) {
const args = `module${uses.exports ? ', exports' : ''}`;
function wrapCode(magicString, uses, moduleName, exportsName) {
const args = [];
const passedArgs = [];
if (uses.module) {
args.push('module');
passedArgs.push(moduleName);
}
if (uses.exports) {
args.push('exports');
passedArgs.push(exportsName);
}
magicString
.trim()
.prepend(`var ${moduleName} = ${HELPERS_NAME}.createCommonjsModule(function (${args}) {\n`)
.append(
`\n}${virtualDynamicRequirePath ? `, ${JSON.stringify(virtualDynamicRequirePath)}` : ''});`
);
.prepend(`(function (${args.join(', ')}) {\n`)
.append(`\n}(${passedArgs.join(', ')}));`);
}

@@ -818,84 +833,151 @@

moduleName,
exportsName,
wrapped,
topLevelModuleExportsAssignments,
topLevelExportsAssignmentsByName,
moduleExportsAssignments,
firstTopLevelModuleExportsAssignment,
exportsAssignmentsByName,
topLevelAssignments,
defineCompiledEsmExpressions,
deconflict,
isRestorableCompiledEsm,
deconflictedExportNames,
code,
uses,
HELPERS_NAME
HELPERS_NAME,
exportMode,
detectWrappedDefault
) {
const namedExportDeclarations = [`export { ${moduleName} as __moduleExports };`];
const moduleExportsPropertyAssignments = [];
let deconflictedDefaultExportName;
const exports = [];
const exportDeclarations = [];
if (!wrapped) {
let hasModuleExportsAssignment = false;
const namedExportProperties = [];
// Collect and rewrite module.exports assignments
for (const { left } of topLevelModuleExportsAssignments) {
hasModuleExportsAssignment = true;
magicString.overwrite(left.start, left.end, `var ${moduleName}`);
if (exportMode === 'replace') {
getExportsForReplacedModuleExports(
magicString,
exports,
moduleExportsAssignments,
firstTopLevelModuleExportsAssignment,
exportsName
);
} else {
exports.push(`${exportsName} as __moduleExports`);
if (wrapped) {
getExportsWhenWrapping(
exports,
exportDeclarations,
exportsName,
detectWrappedDefault,
HELPERS_NAME
);
} else {
getExports(
magicString,
exports,
exportDeclarations,
moduleExportsAssignments,
exportsAssignmentsByName,
deconflictedExportNames,
topLevelAssignments,
moduleName,
exportsName,
defineCompiledEsmExpressions,
HELPERS_NAME
);
}
}
if (exports.length) {
exportDeclarations.push(`export { ${exports.join(', ')} };`);
}
// Collect and rewrite named exports
for (const [exportName, node] of topLevelExportsAssignmentsByName) {
const deconflicted = deconflict(exportName);
magicString.overwrite(node.start, node.left.end, `var ${deconflicted}`);
return `\n\n${exportDeclarations.join('\n')}`;
}
if (exportName === 'default') {
deconflictedDefaultExportName = deconflicted;
} else {
namedExportDeclarations.push(
exportName === deconflicted
? `export { ${exportName} };`
: `export { ${deconflicted} as ${exportName} };`
);
}
function getExportsForReplacedModuleExports(
magicString,
exports,
moduleExportsAssignments,
firstTopLevelModuleExportsAssignment,
exportsName
) {
for (const { left } of moduleExportsAssignments) {
magicString.overwrite(left.start, left.end, exportsName);
}
magicString.prependRight(firstTopLevelModuleExportsAssignment.left.start, 'var ');
exports.push(`${exportsName} as __moduleExports`, `${exportsName} as default`);
}
if (hasModuleExportsAssignment) {
moduleExportsPropertyAssignments.push(`${moduleName}.${exportName} = ${deconflicted};`);
} else {
namedExportProperties.push(`\t${exportName}: ${deconflicted}`);
function getExportsWhenWrapping(
exports,
exportDeclarations,
exportsName,
detectWrappedDefault,
HELPERS_NAME
) {
if (detectWrappedDefault) {
exportDeclarations.push(
`export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportsName});`
);
} else {
exports.push(`${exportsName} as default`);
}
}
function getExports(
magicString,
exports,
exportDeclarations,
moduleExportsAssignments,
exportsAssignmentsByName,
deconflictedExportNames,
topLevelAssignments,
moduleName,
exportsName,
defineCompiledEsmExpressions,
HELPERS_NAME
) {
let deconflictedDefaultExportName;
// Collect and rewrite module.exports assignments
for (const { left } of moduleExportsAssignments) {
magicString.overwrite(left.start, left.end, `${moduleName}.exports`);
}
// Collect and rewrite named exports
for (const [exportName, { nodes }] of exportsAssignmentsByName) {
const deconflicted = deconflictedExportNames[exportName];
let needsDeclaration = true;
for (const node of nodes) {
let replacement = `${deconflicted} = ${exportsName}.${exportName}`;
if (needsDeclaration && topLevelAssignments.has(node)) {
replacement = `var ${replacement}`;
needsDeclaration = false;
}
magicString.overwrite(node.start, node.left.end, replacement);
}
if (needsDeclaration) {
magicString.prepend(`var ${deconflicted};\n`);
}
// Regenerate CommonJS namespace
if (!hasModuleExportsAssignment) {
const moduleExports = `{\n${namedExportProperties.join(',\n')}\n}`;
magicString
.trim()
.append(
`\n\nvar ${moduleName} = ${
isRestorableCompiledEsm
? `/*#__PURE__*/Object.defineProperty(${moduleExports}, '__esModule', {value: true})`
: moduleExports
};`
);
if (exportName === 'default') {
deconflictedDefaultExportName = deconflicted;
} else {
exports.push(exportName === deconflicted ? exportName : `${deconflicted} as ${exportName}`);
}
}
// Generate default export
const defaultExport = [];
// Collect and rewrite exports.__esModule assignments
let isRestorableCompiledEsm = false;
for (const expression of defineCompiledEsmExpressions) {
isRestorableCompiledEsm = true;
const moduleExportsExpression =
expression.type === 'CallExpression' ? expression.arguments[0] : expression.left.object;
magicString.overwrite(moduleExportsExpression.start, moduleExportsExpression.end, exportsName);
}
if (isRestorableCompiledEsm) {
defaultExport.push(`export default ${deconflictedDefaultExportName || moduleName};`);
} else if (
(wrapped || deconflictedDefaultExportName) &&
(defineCompiledEsmExpressions.length > 0 || code.indexOf('__esModule') >= 0)
) {
// eslint-disable-next-line no-param-reassign
uses.commonjsHelpers = true;
defaultExport.push(
`export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${moduleName});`
);
if (moduleExportsAssignments.length === 0) {
exports.push(`${deconflictedDefaultExportName || exportsName} as default`);
} else {
exportDeclarations.push(
`export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportsName});`
);
}
} else {
defaultExport.push(`export default ${moduleName};`);
exports.push(`${exportsName} as default`);
}
return `\n\n${defaultExport
.concat(namedExportDeclarations)
.concat(moduleExportsPropertyAssignments)
.join('\n')}`;
}

@@ -1018,4 +1100,8 @@

reassignedNames,
helpersNameIfUsed,
dynamicRegisterSources
helpersName,
dynamicRegisterSources,
moduleName,
exportsName,
id,
exportMode
) {

@@ -1033,26 +1119,30 @@ const removedDeclarators = getDeclaratorsReplacedByImportsAndSetImportNames(

removeDeclaratorsFromDeclarations(topLevelDeclarations, removedDeclarators, magicString);
const importBlock = `${(helpersNameIfUsed
? [`import * as ${helpersNameIfUsed} from '${HELPERS_ID}';`]
: []
)
.concat(
// dynamic registers first, as the may be required in the other modules
[...dynamicRegisterSources].map((source) => `import '${wrapId(source, REQUIRE_SUFFIX)}';`),
// now the actual modules so that they are analyzed before creating the proxies;
// no need to do this for virtual modules as we never proxy them
requiredSources
.filter((source) => !source.startsWith('\0'))
.map((source) => `import '${wrapId(source, REQUIRE_SUFFIX)}';`),
// now the proxy modules
requiredSources.map((source) => {
const { name, nodesUsingRequired } = requiredBySource[source];
return `import ${nodesUsingRequired.length ? `${name} from ` : ``}'${
source.startsWith('\0') ? source : wrapId(source, PROXY_SUFFIX)
}';`;
})
)
.join('\n')}`;
return importBlock ? `${importBlock}\n\n` : '';
const imports = [];
imports.push(`import * as ${helpersName} from "${HELPERS_ID}";`);
if (exportMode === 'module') {
imports.push(
`import { __module as ${moduleName}, exports as ${exportsName} } from ${JSON.stringify(
wrapId(id, MODULE_SUFFIX)
)}`
);
} else if (exportMode === 'exports') {
imports.push(
`import { __exports as ${exportsName} } from ${JSON.stringify(wrapId(id, EXPORTS_SUFFIX))}`
);
}
for (const source of dynamicRegisterSources) {
imports.push(`import ${JSON.stringify(wrapId(source, REQUIRE_SUFFIX))};`);
}
for (const source of requiredSources) {
if (!source.startsWith('\0')) {
imports.push(`import ${JSON.stringify(wrapId(source, REQUIRE_SUFFIX))};`);
}
const { name, nodesUsingRequired } = requiredBySource[source];
imports.push(
`import ${nodesUsingRequired.length ? `${name} from ` : ''}${JSON.stringify(
source.startsWith('\0') ? source : wrapId(source, PROXY_SUFFIX)
)};`
);
}
return imports.length ? `${imports.join('\n')}\n\n` : '';
}

@@ -1158,5 +1248,5 @@

global: false,
require: false,
commonjsHelpers: false
require: false
};
let usesDynamicRequire = false;
const virtualDynamicRequirePath =

@@ -1169,3 +1259,2 @@ isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(path.dirname(id), commonDir);

let shouldWrap = false;
const defineCompiledEsmExpressions = [];

@@ -1176,3 +1265,2 @@ const globals = new Set();

const HELPERS_NAME = deconflict(scope, globals, 'commonjsHelpers');
const namedExports = {};
const dynamicRegisterSources = new Set();

@@ -1194,4 +1282,9 @@ let hasRemovedRequire = false;

const skippedNodes = new Set();
const topLevelModuleExportsAssignments = [];
const topLevelExportsAssignmentsByName = new Map();
const moduleAccessScopes = new Set([scope]);
const exportsAccessScopes = new Set([scope]);
const moduleExportsAssignments = [];
let firstTopLevelModuleExportsAssignment = null;
const exportsAssignmentsByName = new Map();
const topLevelAssignments = new Set();
const topLevelDefineCompiledEsmExpressions = [];

@@ -1236,26 +1329,30 @@ estreeWalker.walk(ast, {

// we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` –
if (programDepth > 3) {
shouldWrap = true;
if (flattened.keypath === 'module.exports') {
moduleExportsAssignments.push(node);
if (programDepth > 3) {
moduleAccessScopes.add(scope);
} else if (!firstTopLevelModuleExportsAssignment) {
firstTopLevelModuleExportsAssignment = node;
}
} else if (exportName === KEY_COMPILED_ESM) {
defineCompiledEsmExpressions.push(parent);
} else if (flattened.keypath === 'module.exports') {
topLevelModuleExportsAssignments.push(node);
} else if (!topLevelExportsAssignmentsByName.has(exportName)) {
topLevelExportsAssignmentsByName.set(exportName, node);
if (programDepth > 3) {
shouldWrap = true;
} else {
topLevelDefineCompiledEsmExpressions.push(node);
}
} else {
shouldWrap = true;
const exportsAssignments = exportsAssignmentsByName.get(exportName) || {
nodes: [],
scopes: new Set()
};
exportsAssignments.nodes.push(node);
exportsAssignments.scopes.add(scope);
exportsAccessScopes.add(scope);
exportsAssignmentsByName.set(exportName, exportsAssignments);
if (programDepth <= 3) {
topLevelAssignments.add(node);
}
}
skippedNodes.add(node.left);
if (flattened.keypath === 'module.exports' && node.right.type === 'ObjectExpression') {
node.right.properties.forEach((prop) => {
if (prop.computed || !('key' in prop) || prop.key.type !== 'Identifier') return;
const { name } = prop.key;
if (name === pluginutils.makeLegalIdentifier(name)) namedExports[name] = true;
});
return;
}
if (exportsPatternMatch[1]) namedExports[exportsPatternMatch[1]] = true;
} else {

@@ -1272,3 +1369,3 @@ for (const name of pluginutils.extractAssignedNames(node.left)) {

skippedNodes.add(node.arguments[0]);
defineCompiledEsmExpressions.push(parent);
topLevelDefineCompiledEsmExpressions.push(node);
} else {

@@ -1301,3 +1398,2 @@ shouldWrap = true;

);
uses.commonjsHelpers = true;
return;

@@ -1329,9 +1425,9 @@ }

let sourceId = getRequireStringArg(node);
const isDynamicRegister = isModuleRegisterProxy(sourceId);
const isDynamicRegister = isWrappedId(sourceId, DYNAMIC_REGISTER_SUFFIX);
if (isDynamicRegister) {
sourceId = unwrapModuleRegisterProxy(sourceId);
sourceId = unwrapId(sourceId, DYNAMIC_REGISTER_SUFFIX);
if (sourceId.endsWith('.json')) {
sourceId = DYNAMIC_JSON_PREFIX + sourceId;
}
dynamicRegisterSources.add(wrapModuleRegisterProxy(sourceId));
dynamicRegisterSources.add(wrapId(sourceId, DYNAMIC_REGISTER_SUFFIX));
} else {

@@ -1354,3 +1450,3 @@ if (

);
uses.commonjsHelpers = true;
usesDynamicRequire = true;
}

@@ -1412,3 +1508,2 @@ return;

});
uses.commonjsHelpers = true;
}

@@ -1435,4 +1530,3 @@ }

}
uses.commonjsHelpers = true;
usesDynamicRequire = true;
return;

@@ -1450,7 +1544,8 @@ case 'module':

});
uses.commonjsHelpers = true;
}
return;
case 'define':
magicString.overwrite(node.start, node.end, 'undefined', { storeName: true });
magicString.overwrite(node.start, node.end, 'undefined', {
storeName: true
});
return;

@@ -1467,3 +1562,2 @@ default:

});
uses.commonjsHelpers = true;
skippedNodes.add(node.object);

@@ -1487,3 +1581,2 @@ skippedNodes.add(node.property);

});
uses.commonjsHelpers = true;
}

@@ -1505,3 +1598,5 @@ }

) {
magicString.overwrite(node.start, node.end, `'object'`, { storeName: false });
magicString.overwrite(node.start, node.end, `'object'`, {
storeName: false
});
}

@@ -1524,19 +1619,18 @@ }

let isRestorableCompiledEsm = false;
if (defineCompiledEsmExpressions.length > 0) {
if (!shouldWrap && defineCompiledEsmExpressions.length === 1) {
isRestorableCompiledEsm = true;
magicString.remove(
defineCompiledEsmExpressions[0].start,
defineCompiledEsmExpressions[0].end
);
} else {
shouldWrap = true;
uses.exports = true;
}
const nameBase = getName(id);
const exportsName = deconflictScopes([...exportsAccessScopes], globals, nameBase);
const moduleName = deconflictScopes([...moduleAccessScopes], globals, `${nameBase}Module`);
const deconflictedExportNames = Object.create(null);
for (const [exportName, { scopes }] of exportsAssignmentsByName) {
deconflictedExportNames[exportName] = deconflictScopes([...scopes], globals, exportName);
}
// We cannot wrap ES/mixed modules
shouldWrap = shouldWrap && !disableWrap && !isEsModule;
uses.commonjsHelpers = uses.commonjsHelpers || shouldWrap;
shouldWrap =
!isEsModule &&
!disableWrap &&
(shouldWrap || (uses.exports && moduleExportsAssignments.length > 0));
const detectWrappedDefault =
shouldWrap &&
(topLevelDefineCompiledEsmExpressions.length > 0 || code.indexOf('__esModule') >= 0);

@@ -1550,3 +1644,3 @@ if (

uses.require ||
uses.commonjsHelpers ||
usesDynamicRequire ||
hasRemovedRequire

@@ -1559,4 +1653,2 @@ ) &&

const moduleName = deconflict(scope, globals, getName(id));
let leadingComment = '';

@@ -1569,2 +1661,27 @@ if (code.startsWith('/*')) {

const exportMode = shouldWrap
? uses.module
? 'module'
: 'exports'
: firstTopLevelModuleExportsAssignment
? exportsAssignmentsByName.size === 0 && topLevelDefineCompiledEsmExpressions.length === 0
? 'replace'
: 'module'
: moduleExportsAssignments.length === 0
? 'exports'
: 'module';
const importBlock = rewriteRequireExpressionsAndGetImportBlock(
magicString,
topLevelDeclarations,
topLevelRequireDeclarators,
reassignedNames,
HELPERS_NAME,
dynamicRegisterSources,
moduleName,
exportsName,
id,
exportMode
);
const exportBlock = isEsModule

@@ -1575,24 +1692,18 @@ ? ''

moduleName,
exportsName,
shouldWrap,
topLevelModuleExportsAssignments,
topLevelExportsAssignmentsByName,
defineCompiledEsmExpressions,
(name) => deconflict(scope, globals, name),
isRestorableCompiledEsm,
moduleExportsAssignments,
firstTopLevelModuleExportsAssignment,
exportsAssignmentsByName,
topLevelAssignments,
topLevelDefineCompiledEsmExpressions,
deconflictedExportNames,
code,
uses,
HELPERS_NAME
HELPERS_NAME,
exportMode,
detectWrappedDefault
);
const importBlock = rewriteRequireExpressionsAndGetImportBlock(
magicString,
topLevelDeclarations,
topLevelRequireDeclarators,
reassignedNames,
uses.commonjsHelpers && HELPERS_NAME,
dynamicRegisterSources
);
if (shouldWrap) {
wrapCode(magicString, uses, moduleName, HELPERS_NAME, virtualDynamicRequirePath);
wrapCode(magicString, uses, moduleName, exportsName);
}

@@ -1671,2 +1782,3 @@

if (isDynamicRequireModulesEnabled && this.getModuleInfo(id).isEntry) {
// eslint-disable-next-line no-param-reassign
code =

@@ -1695,8 +1807,7 @@ getDynamicPackagesEntryIntro(dynamicRequireModuleDirPaths, dynamicRequireModuleSet) + code;

let disableWrap = false;
// avoid wrapping in createCommonjsModule, as this is a commonjsRegister call
if (isModuleRegisterProxy(id)) {
disableWrap = true;
id = unwrapModuleRegisterProxy(id);
// avoid wrapping as this is a commonjsRegister call
const disableWrap = isWrappedId(id, DYNAMIC_REGISTER_SUFFIX);
if (disableWrap) {
// eslint-disable-next-line no-param-reassign
id = unwrapId(id, DYNAMIC_REGISTER_SUFFIX);
}

@@ -1744,2 +1855,35 @@

if (isWrappedId(id, MODULE_SUFFIX)) {
const actualId = unwrapId(id, MODULE_SUFFIX);
let name = getName(actualId);
let code;
if (isDynamicRequireModulesEnabled) {
if (['modulePath', 'commonjsRequire', 'createModule'].includes(name)) {
name = `${name}_`;
}
code =
`import {commonjsRequire, createModule} from "${HELPERS_ID}";\n` +
`var ${name} = createModule(${JSON.stringify(
getVirtualPathForDynamicRequirePath(path.dirname(actualId), commonDir)
)});\n` +
`export {${name} as __module}`;
} else {
code = `var ${name} = {exports: {}}; export {${name} as __module}`;
}
return {
code,
syntheticNamedExports: '__module',
meta: { commonjs: { isCommonJS: false } }
};
}
if (isWrappedId(id, EXPORTS_SUFFIX)) {
const actualId = unwrapId(id, EXPORTS_SUFFIX);
const name = getName(actualId);
return {
code: `var ${name} = {}; export {${name} as __exports}`,
meta: { commonjs: { isCommonJS: false } }
};
}
if (isWrappedId(id, EXTERNAL_SUFFIX)) {

@@ -1765,5 +1909,5 @@ const actualId = unwrapId(id, EXTERNAL_SUFFIX);

if (isModuleRegisterProxy(id)) {
if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) {
return getDynamicRequireProxy(
normalizePathSlashes(unwrapModuleRegisterProxy(id)),
normalizePathSlashes(unwrapId(id, DYNAMIC_REGISTER_SUFFIX)),
commonDir

@@ -1789,4 +1933,4 @@ );

if (isModuleRegisterProxy(id)) {
id = unwrapModuleRegisterProxy(id);
if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) {
id = unwrapId(id, DYNAMIC_REGISTER_SUFFIX);
}

@@ -1811,11 +1955,8 @@

moduleParsed({ id, meta: { commonjs } }) {
if (commonjs) {
const isCjs = commonjs.isCommonJS;
if (isCjs != null) {
setIsCjsPromise(id, isCjs);
return;
}
moduleParsed({ id, meta: { commonjs: commonjsMeta } }) {
if (commonjsMeta && commonjsMeta.isCommonJS != null) {
setCommonJSMetaPromise(id, commonjsMeta);
return;
}
setIsCjsPromise(id, null);
setCommonJSMetaPromise(id, null);
}

@@ -1822,0 +1963,0 @@ };

{
"name": "@rollup/plugin-commonjs",
"version": "17.1.0",
"version": "18.0.0-0",
"publishConfig": {

@@ -50,3 +50,3 @@ "access": "public"

"peerDependencies": {
"rollup": "^2.30.0"
"rollup": "^2.38.0"
},

@@ -67,3 +67,3 @@ "dependencies": {

"require-relative": "^0.8.7",
"rollup": "^2.30.0",
"rollup": "^2.38.0",
"shx": "^0.3.2",

@@ -70,0 +70,0 @@ "source-map": "^0.7.3",

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