diff --git a/packages/commonjs/README.md b/packages/commonjs/README.md index 073cb735e..225ed182c 100644 --- a/packages/commonjs/README.md +++ b/packages/commonjs/README.md @@ -13,7 +13,7 @@ ## Requirements -This plugin requires an [LTS](https://github.com/nodejs/Release) Node version (v8.0.0+) and Rollup v2.38.3+. +This plugin requires an [LTS](https://github.com/nodejs/Release) Node version (v12.0.0+) and Rollup v2.68.0+. If you are using [`@rollup/plugin-node-resolve`](https://github.com/rollup/plugins/tree/master/packages/node-resolve), it should be v13.0.6+. ## Install @@ -42,15 +42,36 @@ export default { Then call `rollup` either via the [CLI](https://www.rollupjs.org/guide/en/#command-line-reference) or the [API](https://www.rollupjs.org/guide/en/#javascript-api). +When used together with the node-resolve plugin + ## Options +### `strictRequires` + +Type: `"auto" | boolean | "debug" | string[]`
+Default: `"auto"` + +By default, this plugin will try to hoist `require` statements as imports to the top of each file. While this works well for many code bases and allows for very efficient ESM output, it does not perfectly capture CommonJS semantics as the initialisation order of required modules will be different. The resultant side effects can include log statements being emitted in a different order, and some code that is dependent on the initialisation order of polyfills in require statements may not work. But it is especially problematic when there are circular `require` calls between CommonJS modules as those often rely on the lazy execution of nested `require` calls. + +Setting this option to `true` will wrap all CommonJS files in functions which are executed when they are required for the first time, preserving NodeJS semantics. This is the safest setting and should be used if the generated code does not work correctly with `"auto"`. Note that `strictRequires: true` can have a small impact on the size and performance of generated code, but less so if the code is minified. + +The default value of `"auto"` will only wrap CommonJS files when they are part of a CommonJS dependency cycle, e.g. an index file that is required by some of its dependencies, or if they are only required in a potentially "conditional" way like from within an if-statement or a function. All other CommonJS files are hoisted. This is the recommended setting for most code bases. Note that the detection of conditional requires can be subject to race conditions if there are both conditional and unconditional requires of the same file, which in edge cases may result in inconsistencies between builds. If you think this is a problem for you, you can avoid this by using any value other than `"auto"` or `"debug"`. + +`false` will entirely prevent wrapping and hoist all files. This may still work depending on the nature of cyclic dependencies but will often cause problems. + +You can also provide a [minimatch pattern](https://github.com/isaacs/minimatch), or array of patterns, to only specify a subset of files which should be wrapped in functions for proper `require` semantics. + +`"debug"` works like `"auto"` but after bundling, it will display a warning containing a list of ids that have been wrapped which can be used as minimatch pattern for fine-tuning or to avoid the potential race conditions mentioned for `"auto"`. + ### `dynamicRequireTargets` Type: `string | string[]`
Default: `[]` +_Note: In previous versions, this option would spin up a rather comprehensive mock environment that was capable of handling modules that manipulate `require.cache`. This is no longer supported. If you rely on this e.g. when using request-promise-native, use version 21 of this plugin._ + Some modules contain dynamic `require` calls, or require modules that contain circular dependencies, which are not handled well by static imports. -Including those modules as `dynamicRequireTargets` will simulate a CommonJS (NodeJS-like) environment for them with support for dynamic and circular dependencies. +Including those modules as `dynamicRequireTargets` will simulate a CommonJS (NodeJS-like) environment for them with support for dynamic dependencies. It also enables `strictRequires` for those modules, see above. _Note: In extreme cases, this feature may result in some paths being rendered as absolute in the final bundle. The plugin tries to avoid exposing paths from the local machine, but if you are `dynamicRequirePaths` with paths that are far away from your project's folder, that may require replacing strings like `"/Users/John/Desktop/foo-project/"` -> `"/"`._ @@ -71,6 +92,13 @@ commonjs({ }); ``` +### `dynamicRequireRoot` + +Type: `string`
+Default: `process.cwd()` + +To avoid long paths when using the `dynamicRequireTargets` option, you can use this option to specify a directory that is a common parent for all files that use dynamic require statements. Using a directory higher up such as `/` may lead to unnecessarily long paths in the generated code and may expose directory names on your machine like your home directory name. By default it uses the current working directory. + ### `exclude` Type: `string | string[]`
@@ -125,15 +153,17 @@ Sometimes you have to leave require statements unconverted. Pass an array contai Type: `boolean | 'remove' | string[] | ((id: string) => boolean)`
Default: `true` -In most cases, where `require` calls are inside a `try-catch` clause, they should be left unconverted as it requires an optional dependency that may or may not be installed beside the rolled up package. +In most cases, where `require` calls to external dependencies are inside a `try-catch` clause, they should be left unconverted as it requires an optional dependency that may or may not be installed beside the rolled up package. Due to the conversion of `require` to a static `import` - the call is hoisted to the top of the file, outside of the `try-catch` clause. -- `true`: All `require` calls inside a `try` will be left unconverted. -- `false`: All `require` calls inside a `try` will be converted as if the `try-catch` clause is not there. -- `remove`: Remove all `require` calls from inside any `try` block. +- `true`: All external `require` calls inside a `try` will be left unconverted. +- `false`: All external `require` calls inside a `try` will be converted as if the `try-catch` clause is not there. +- `remove`: Remove all external `require` calls from inside any `try` block. - `string[]`: Pass an array containing the IDs to left unconverted. - `((id: string) => boolean|'remove')`: Pass a function that control individual IDs. +Note that non-external requires will not be ignored by this option. + ### `ignoreDynamicRequires` Type: `boolean` @@ -361,7 +391,7 @@ export default { format: 'iife', name: 'MyModule' }, - plugins: [resolve(), commonjs()] + plugins: [commonjs(), resolve()] }; ``` diff --git a/packages/commonjs/package.json b/packages/commonjs/package.json index a93b7ecf6..e4643da9b 100644 --- a/packages/commonjs/package.json +++ b/packages/commonjs/package.json @@ -13,10 +13,14 @@ "author": "Rich Harris ", "homepage": "https://github.com/rollup/plugins/tree/master/packages/commonjs/#readme", "bugs": "https://github.com/rollup/plugins/issues", - "main": "dist/index.js", - "module": "dist/index.es.js", + "main": "./dist/cjs/index.js", + "module": "./dist/es/index.js", + "exports": { + "require": "./dist/cjs/index.js", + "import": "./dist/es/index.js" + }, "engines": { - "node": ">= 8.0.0" + "node": ">= 12.0.0" }, "scripts": { "build": "rollup -c", @@ -26,6 +30,7 @@ "ci:test": "pnpm test -- --verbose && pnpm test:ts", "prebuild": "del-cli dist", "prepare": "if [ ! -d 'dist' ]; then pnpm build; fi", + "prepublishOnly": "pnpm build", "prerelease": "pnpm build", "pretest": "pnpm build", "release": "pnpm plugin:release --workspace-root -- --pkg $npm_package_name", @@ -47,7 +52,7 @@ "require" ], "peerDependencies": { - "rollup": "^2.38.3" + "rollup": "^2.68.0" }, "dependencies": { "@rollup/pluginutils": "^3.1.0", @@ -60,10 +65,10 @@ }, "devDependencies": { "@rollup/plugin-json": "^4.1.0", - "@rollup/plugin-node-resolve": "^8.4.0", + "@rollup/plugin-node-resolve": "^13.1.0", "locate-character": "^2.0.5", "require-relative": "^0.8.7", - "rollup": "^2.67.3", + "rollup": "^2.68.0", "shx": "^0.3.2", "source-map": "^0.7.3", "source-map-support": "^0.5.19", diff --git a/packages/commonjs/rollup.config.js b/packages/commonjs/rollup.config.js index 93f8a4c3e..825c4b1be 100644 --- a/packages/commonjs/rollup.config.js +++ b/packages/commonjs/rollup.config.js @@ -1,5 +1,7 @@ import json from '@rollup/plugin-json'; +import { emitModulePackageFile } from '../../shared/rollup.config'; + import pkg from './package.json'; export default { @@ -10,6 +12,7 @@ export default { { file: pkg.module, format: 'es', + plugins: [emitModulePackageFile()], sourcemap: true }, { diff --git a/packages/commonjs/src/dynamic-modules.js b/packages/commonjs/src/dynamic-modules.js new file mode 100644 index 000000000..c00c21511 --- /dev/null +++ b/packages/commonjs/src/dynamic-modules.js @@ -0,0 +1,189 @@ +import { existsSync, readFileSync, statSync } from 'fs'; +import { join, resolve, dirname } from 'path'; + +import getCommonDir from 'commondir'; + +import glob from 'glob'; + +import { getVirtualPathForDynamicRequirePath, normalizePathSlashes } from './utils'; + +function getPackageEntryPoint(dirPath) { + let entryPoint = 'index.js'; + + try { + if (existsSync(join(dirPath, 'package.json'))) { + entryPoint = + JSON.parse(readFileSync(join(dirPath, 'package.json'), { encoding: 'utf8' })).main || + entryPoint; + } + } catch (ignored) { + // ignored + } + + return entryPoint; +} + +function isDirectory(path) { + try { + if (statSync(path).isDirectory()) return true; + } catch (ignored) { + // Nothing to do here + } + return false; +} + +export function getDynamicRequireModules(patterns, dynamicRequireRoot) { + const dynamicRequireModules = new Map(); + const dirNames = new Set(); + for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) { + const isNegated = pattern.startsWith('!'); + const modifyMap = (targetPath, resolvedPath) => + isNegated + ? dynamicRequireModules.delete(targetPath) + : dynamicRequireModules.set(targetPath, resolvedPath); + for (const path of glob.sync(isNegated ? pattern.substr(1) : pattern)) { + const resolvedPath = resolve(path); + const requirePath = normalizePathSlashes(resolvedPath); + if (isDirectory(resolvedPath)) { + dirNames.add(resolvedPath); + const modulePath = resolve(join(resolvedPath, getPackageEntryPoint(path))); + modifyMap(requirePath, modulePath); + modifyMap(normalizePathSlashes(modulePath), modulePath); + } else { + dirNames.add(dirname(resolvedPath)); + modifyMap(requirePath, resolvedPath); + } + } + } + return { + commonDir: dirNames.size ? getCommonDir([...dirNames, dynamicRequireRoot]) : null, + dynamicRequireModules + }; +} + +const FAILED_REQUIRE_ERROR = `throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');`; + +export const COMMONJS_REQUIRE_EXPORT = 'commonjsRequire'; +export const CREATE_COMMONJS_REQUIRE_EXPORT = 'createCommonjsRequire'; + +export function getDynamicModuleRegistry( + isDynamicRequireModulesEnabled, + dynamicRequireModules, + commonDir, + ignoreDynamicRequires +) { + if (!isDynamicRequireModulesEnabled) { + return `export function ${COMMONJS_REQUIRE_EXPORT}(path) { + ${FAILED_REQUIRE_ERROR} +}`; + } + const dynamicModuleImports = [...dynamicRequireModules.values()] + .map( + (id, index) => + `import ${ + id.endsWith('.json') ? `json${index}` : `{ __require as require${index} }` + } from ${JSON.stringify(id)};` + ) + .join('\n'); + const dynamicModuleProps = [...dynamicRequireModules.keys()] + .map( + (id, index) => + `\t\t${JSON.stringify(getVirtualPathForDynamicRequirePath(id, commonDir))}: ${ + id.endsWith('.json') ? `function () { return json${index}; }` : `require${index}` + }` + ) + .join(',\n'); + return `${dynamicModuleImports} + +var dynamicModules; + +function getDynamicModules() { + return dynamicModules || (dynamicModules = { +${dynamicModuleProps} + }); +} + +export function ${CREATE_COMMONJS_REQUIRE_EXPORT}(originalModuleDir) { + function handleRequire(path) { + var resolvedPath = commonjsResolve(path, originalModuleDir); + if (resolvedPath !== null) { + return getDynamicModules()[resolvedPath](); + } + ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR} + } + handleRequire.resolve = function (path) { + var resolvedPath = commonjsResolve(path, originalModuleDir); + if (resolvedPath !== null) { + return resolvedPath; + } + return require.resolve(path); + } + return handleRequire; +} + +function commonjsResolve (path, originalModuleDir) { + var shouldTryNodeModules = isPossibleNodeModulesPath(path); + path = normalize(path); + var relPath; + if (path[0] === '/') { + originalModuleDir = ''; + } + var modules = getDynamicModules(); + var checkedExtensions = ['', '.js', '.json']; + while (true) { + if (!shouldTryNodeModules) { + relPath = normalize(originalModuleDir + '/' + path); + } else { + relPath = normalize(originalModuleDir + '/node_modules/' + path); + } + + if (relPath.endsWith('/..')) { + break; // Travelled too far up, avoid infinite loop + } + + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) { + var resolvedPath = relPath + checkedExtensions[extensionIndex]; + if (modules[resolvedPath]) { + return resolvedPath; + } + } + if (!shouldTryNodeModules) break; + var nextDir = normalize(originalModuleDir + '/..'); + if (nextDir === originalModuleDir) break; + originalModuleDir = nextDir; + } + return null; +} + +function isPossibleNodeModulesPath (modulePath) { + var c0 = modulePath[0]; + if (c0 === '/' || c0 === '\\\\') return false; + var c1 = modulePath[1], c2 = modulePath[2]; + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) || + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false; + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false; + return true; +} + +function normalize (path) { + path = path.replace(/\\\\/g, '/'); + var parts = path.split('/'); + var slashed = parts[0] === ''; + for (var i = 1; i < parts.length; i++) { + if (parts[i] === '.' || parts[i] === '') { + parts.splice(i--, 1); + } + } + for (var i = 1; i < parts.length; i++) { + if (parts[i] !== '..') continue; + if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') { + parts.splice(--i, 2); + i--; + } + } + path = parts.join('/'); + if (slashed && path[0] !== '/') path = '/' + path; + else if (path.length === 0) path = '.'; + return path; +}`; +} diff --git a/packages/commonjs/src/dynamic-packages-manager.js b/packages/commonjs/src/dynamic-packages-manager.js deleted file mode 100644 index 4e754850b..000000000 --- a/packages/commonjs/src/dynamic-packages-manager.js +++ /dev/null @@ -1,56 +0,0 @@ -import { existsSync, readFileSync } from 'fs'; -import { join } from 'path'; - -import { DYNAMIC_PACKAGES_ID, DYNAMIC_REGISTER_SUFFIX, HELPERS_ID, wrapId } from './helpers'; -import { getVirtualPathForDynamicRequirePath, normalizePathSlashes } from './utils'; - -export function getPackageEntryPoint(dirPath) { - let entryPoint = 'index.js'; - - try { - if (existsSync(join(dirPath, 'package.json'))) { - entryPoint = - JSON.parse(readFileSync(join(dirPath, 'package.json'), { encoding: 'utf8' })).main || - entryPoint; - } - } catch (ignored) { - // ignored - } - - return entryPoint; -} - -export function getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir) { - let code = `const commonjsRegisterOrShort = require('${HELPERS_ID}?commonjsRegisterOrShort');`; - for (const dir of dynamicRequireModuleDirPaths) { - const entryPoint = getPackageEntryPoint(dir); - - code += `\ncommonjsRegisterOrShort(${JSON.stringify( - getVirtualPathForDynamicRequirePath(dir, commonDir) - )}, ${JSON.stringify(getVirtualPathForDynamicRequirePath(join(dir, entryPoint), commonDir))});`; - } - return code; -} - -export function getDynamicPackagesEntryIntro( - dynamicRequireModuleDirPaths, - dynamicRequireModuleSet -) { - let dynamicImports = Array.from( - dynamicRequireModuleSet, - (dynamicId) => `require(${JSON.stringify(wrapId(dynamicId, DYNAMIC_REGISTER_SUFFIX))});` - ).join('\n'); - - if (dynamicRequireModuleDirPaths.length) { - dynamicImports += `require(${JSON.stringify( - wrapId(DYNAMIC_PACKAGES_ID, DYNAMIC_REGISTER_SUFFIX) - )});`; - } - - return dynamicImports; -} - -export function isDynamicModuleImport(id, dynamicRequireModuleSet) { - const normalizedPath = normalizePathSlashes(id); - return dynamicRequireModuleSet.has(normalizedPath) && !normalizedPath.endsWith('.json'); -} diff --git a/packages/commonjs/src/dynamic-require-paths.js b/packages/commonjs/src/dynamic-require-paths.js deleted file mode 100644 index f944a0d33..000000000 --- a/packages/commonjs/src/dynamic-require-paths.js +++ /dev/null @@ -1,35 +0,0 @@ -import { statSync } from 'fs'; - -import { join, resolve } from 'path'; - -import glob from 'glob'; - -import { normalizePathSlashes } from './utils'; -import { getPackageEntryPoint } from './dynamic-packages-manager'; - -function isDirectory(path) { - try { - if (statSync(path).isDirectory()) return true; - } catch (ignored) { - // Nothing to do here - } - return false; -} - -export default function getDynamicRequirePaths(patterns) { - const dynamicRequireModuleSet = new Set(); - for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) { - const isNegated = pattern.startsWith('!'); - const modifySet = Set.prototype[isNegated ? 'delete' : 'add'].bind(dynamicRequireModuleSet); - for (const path of glob.sync(isNegated ? pattern.substr(1) : pattern)) { - modifySet(normalizePathSlashes(resolve(path))); - if (isDirectory(path)) { - modifySet(normalizePathSlashes(resolve(join(path, getPackageEntryPoint(path))))); - } - } - } - const dynamicRequireModuleDirPaths = Array.from(dynamicRequireModuleSet.values()).filter((path) => - isDirectory(path) - ); - return { dynamicRequireModuleSet, dynamicRequireModuleDirPaths }; -} diff --git a/packages/commonjs/src/generate-exports.js b/packages/commonjs/src/generate-exports.js index f94ae3fe4..1c5faa41d 100644 --- a/packages/commonjs/src/generate-exports.js +++ b/packages/commonjs/src/generate-exports.js @@ -11,8 +11,9 @@ export function wrapCode(magicString, uses, moduleName, exportsName) { } magicString .trim() + .indent('\t') .prepend(`(function (${args.join(', ')}) {\n`) - .append(`\n}(${passedArgs.join(', ')}));`); + .append(`\n} (${passedArgs.join(', ')}));`); } export function rewriteExportsAndGetExportsBlock( @@ -30,12 +31,27 @@ export function rewriteExportsAndGetExportsBlock( HELPERS_NAME, exportMode, detectWrappedDefault, - defaultIsModuleExports + defaultIsModuleExports, + usesRequireWrapper, + requireName ) { const exports = []; const exportDeclarations = []; - if (exportMode === 'replace') { + if (usesRequireWrapper) { + getExportsWhenUsingRequireWrapper( + magicString, + wrapped, + exportMode, + exports, + moduleExportsAssignments, + exportsAssignmentsByName, + moduleName, + exportsName, + requireName, + defineCompiledEsmExpressions + ); + } else if (exportMode === 'replace') { getExportsForReplacedModuleExports( magicString, exports, @@ -78,6 +94,49 @@ export function rewriteExportsAndGetExportsBlock( return `\n\n${exportDeclarations.join('\n')}`; } +function getExportsWhenUsingRequireWrapper( + magicString, + wrapped, + exportMode, + exports, + moduleExportsAssignments, + exportsAssignmentsByName, + moduleName, + exportsName, + requireName, + defineCompiledEsmExpressions +) { + if (!wrapped) { + if (exportMode === 'replace') { + for (const { left } of moduleExportsAssignments) { + magicString.overwrite(left.start, left.end, exportsName); + } + } else { + // 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) { + for (const node of nodes) { + magicString.overwrite(node.start, node.left.end, `${exportsName}.${exportName}`); + } + } + // Collect and rewrite exports.__esModule assignments + for (const expression of defineCompiledEsmExpressions) { + const moduleExportsExpression = + expression.type === 'CallExpression' ? expression.arguments[0] : expression.left.object; + magicString.overwrite( + moduleExportsExpression.start, + moduleExportsExpression.end, + exportsName + ); + } + } + } + exports.push(`${requireName} as __require`); +} + function getExportsForReplacedModuleExports( magicString, exports, @@ -165,7 +224,7 @@ function getExports( } if (!isRestorableCompiledEsm || defaultIsModuleExports === true) { - exportDeclarations.push(`export default ${exportsName};`); + exports.push(`${exportsName} as default`); } else if (moduleExportsAssignments.length === 0 || defaultIsModuleExports === false) { exports.push(`${deconflictedDefaultExportName || exportsName} as default`); } else { diff --git a/packages/commonjs/src/generate-imports.js b/packages/commonjs/src/generate-imports.js index a39ac5977..59fdd997d 100644 --- a/packages/commonjs/src/generate-imports.js +++ b/packages/commonjs/src/generate-imports.js @@ -1,18 +1,16 @@ -import { dirname, resolve } from 'path'; - -import { sync as nodeResolveSync } from 'resolve'; - +import { COMMONJS_REQUIRE_EXPORT, CREATE_COMMONJS_REQUIRE_EXPORT } from './dynamic-modules'; import { + DYNAMIC_MODULES_ID, EXPORTS_SUFFIX, + EXTERNAL_SUFFIX, HELPERS_ID, + IS_WRAPPED_COMMONJS, + isWrappedId, MODULE_SUFFIX, - PROXY_SUFFIX, - REQUIRE_SUFFIX, wrapId } from './helpers'; -import { normalizePathSlashes } from './utils'; -export function isRequireStatement(node, scope) { +export function isRequireExpression(node, scope) { if (!node) return false; if (node.type !== 'CallExpression') return false; @@ -22,7 +20,7 @@ export function isRequireStatement(node, scope) { return isRequire(node.callee, scope); } -function isRequire(node, scope) { +export function isRequire(node, scope) { return ( (node.type === 'Identifier' && node.name === 'require' && !scope.contains('require')) || (node.type === 'MemberExpression' && isModuleRequire(node, scope)) @@ -39,12 +37,7 @@ export function isModuleRequire({ object, property }, scope) { ); } -export function isStaticRequireStatement(node, scope) { - if (!isRequireStatement(node, scope)) return false; - return !hasDynamicArguments(node); -} - -function hasDynamicArguments(node) { +export function hasDynamicArguments(node) { return ( node.arguments.length > 1 || (node.arguments[0].type !== 'Literal' && @@ -58,89 +51,61 @@ export function isNodeRequirePropertyAccess(parent) { return parent && parent.property && reservedMethod[parent.property.name]; } -export function isIgnoredRequireStatement(requiredNode, ignoreRequire) { - return ignoreRequire(requiredNode.arguments[0].value); -} - export function getRequireStringArg(node) { return node.arguments[0].type === 'Literal' ? node.arguments[0].value : node.arguments[0].quasis[0].value.cooked; } -export function hasDynamicModuleForPath(source, id, dynamicRequireModuleSet) { - if (!/^(?:\.{0,2}[/\\]|[A-Za-z]:[/\\])/.test(source)) { - try { - const resolvedPath = normalizePathSlashes(nodeResolveSync(source, { basedir: dirname(id) })); - if (dynamicRequireModuleSet.has(resolvedPath)) { - return true; - } - } catch (ex) { - // Probably a node.js internal module - return false; - } - - return false; - } - - for (const attemptExt of ['', '.js', '.json']) { - const resolvedPath = normalizePathSlashes(resolve(dirname(id), source + attemptExt)); - if (dynamicRequireModuleSet.has(resolvedPath)) { - return true; - } - } - - return false; -} - export function getRequireHandlers() { - const requiredSources = []; - const requiredBySource = Object.create(null); - const requiredByNode = new Map(); - const requireExpressionsWithUsedReturnValue = []; - - function addRequireStatement(sourceId, node, scope, usesReturnValue) { - const required = getRequired(sourceId); - requiredByNode.set(node, { scope, required }); - if (usesReturnValue) { - required.nodesUsingRequired.push(node); - requireExpressionsWithUsedReturnValue.push(node); - } - } - - function getRequired(sourceId) { - if (!requiredBySource[sourceId]) { - requiredSources.push(sourceId); - - requiredBySource[sourceId] = { - source: sourceId, - name: null, - nodesUsingRequired: [] - }; - } - - return requiredBySource[sourceId]; + const requireExpressions = []; + + function addRequireExpression( + sourceId, + node, + scope, + usesReturnValue, + isInsideTryBlock, + isInsideConditional, + toBeRemoved + ) { + requireExpressions.push({ + sourceId, + node, + scope, + usesReturnValue, + isInsideTryBlock, + isInsideConditional, + toBeRemoved + }); } - function rewriteRequireExpressionsAndGetImportBlock( + async function rewriteRequireExpressionsAndGetImportBlock( magicString, topLevelDeclarations, - topLevelRequireDeclarators, reassignedNames, helpersName, - dynamicRegisterSources, + dynamicRequireName, moduleName, exportsName, id, - exportMode + exportMode, + resolveRequireSourcesAndUpdateMeta, + needsRequireWrapper, + isEsModule, + isDynamicRequireModulesEnabled, + getIgnoreTryCatchRequireStatementMode, + commonjsMeta ) { - setRemainingImportNamesAndRewriteRequires( - requireExpressionsWithUsedReturnValue, - requiredByNode, - magicString - ); const imports = []; imports.push(`import * as ${helpersName} from "${HELPERS_ID}";`); + if (dynamicRequireName) { + imports.push( + `import { ${ + isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT + } as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}";` + ); + } if (exportMode === 'module') { imports.push( `import { __module as ${moduleName}, exports as ${exportsName} } from ${JSON.stringify( @@ -152,47 +117,102 @@ export function getRequireHandlers() { `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) - )};` - ); - } + const requiresBySource = collectSources(requireExpressions); + const requireTargets = await resolveRequireSourcesAndUpdateMeta( + id, + needsRequireWrapper ? IS_WRAPPED_COMMONJS : !isEsModule, + commonjsMeta, + Object.keys(requiresBySource).map((source) => { + return { + source, + isConditional: requiresBySource[source].every((require) => require.isInsideConditional) + }; + }) + ); + processRequireExpressions( + imports, + requireTargets, + requiresBySource, + getIgnoreTryCatchRequireStatementMode, + magicString + ); return imports.length ? `${imports.join('\n')}\n\n` : ''; } return { - addRequireStatement, - requiredSources, + addRequireExpression, rewriteRequireExpressionsAndGetImportBlock }; } -function setRemainingImportNamesAndRewriteRequires( - requireExpressionsWithUsedReturnValue, - requiredByNode, +function collectSources(requireExpressions) { + const requiresBySource = Object.create(null); + for (const requireExpression of requireExpressions) { + const { sourceId } = requireExpression; + if (!requiresBySource[sourceId]) { + requiresBySource[sourceId] = []; + } + const requires = requiresBySource[sourceId]; + requires.push(requireExpression); + } + return requiresBySource; +} + +function processRequireExpressions( + imports, + requireTargets, + requiresBySource, + getIgnoreTryCatchRequireStatementMode, magicString ) { - let uid = 0; - for (const requireExpression of requireExpressionsWithUsedReturnValue) { - const { required } = requiredByNode.get(requireExpression); - if (!required.name) { - let potentialName; - const isUsedName = (node) => requiredByNode.get(node).scope.contains(potentialName); - do { - potentialName = `require$$${uid}`; - uid += 1; - } while (required.nodesUsingRequired.some(isUsedName)); - required.name = potentialName; + const generateRequireName = getGenerateRequireName(); + for (const { source, id: resolvedId, isCommonJS } of requireTargets) { + const requires = requiresBySource[source]; + const name = generateRequireName(requires); + let usesRequired = false; + let needsImport = false; + for (const { node, usesReturnValue, toBeRemoved, isInsideTryBlock } of requires) { + const { canConvertRequire, shouldRemoveRequire } = + isInsideTryBlock && isWrappedId(resolvedId, EXTERNAL_SUFFIX) + ? getIgnoreTryCatchRequireStatementMode(source) + : { canConvertRequire: true, shouldRemoveRequire: false }; + if (shouldRemoveRequire) { + if (usesReturnValue) { + magicString.overwrite(node.start, node.end, 'undefined'); + } else { + magicString.remove(toBeRemoved.start, toBeRemoved.end); + } + } else if (canConvertRequire) { + needsImport = true; + if (isCommonJS === IS_WRAPPED_COMMONJS) { + magicString.overwrite(node.start, node.end, `${name}()`); + } else if (usesReturnValue) { + usesRequired = true; + magicString.overwrite(node.start, node.end, name); + } else { + magicString.remove(toBeRemoved.start, toBeRemoved.end); + } + } + } + if (needsImport) { + if (isCommonJS === IS_WRAPPED_COMMONJS) { + imports.push(`import { __require as ${name} } from ${JSON.stringify(resolvedId)};`); + } else { + imports.push(`import ${usesRequired ? `${name} from ` : ''}${JSON.stringify(resolvedId)};`); + } } - magicString.overwrite(requireExpression.start, requireExpression.end, required.name); } } + +function getGenerateRequireName() { + let uid = 0; + return (requires) => { + let name; + const hasNameConflict = ({ scope }) => scope.contains(name); + do { + name = `require$$${uid}`; + uid += 1; + } while (requires.some(hasNameConflict)); + return name; + }; +} diff --git a/packages/commonjs/src/helpers.js b/packages/commonjs/src/helpers.js index b358a9d0c..94d770d38 100644 --- a/packages/commonjs/src/helpers.js +++ b/packages/commonjs/src/helpers.js @@ -3,21 +3,21 @@ export const wrapId = (id, suffix) => `\0${id}${suffix}`; export const unwrapId = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length); export const PROXY_SUFFIX = '?commonjs-proxy'; -export const REQUIRE_SUFFIX = '?commonjs-require'; +export const WRAPPED_SUFFIX = '?commonjs-wrapped'; export const EXTERNAL_SUFFIX = '?commonjs-external'; export const EXPORTS_SUFFIX = '?commonjs-exports'; export const MODULE_SUFFIX = '?commonjs-module'; +export const ENTRY_SUFFIX = '?commonjs-entry'; +export const ES_IMPORT_SUFFIX = '?commonjs-es-import'; -export const DYNAMIC_REGISTER_SUFFIX = '?commonjs-dynamic-register'; -export const DYNAMIC_JSON_PREFIX = '\0commonjs-dynamic-json:'; -export const DYNAMIC_PACKAGES_ID = '\0commonjs-dynamic-packages'; - +export const DYNAMIC_MODULES_ID = '\0commonjs-dynamic-modules'; export const HELPERS_ID = '\0commonjsHelpers.js'; +export const IS_WRAPPED_COMMONJS = 'withRequireFunction'; + // `x['default']` is used instead of `x.default` for backward compatibility with ES3 browsers. // Minifiers like uglify will usually transpile it back if compatibility with ES3 is not enabled. -// This will no longer be necessary once Rollup switches to ES6 output, likely -// in Rollup 3 +// This could be improved by inspecting Rollup's "generatedCode" option const HELPERS = ` export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; @@ -35,8 +35,14 @@ export function getDefaultExportFromNamespaceIfNotNamed (n) { } export function getAugmentedNamespace(n) { - if (n.__esModule) return n; - var a = Object.defineProperty({}, '__esModule', {value: true}); + var f = n.default; + if (typeof f == "function") { + var a = function () { + return f.apply(this, arguments); + }; + a.prototype = f.prototype; + } else a = {}; + Object.defineProperty(a, '__esModule', {value: true}); Object.keys(n).forEach(function (k) { var d = Object.getOwnPropertyDescriptor(n, k); Object.defineProperty(a, k, d.get ? d : { @@ -50,215 +56,6 @@ export function getAugmentedNamespace(n) { } `; -const FAILED_REQUIRE_ERROR = `throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');`; - -const HELPER_NON_DYNAMIC = ` -export function commonjsRequire (path) { - ${FAILED_REQUIRE_ERROR} -} -`; - -const getDynamicHelpers = (ignoreDynamicRequires) => ` -export function createModule(modulePath) { - return { - path: modulePath, - exports: {}, - require: function (path, base) { - return commonjsRequire(path, base == null ? modulePath : base); - } - }; -} - -export function commonjsRegister (path, loader) { - DYNAMIC_REQUIRE_LOADERS[path] = loader; -} - -export function commonjsRegisterOrShort (path, to) { - var resolvedPath = commonjsResolveImpl(path, null, true); - if (resolvedPath !== null && DYNAMIC_REQUIRE_CACHE[resolvedPath]) { - DYNAMIC_REQUIRE_CACHE[path] = DYNAMIC_REQUIRE_CACHE[resolvedPath]; - } else { - DYNAMIC_REQUIRE_SHORTS[path] = to; - } -} - -var DYNAMIC_REQUIRE_LOADERS = Object.create(null); -var DYNAMIC_REQUIRE_CACHE = Object.create(null); -var DYNAMIC_REQUIRE_SHORTS = Object.create(null); -var DEFAULT_PARENT_MODULE = { - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: [] -}; -var CHECKED_EXTENSIONS = ['', '.js', '.json']; - -function normalize (path) { - path = path.replace(/\\\\/g, '/'); - var parts = path.split('/'); - var slashed = parts[0] === ''; - for (var i = 1; i < parts.length; i++) { - if (parts[i] === '.' || parts[i] === '') { - parts.splice(i--, 1); - } - } - for (var i = 1; i < parts.length; i++) { - if (parts[i] !== '..') continue; - if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') { - parts.splice(--i, 2); - i--; - } - } - path = parts.join('/'); - if (slashed && path[0] !== '/') - path = '/' + path; - else if (path.length === 0) - path = '.'; - return path; -} - -function join () { - if (arguments.length === 0) - return '.'; - var joined; - for (var i = 0; i < arguments.length; ++i) { - var arg = arguments[i]; - if (arg.length > 0) { - if (joined === undefined) - joined = arg; - else - joined += '/' + arg; - } - } - if (joined === undefined) - return '.'; - - return joined; -} - -function isPossibleNodeModulesPath (modulePath) { - var c0 = modulePath[0]; - if (c0 === '/' || c0 === '\\\\') return false; - var c1 = modulePath[1], c2 = modulePath[2]; - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) || - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false; - if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) - return false; - return true; -} - -function dirname (path) { - if (path.length === 0) - return '.'; - - var i = path.length - 1; - while (i > 0) { - var c = path.charCodeAt(i); - if ((c === 47 || c === 92) && i !== path.length - 1) - break; - i--; - } - - if (i > 0) - return path.substr(0, i); - - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92) - return path.charAt(0); - - return '.'; -} - -export function commonjsResolveImpl (path, originalModuleDir, testCache) { - var shouldTryNodeModules = isPossibleNodeModulesPath(path); - path = normalize(path); - var relPath; - if (path[0] === '/') { - originalModuleDir = '/'; - } - while (true) { - if (!shouldTryNodeModules) { - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path; - } else if (originalModuleDir) { - relPath = normalize(originalModuleDir + '/node_modules/' + path); - } else { - relPath = normalize(join('node_modules', path)); - } - - if (relPath.endsWith('/..')) { - break; // Travelled too far up, avoid infinite loop - } - - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) { - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex]; - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) { - return resolvedPath; - } - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) { - return resolvedPath; - } - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) { - return resolvedPath; - } - } - if (!shouldTryNodeModules) break; - var nextDir = normalize(originalModuleDir + '/..'); - if (nextDir === originalModuleDir) break; - originalModuleDir = nextDir; - } - return null; -} - -export function commonjsResolve (path, originalModuleDir) { - var resolvedPath = commonjsResolveImpl(path, originalModuleDir); - if (resolvedPath !== null) { - return resolvedPath; - } - return require.resolve(path); -} - -export function commonjsRequire (path, originalModuleDir) { - var resolvedPath = commonjsResolveImpl(path, originalModuleDir, true); - if (resolvedPath !== null) { - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath]; - if (cachedModule) return cachedModule.exports; - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath]; - if (shortTo) { - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo]; - if (cachedModule) - return cachedModule.exports; - resolvedPath = commonjsResolveImpl(shortTo, null, true); - } - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath]; - if (loader) { - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = { - id: resolvedPath, - filename: resolvedPath, - path: dirname(resolvedPath), - exports: {}, - parent: DEFAULT_PARENT_MODULE, - loaded: false, - children: [], - paths: [], - require: function (path, base) { - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base); - } - }; - try { - loader.call(commonjsGlobal, cachedModule, cachedModule.exports); - } catch (error) { - delete DYNAMIC_REQUIRE_CACHE[resolvedPath]; - throw error; - } - cachedModule.loaded = true; - return cachedModule.exports; - }; - } - ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR} -} - -commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE; -commonjsRequire.resolve = commonjsResolve; -`; - -export function getHelpersModule(isDynamicRequireModulesEnabled, ignoreDynamicRequires) { - return `${HELPERS}${ - isDynamicRequireModulesEnabled ? getDynamicHelpers(ignoreDynamicRequires) : HELPER_NON_DYNAMIC - }`; +export function getHelpersModule() { + return HELPERS; } diff --git a/packages/commonjs/src/index.js b/packages/commonjs/src/index.js index 1a6abfc37..3c8f5f642 100644 --- a/packages/commonjs/src/index.js +++ b/packages/commonjs/src/index.js @@ -1,22 +1,16 @@ -import { dirname, extname } from 'path'; +import { extname, relative, resolve, dirname } from 'path'; import { createFilter } from '@rollup/pluginutils'; -import getCommonDir from 'commondir'; -import { peerDependencies } from '../package.json'; +import { peerDependencies, version } from '../package.json'; import analyzeTopLevelStatements from './analyze-top-level-statements'; +import { getDynamicModuleRegistry, getDynamicRequireModules } from './dynamic-modules'; import { - getDynamicPackagesEntryIntro, - getDynamicPackagesModule, - isDynamicModuleImport -} from './dynamic-packages-manager'; -import getDynamicRequirePaths from './dynamic-require-paths'; -import { - DYNAMIC_JSON_PREFIX, - DYNAMIC_PACKAGES_ID, - DYNAMIC_REGISTER_SUFFIX, + DYNAMIC_MODULES_ID, + ENTRY_SUFFIX, + ES_IMPORT_SUFFIX, EXPORTS_SUFFIX, EXTERNAL_SUFFIX, getHelpersModule, @@ -26,23 +20,22 @@ import { PROXY_SUFFIX, unwrapId } from './helpers'; -import { setCommonJSMetaPromise } from './is-cjs'; import { hasCjsKeywords } from './parse'; import { - getDynamicJsonProxy, - getDynamicRequireProxy, - getSpecificHelperProxy, + getEntryProxy, + getEsImportProxy, getStaticRequireProxy, getUnknownRequireProxy } from './proxies'; import getResolveId from './resolve-id'; -import validateRollupVersion from './rollup-version'; +import { getRequireResolver } from './resolve-require-sources'; +import validateVersion from './rollup-version'; import transformCommonjs from './transform-commonjs'; -import { getName, getVirtualPathForDynamicRequirePath, normalizePathSlashes } from './utils'; +import { getName, getStrictRequiresFilter, normalizePathSlashes } from './utils'; + +const PLUGIN_NAME = 'commonjs'; export default function commonjs(options = {}) { - const extensions = options.extensions || ['.js']; - const filter = createFilter(options.include, options.exclude); const { ignoreGlobal, ignoreDynamicRequires, @@ -50,10 +43,15 @@ export default function commonjs(options = {}) { defaultIsModuleExports: defaultIsModuleExportsOption, esmExternals } = options; + const extensions = options.extensions || ['.js']; + const filter = createFilter(options.include, options.exclude); + const { strictRequiresFilter, detectCyclesAndConditional } = getStrictRequiresFilter(options); + const getRequireReturnsDefault = typeof requireReturnsDefaultOption === 'function' ? requireReturnsDefaultOption : () => requireReturnsDefaultOption; + let esmExternalIds; const isEsmExternal = typeof esmExternals === 'function' @@ -61,23 +59,22 @@ export default function commonjs(options = {}) { : Array.isArray(esmExternals) ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id)) : () => esmExternals; + const getDefaultIsModuleExports = typeof defaultIsModuleExportsOption === 'function' ? defaultIsModuleExportsOption : () => typeof defaultIsModuleExportsOption === 'boolean' ? defaultIsModuleExportsOption : 'auto'; - const { dynamicRequireModuleSet, dynamicRequireModuleDirPaths } = getDynamicRequirePaths( - options.dynamicRequireTargets + const dynamicRequireRoot = + typeof options.dynamicRequireRoot === 'string' + ? resolve(options.dynamicRequireRoot) + : process.cwd(); + const { commonDir, dynamicRequireModules } = getDynamicRequireModules( + options.dynamicRequireTargets, + dynamicRequireRoot ); - const isDynamicRequireModulesEnabled = dynamicRequireModuleSet.size > 0; - const commonDir = isDynamicRequireModulesEnabled - ? getCommonDir(null, Array.from(dynamicRequireModuleSet).concat(process.cwd())) - : null; - - const esModulesWithDefaultExport = new Set(); - const esModulesWithNamedExports = new Set(); - const commonJsMetaPromises = new Map(); + const isDynamicRequireModulesEnabled = dynamicRequireModules.size > 0; const ignoreRequire = typeof options.ignore === 'function' @@ -98,46 +95,60 @@ export default function commonjs(options = {}) { return { canConvertRequire: mode !== 'remove' && mode !== true, - shouldRemoveRequireStatement: mode === 'remove' + shouldRemoveRequire: mode === 'remove' }; }; - const resolveId = getResolveId(extensions); + const { currentlyResolving, resolveId } = getResolveId(extensions); const sourceMap = options.sourceMap !== false; - function transformAndCheckExports(code, id) { - if (isDynamicRequireModulesEnabled && this.getModuleInfo(id).isEntry) { - // eslint-disable-next-line no-param-reassign - code = - getDynamicPackagesEntryIntro(dynamicRequireModuleDirPaths, dynamicRequireModuleSet) + code; - } + // Initialized in buildStart + let requireResolver; + function transformAndCheckExports(code, id) { const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements( this.parse, code, id ); + + const commonjsMeta = this.getModuleInfo(id).meta.commonjs || {}; if (hasDefaultExport) { - esModulesWithDefaultExport.add(id); + commonjsMeta.hasDefaultExport = true; } if (hasNamedExports) { - esModulesWithNamedExports.add(id); + commonjsMeta.hasNamedExports = true; } if ( - !dynamicRequireModuleSet.has(normalizePathSlashes(id)) && - (!hasCjsKeywords(code, ignoreGlobal) || (isEsModule && !options.transformMixedEsModules)) + !dynamicRequireModules.has(normalizePathSlashes(id)) && + (!(hasCjsKeywords(code, ignoreGlobal) || requireResolver.isRequiredId(id)) || + (isEsModule && !options.transformMixedEsModules)) ) { - return { meta: { commonjs: { isCommonJS: false } } }; + commonjsMeta.isCommonJS = false; + return { meta: { commonjs: commonjsMeta } }; } - // 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); - } + const needsRequireWrapper = + !isEsModule && + (dynamicRequireModules.has(normalizePathSlashes(id)) || strictRequiresFilter(id)); + + const checkDynamicRequire = (position) => { + if (id.indexOf(dynamicRequireRoot) !== 0) { + this.error( + { + code: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT', + id, + dynamicRequireRoot, + message: `"${id}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${dynamicRequireRoot}". You should set dynamicRequireRoot to "${dirname( + id + )}" or one of its parent directories.` + }, + position + ); + } + }; return transformCommonjs( this.parse, @@ -150,64 +161,93 @@ export default function commonjs(options = {}) { getIgnoreTryCatchRequireStatementMode, sourceMap, isDynamicRequireModulesEnabled, - dynamicRequireModuleSet, - disableWrap, + dynamicRequireModules, commonDir, ast, - getDefaultIsModuleExports(id) + getDefaultIsModuleExports(id), + needsRequireWrapper, + requireResolver.resolveRequireSourcesAndUpdateMeta(this), + requireResolver.isRequiredId(id), + checkDynamicRequire, + commonjsMeta ); } return { - name: 'commonjs', + name: PLUGIN_NAME, + + version, + + options(rawOptions) { + // We inject the resolver in the beginning so that "catch-all-resolver" like node-resolver + // do not prevent our plugin from resolving entry points ot proxies. + const plugins = Array.isArray(rawOptions.plugins) + ? [...rawOptions.plugins] + : rawOptions.plugins + ? [rawOptions.plugins] + : []; + plugins.unshift({ + name: 'commonjs--resolver', + resolveId + }); + return { ...rawOptions, plugins }; + }, - buildStart() { - validateRollupVersion(this.meta.rollupVersion, peerDependencies.rollup); + buildStart({ plugins }) { + validateVersion(this.meta.rollupVersion, peerDependencies.rollup, 'rollup'); + const nodeResolve = plugins.find(({ name }) => name === 'node-resolve'); + if (nodeResolve) { + validateVersion(nodeResolve.version, '^13.0.6', '@rollup/plugin-node-resolve'); + } if (options.namedExports != null) { this.warn( 'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.' ); } + requireResolver = getRequireResolver( + extensions, + detectCyclesAndConditional, + currentlyResolving + ); }, - resolveId, + buildEnd() { + if (options.strictRequires === 'debug') { + const wrappedIds = requireResolver.getWrappedIds(); + if (wrappedIds.length) { + this.warn({ + code: 'WRAPPED_IDS', + ids: wrappedIds, + message: `The commonjs plugin automatically wrapped the following files:\n[\n${wrappedIds + .map((id) => `\t${JSON.stringify(relative(process.cwd(), id))}`) + .join(',\n')}\n]` + }); + } else { + this.warn({ + code: 'WRAPPED_IDS', + ids: wrappedIds, + message: 'The commonjs plugin did not wrap any files.' + }); + } + } + }, load(id) { if (id === HELPERS_ID) { - return getHelpersModule(isDynamicRequireModulesEnabled, ignoreDynamicRequires); - } - - if (id.startsWith(HELPERS_ID)) { - return getSpecificHelperProxy(id); + return getHelpersModule(); } 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}`; - } + const name = getName(unwrapId(id, MODULE_SUFFIX)); return { - code, + code: `var ${name} = {exports: {}}; export {${name} as __module}`, syntheticNamedExports: '__module', meta: { commonjs: { isCommonJS: false } } }; } if (isWrappedId(id, EXPORTS_SUFFIX)) { - const actualId = unwrapId(id, EXPORTS_SUFFIX); - const name = getName(actualId); + const name = getName(unwrapId(id, EXPORTS_SUFFIX)); return { code: `var ${name} = {}; export {${name} as __exports}`, meta: { commonjs: { isCommonJS: false } } @@ -222,69 +262,49 @@ export default function commonjs(options = {}) { ); } - if (id === DYNAMIC_PACKAGES_ID) { - return getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir); + // entry suffix is just appended to not mess up relative external resolution + if (id.endsWith(ENTRY_SUFFIX)) { + const acutalId = id.slice(0, -ENTRY_SUFFIX.length); + return getEntryProxy(acutalId, getDefaultIsModuleExports(acutalId), this.getModuleInfo); } - if (id.startsWith(DYNAMIC_JSON_PREFIX)) { - return getDynamicJsonProxy(id, commonDir); + if (isWrappedId(id, ES_IMPORT_SUFFIX)) { + const actualId = unwrapId(id, ES_IMPORT_SUFFIX); + return getEsImportProxy(actualId, getDefaultIsModuleExports(actualId)); } - if (isDynamicModuleImport(id, dynamicRequireModuleSet)) { - return `export default require(${JSON.stringify(normalizePathSlashes(id))});`; - } - - if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) { - return getDynamicRequireProxy( - normalizePathSlashes(unwrapId(id, DYNAMIC_REGISTER_SUFFIX)), - commonDir + if (id === DYNAMIC_MODULES_ID) { + return getDynamicModuleRegistry( + isDynamicRequireModulesEnabled, + dynamicRequireModules, + commonDir, + ignoreDynamicRequires ); } if (isWrappedId(id, PROXY_SUFFIX)) { const actualId = unwrapId(id, PROXY_SUFFIX); - return getStaticRequireProxy( - actualId, - getRequireReturnsDefault(actualId), - esModulesWithDefaultExport, - esModulesWithNamedExports, - commonJsMetaPromises - ); + return getStaticRequireProxy(actualId, getRequireReturnsDefault(actualId), this.load); } return null; }, - transform(code, rawId) { - let id = rawId; - - if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) { - id = unwrapId(id, DYNAMIC_REGISTER_SUFFIX); - } + shouldTransformCachedModule(...args) { + return requireResolver.shouldTransformCachedModule.call(this, ...args); + }, + transform(code, id) { const extName = extname(id); - if ( - extName !== '.cjs' && - id !== DYNAMIC_PACKAGES_ID && - !id.startsWith(DYNAMIC_JSON_PREFIX) && - (!filter(id) || !extensions.includes(extName)) - ) { + if (extName !== '.cjs' && (!filter(id) || !extensions.includes(extName))) { return null; } try { - return transformAndCheckExports.call(this, code, rawId); + return transformAndCheckExports.call(this, code, id); } catch (err) { return this.error(err, err.loc); } - }, - - moduleParsed({ id, meta: { commonjs: commonjsMeta } }) { - if (commonjsMeta && commonjsMeta.isCommonJS != null) { - setCommonJSMetaPromise(commonJsMetaPromises, id, commonjsMeta); - return; - } - setCommonJSMetaPromise(commonJsMetaPromises, id, null); } }; } diff --git a/packages/commonjs/src/is-cjs.js b/packages/commonjs/src/is-cjs.js deleted file mode 100644 index 8c88f09fa..000000000 --- a/packages/commonjs/src/is-cjs.js +++ /dev/null @@ -1,27 +0,0 @@ -export function getCommonJSMetaPromise(commonJSMetaPromises, id) { - let commonJSMetaPromise = commonJSMetaPromises.get(id); - if (commonJSMetaPromise) return commonJSMetaPromise.promise; - - const promise = new Promise((resolve) => { - commonJSMetaPromise = { - resolve, - promise: null - }; - commonJSMetaPromises.set(id, commonJSMetaPromise); - }); - commonJSMetaPromise.promise = promise; - - return promise; -} - -export function setCommonJSMetaPromise(commonJSMetaPromises, id, commonjsMeta) { - const commonJSMetaPromise = commonJSMetaPromises.get(id); - if (commonJSMetaPromise) { - if (commonJSMetaPromise.resolve) { - commonJSMetaPromise.resolve(commonjsMeta); - commonJSMetaPromise.resolve = null; - } - } else { - commonJSMetaPromises.set(id, { promise: Promise.resolve(commonjsMeta), resolve: null }); - } -} diff --git a/packages/commonjs/src/proxies.js b/packages/commonjs/src/proxies.js index f8050bc6a..eb6ff9ea5 100644 --- a/packages/commonjs/src/proxies.js +++ b/packages/commonjs/src/proxies.js @@ -1,60 +1,31 @@ -import { readFileSync } from 'fs'; - -import { DYNAMIC_JSON_PREFIX, HELPERS_ID } from './helpers'; -import { getCommonJSMetaPromise } from './is-cjs'; -import { getName, getVirtualPathForDynamicRequirePath, normalizePathSlashes } from './utils'; - -// e.g. id === "commonjsHelpers?commonjsRegister" -export function getSpecificHelperProxy(id) { - return `export {${id.split('?')[1]} as default} from "${HELPERS_ID}";`; -} +import { HELPERS_ID, IS_WRAPPED_COMMONJS } from './helpers'; +import { capitalize, getName } from './utils'; export function getUnknownRequireProxy(id, requireReturnsDefault) { if (requireReturnsDefault === true || id.endsWith('.json')) { - return `export {default} from ${JSON.stringify(id)};`; + return `export { default } from ${JSON.stringify(id)};`; } const name = getName(id); const exported = requireReturnsDefault === 'auto' - ? `import {getDefaultExportFromNamespaceIfNotNamed} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});` + ? `import { getDefaultExportFromNamespaceIfNotNamed } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});` : requireReturnsDefault === 'preferred' - ? `import {getDefaultExportFromNamespaceIfPresent} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});` + ? `import { getDefaultExportFromNamespaceIfPresent } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});` : !requireReturnsDefault - ? `import {getAugmentedNamespace} from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});` + ? `import { getAugmentedNamespace } from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});` : `export default ${name};`; return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`; } -export function getDynamicJsonProxy(id, commonDir) { - const normalizedPath = normalizePathSlashes(id.slice(DYNAMIC_JSON_PREFIX.length)); - return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify( - getVirtualPathForDynamicRequirePath(normalizedPath, commonDir) - )}, function (module, exports) { - module.exports = require(${JSON.stringify(normalizedPath)}); -});`; -} - -export function getDynamicRequireProxy(normalizedPath, commonDir) { - return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify( - getVirtualPathForDynamicRequirePath(normalizedPath, commonDir) - )}, function (module, exports) { - ${readFileSync(normalizedPath, { encoding: 'utf8' })} -});`; -} - -export async function getStaticRequireProxy( - id, - requireReturnsDefault, - esModulesWithDefaultExport, - esModulesWithNamedExports, - commonJsMetaPromises -) { +export async function getStaticRequireProxy(id, requireReturnsDefault, loadModule) { const name = getName(id); - const commonjsMeta = await getCommonJSMetaPromise(commonJsMetaPromises, id); - if (commonjsMeta && commonjsMeta.isCommonJS) { - return `export { __moduleExports as default } from ${JSON.stringify(id)};`; - } else if (commonjsMeta === null) { + const { + meta: { commonjs: commonjsMeta } + } = await loadModule({ id }); + if (!commonjsMeta) { return getUnknownRequireProxy(id, requireReturnsDefault); + } else if (commonjsMeta.isCommonJS) { + return `export { __moduleExports as default } from ${JSON.stringify(id)};`; } else if (!requireReturnsDefault) { return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify( id @@ -62,10 +33,46 @@ export async function getStaticRequireProxy( } else if ( requireReturnsDefault !== true && (requireReturnsDefault === 'namespace' || - !esModulesWithDefaultExport.has(id) || - (requireReturnsDefault === 'auto' && esModulesWithNamedExports.has(id))) + !commonjsMeta.hasDefaultExport || + (requireReturnsDefault === 'auto' && commonjsMeta.hasNamedExports)) ) { return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`; } return `export { default } from ${JSON.stringify(id)};`; } + +export function getEntryProxy(id, defaultIsModuleExports, getModuleInfo) { + const { + meta: { commonjs: commonjsMeta }, + hasDefaultExport + } = getModuleInfo(id); + if (!commonjsMeta || commonjsMeta.isCommonJS !== IS_WRAPPED_COMMONJS) { + const stringifiedId = JSON.stringify(id); + let code = `export * from ${stringifiedId};`; + if (hasDefaultExport) { + code += `export { default } from ${stringifiedId};`; + } + return code; + } + return getEsImportProxy(id, defaultIsModuleExports); +} + +export function getEsImportProxy(id, defaultIsModuleExports) { + const name = getName(id); + const exportsName = `${name}Exports`; + const requireModule = `require${capitalize(name)}`; + let code = + `import { getDefaultExportFromCjs } from "${HELPERS_ID}";\n` + + `import { __require as ${requireModule} } from ${JSON.stringify(id)};\n` + + `var ${exportsName} = ${requireModule}();\n` + + `export { ${exportsName} as __moduleExports };`; + if (defaultIsModuleExports) { + code += `\nexport { ${exportsName} as default };`; + } else { + code += `export default /*@__PURE__*/getDefaultExportFromCjs(${exportsName});`; + } + return { + code, + syntheticNamedExports: '__moduleExports' + }; +} diff --git a/packages/commonjs/src/resolve-id.js b/packages/commonjs/src/resolve-id.js index c22fe98b7..7fa7f04fe 100644 --- a/packages/commonjs/src/resolve-id.js +++ b/packages/commonjs/src/resolve-id.js @@ -4,18 +4,19 @@ import { statSync } from 'fs'; import { dirname, resolve, sep } from 'path'; import { - DYNAMIC_JSON_PREFIX, - DYNAMIC_PACKAGES_ID, - DYNAMIC_REGISTER_SUFFIX, + DYNAMIC_MODULES_ID, + ENTRY_SUFFIX, + ES_IMPORT_SUFFIX, EXPORTS_SUFFIX, EXTERNAL_SUFFIX, HELPERS_ID, + IS_WRAPPED_COMMONJS, isWrappedId, MODULE_SUFFIX, PROXY_SUFFIX, - REQUIRE_SUFFIX, unwrapId, - wrapId + wrapId, + WRAPPED_SUFFIX } from './helpers'; function getCandidatesForExtension(resolved, extension) { @@ -29,91 +30,134 @@ function getCandidates(resolved, extensions) { ); } -export default function getResolveId(extensions) { - function resolveExtensions(importee, importer) { - // not our problem - if (importee[0] !== '.' || !importer) return undefined; +export function resolveExtensions(importee, importer, extensions) { + // not our problem + if (importee[0] !== '.' || !importer) return undefined; - const resolved = resolve(dirname(importer), importee); - const candidates = getCandidates(resolved, extensions); + const resolved = resolve(dirname(importer), importee); + const candidates = getCandidates(resolved, extensions); - for (let i = 0; i < candidates.length; i += 1) { - try { - const stats = statSync(candidates[i]); - if (stats.isFile()) return { id: candidates[i] }; - } catch (err) { - /* noop */ - } + for (let i = 0; i < candidates.length; i += 1) { + try { + const stats = statSync(candidates[i]); + if (stats.isFile()) return { id: candidates[i] }; + } catch (err) { + /* noop */ } - - return undefined; } - return function resolveId(importee, rawImporter, resolveOptions) { - if (isWrappedId(importee, MODULE_SUFFIX) || isWrappedId(importee, EXPORTS_SUFFIX)) { - return importee; - } - - const importer = - rawImporter && isWrappedId(rawImporter, DYNAMIC_REGISTER_SUFFIX) - ? unwrapId(rawImporter, DYNAMIC_REGISTER_SUFFIX) - : rawImporter; - - // Except for exports, proxies are only importing resolved ids, - // no need to resolve again - if (importer && isWrappedId(importer, PROXY_SUFFIX)) { - return importee; - } + return undefined; +} - const isProxyModule = isWrappedId(importee, PROXY_SUFFIX); - const isRequiredModule = isWrappedId(importee, REQUIRE_SUFFIX); - let isModuleRegistration = false; +export default function getResolveId(extensions) { + const currentlyResolving = new Map(); + + return { + /** + * This is a Maps of importers to Sets of require sources being resolved at + * the moment by resolveRequireSourcesAndUpdateMeta + */ + currentlyResolving, + async resolveId(importee, importer, resolveOptions) { + const customOptions = resolveOptions.custom; + // All logic below is specific to ES imports. + // Also, if we do not skip this logic for requires that are resolved while + // transforming a commonjs file, it can easily lead to deadlocks. + if ( + customOptions && + customOptions['node-resolve'] && + customOptions['node-resolve'].isRequire + ) { + return null; + } + const currentlyResolvingForParent = currentlyResolving.get(importer); + if (currentlyResolvingForParent && currentlyResolvingForParent.has(importee)) { + this.warn({ + code: 'THIS_RESOLVE_WITHOUT_OPTIONS', + message: + 'It appears a plugin has implemented a "resolveId" hook that uses "this.resolve" without forwarding the third "options" parameter of "resolveId". This is problematic as it can lead to wrong module resolutions especially for the node-resolve plugin and in certain cases cause early exit errors for the commonjs plugin.\nIn rare cases, this warning can appear if the same file is both imported and required from the same mixed ES/CommonJS module, in which case it can be ignored.', + url: 'https://rollupjs.org/guide/en/#resolveid' + }); + return null; + } - if (isProxyModule) { - importee = unwrapId(importee, PROXY_SUFFIX); - } else if (isRequiredModule) { - importee = unwrapId(importee, REQUIRE_SUFFIX); + if (isWrappedId(importee, WRAPPED_SUFFIX)) { + return unwrapId(importee, WRAPPED_SUFFIX); + } - isModuleRegistration = isWrappedId(importee, DYNAMIC_REGISTER_SUFFIX); - if (isModuleRegistration) { - importee = unwrapId(importee, DYNAMIC_REGISTER_SUFFIX); + if ( + importee.endsWith(ENTRY_SUFFIX) || + isWrappedId(importee, MODULE_SUFFIX) || + isWrappedId(importee, EXPORTS_SUFFIX) || + isWrappedId(importee, PROXY_SUFFIX) || + isWrappedId(importee, ES_IMPORT_SUFFIX) || + isWrappedId(importee, EXTERNAL_SUFFIX) || + importee.startsWith(HELPERS_ID) || + importee === DYNAMIC_MODULES_ID + ) { + return importee; } - } - if ( - importee.startsWith(HELPERS_ID) || - importee === DYNAMIC_PACKAGES_ID || - importee.startsWith(DYNAMIC_JSON_PREFIX) - ) { - return importee; - } + if (importer) { + if ( + importer === DYNAMIC_MODULES_ID || + // Proxies are only importing resolved ids, no need to resolve again + isWrappedId(importer, PROXY_SUFFIX) || + isWrappedId(importer, ES_IMPORT_SUFFIX) || + importer.endsWith(ENTRY_SUFFIX) + ) { + return importee; + } + if (isWrappedId(importer, EXTERNAL_SUFFIX)) { + // We need to return null for unresolved imports so that the proper warning is shown + if ( + !(await this.resolve( + importee, + importer, + Object.assign({ skipSelf: true }, resolveOptions) + )) + ) { + return null; + } + // For other external imports, we need to make sure they are handled as external + return { id: importee, external: true }; + } + } - if (importee.startsWith('\0')) { - return null; - } + if (importee.startsWith('\0')) { + return null; + } - return this.resolve( - importee, - importer, - Object.assign({}, resolveOptions, { - skipSelf: true, - custom: Object.assign({}, resolveOptions.custom, { - 'node-resolve': { isRequire: isProxyModule || isRequiredModule } - }) - }) - ).then((resolved) => { - if (!resolved) { - resolved = resolveExtensions(importee, importer); + // If this is an entry point or ESM import, we need to figure out if the importee is wrapped and + // if that is the case, we need to add a proxy. + const resolved = + (await this.resolve( + importee, + importer, + Object.assign({ skipSelf: true }, resolveOptions) + )) || resolveExtensions(importee, importer, extensions); + // Make sure that even if other plugins resolve again, we ignore our own proxies + if ( + !resolved || + resolved.external || + resolved.id.endsWith(ENTRY_SUFFIX) || + isWrappedId(resolved.id, ES_IMPORT_SUFFIX) + ) { + return resolved; } - if (resolved && isProxyModule) { - resolved.id = wrapId(resolved.id, resolved.external ? EXTERNAL_SUFFIX : PROXY_SUFFIX); - resolved.external = false; - } else if (resolved && isModuleRegistration) { - resolved.id = wrapId(resolved.id, DYNAMIC_REGISTER_SUFFIX); - } else if (!resolved && (isProxyModule || isRequiredModule)) { - return { id: wrapId(importee, EXTERNAL_SUFFIX), external: false }; + const moduleInfo = await this.load(resolved); + if (resolveOptions.isEntry) { + moduleInfo.moduleSideEffects = true; + // We must not precede entry proxies with a `\0` as that will mess up relative external resolution + return resolved.id + ENTRY_SUFFIX; + } + const { + meta: { commonjs: commonjsMeta } + } = moduleInfo; + if (commonjsMeta && commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS) { + return { id: wrapId(resolved.id, ES_IMPORT_SUFFIX), meta: { commonjs: { resolved } } }; } return resolved; - }); + } }; } diff --git a/packages/commonjs/src/resolve-require-sources.js b/packages/commonjs/src/resolve-require-sources.js new file mode 100644 index 000000000..d392a0755 --- /dev/null +++ b/packages/commonjs/src/resolve-require-sources.js @@ -0,0 +1,214 @@ +import { + ES_IMPORT_SUFFIX, + EXTERNAL_SUFFIX, + IS_WRAPPED_COMMONJS, + isWrappedId, + PROXY_SUFFIX, + wrapId, + WRAPPED_SUFFIX +} from './helpers'; +import { resolveExtensions } from './resolve-id'; + +export function getRequireResolver(extensions, detectCyclesAndConditional, currentlyResolving) { + const knownCjsModuleTypes = Object.create(null); + const requiredIds = Object.create(null); + const unconditionallyRequiredIds = Object.create(null); + const dependencies = Object.create(null); + const getDependencies = (id) => dependencies[id] || (dependencies[id] = new Set()); + + const isCyclic = (id) => { + const dependenciesToCheck = new Set(getDependencies(id)); + for (const dependency of dependenciesToCheck) { + if (dependency === id) { + return true; + } + for (const childDependency of getDependencies(dependency)) { + dependenciesToCheck.add(childDependency); + } + } + return false; + }; + + // Once a module is listed here, its type (wrapped or not) is fixed and may + // not change for the rest of the current build, to not break already + // transformed modules. + const fullyAnalyzedModules = Object.create(null); + + const getTypeForFullyAnalyzedModule = (id) => { + const knownType = knownCjsModuleTypes[id]; + if (knownType !== true || !detectCyclesAndConditional || fullyAnalyzedModules[id]) { + return knownType; + } + if (isCyclic(id)) { + return (knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS); + } + return knownType; + }; + + const setInitialParentType = (id, initialCommonJSType) => { + // Fully analyzed modules may never change type + if (fullyAnalyzedModules[id]) { + return; + } + knownCjsModuleTypes[id] = initialCommonJSType; + if ( + detectCyclesAndConditional && + knownCjsModuleTypes[id] === true && + requiredIds[id] && + !unconditionallyRequiredIds[id] + ) { + knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS; + } + }; + + const analyzeRequiredModule = async (parentId, resolved, isConditional, loadModule) => { + const childId = resolved.id; + requiredIds[childId] = true; + if (!(isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)) { + unconditionallyRequiredIds[childId] = true; + } + + getDependencies(parentId).add(childId); + if (!isCyclic(childId)) { + // This makes sure the current transform handler waits for all direct + // dependencies to be loaded and transformed and therefore for all + // transitive CommonJS dependencies to be loaded as well so that all + // cycles have been found and knownCjsModuleTypes is reliable. + await loadModule(resolved); + } + }; + + const getTypeForImportedModule = async (resolved, loadModule) => { + if (resolved.id in knownCjsModuleTypes) { + // This handles cyclic ES dependencies + return knownCjsModuleTypes[resolved.id]; + } + const { + meta: { commonjs } + } = await loadModule(resolved); + return (commonjs && commonjs.isCommonJS) || false; + }; + + return { + getWrappedIds: () => + Object.keys(knownCjsModuleTypes).filter( + (id) => knownCjsModuleTypes[id] === IS_WRAPPED_COMMONJS + ), + isRequiredId: (id) => requiredIds[id], + async shouldTransformCachedModule({ + id: parentId, + resolvedSources, + meta: { commonjs: parentMeta } + }) { + // We explicitly track ES modules to handle circular imports + if (!(parentMeta && parentMeta.isCommonJS)) knownCjsModuleTypes[parentId] = false; + if (isWrappedId(parentId, ES_IMPORT_SUFFIX)) return false; + const parentRequires = parentMeta && parentMeta.requires; + if (parentRequires) { + setInitialParentType(parentId, parentMeta.initialCommonJSType); + await Promise.all( + parentRequires.map(({ resolved, isConditional }) => + analyzeRequiredModule(parentId, resolved, isConditional, this.load) + ) + ); + if (getTypeForFullyAnalyzedModule(parentId) !== parentMeta.isCommonJS) { + return true; + } + for (const { + resolved: { id } + } of parentRequires) { + if (getTypeForFullyAnalyzedModule(id) !== parentMeta.isRequiredCommonJS[id]) { + return true; + } + } + // Now that we decided to go with the cached copy, neither the parent + // module nor any of its children may change types anymore + fullyAnalyzedModules[parentId] = true; + for (const { + resolved: { id } + } of parentRequires) { + fullyAnalyzedModules[id] = true; + } + } + const parentRequireSet = new Set((parentRequires || []).map(({ resolved: { id } }) => id)); + return ( + await Promise.all( + Object.keys(resolvedSources) + .map((source) => resolvedSources[source]) + .filter(({ id, external }) => !(external || parentRequireSet.has(id))) + .map(async (resolved) => { + if (isWrappedId(resolved.id, ES_IMPORT_SUFFIX)) { + return ( + (await getTypeForImportedModule( + (await this.load({ id: resolved.id })).meta.commonjs.resolved, + this.load + )) !== IS_WRAPPED_COMMONJS + ); + } + return (await getTypeForImportedModule(resolved, this.load)) === IS_WRAPPED_COMMONJS; + }) + ) + ).some((shouldTransform) => shouldTransform); + }, + /* eslint-disable no-param-reassign */ + resolveRequireSourcesAndUpdateMeta: (rollupContext) => async ( + parentId, + isParentCommonJS, + parentMeta, + sources + ) => { + parentMeta.initialCommonJSType = isParentCommonJS; + parentMeta.requires = []; + parentMeta.isRequiredCommonJS = Object.create(null); + setInitialParentType(parentId, isParentCommonJS); + const currentlyResolvingForParent = currentlyResolving.get(parentId) || new Set(); + currentlyResolving.set(parentId, currentlyResolvingForParent); + const requireTargets = await Promise.all( + sources.map(async ({ source, isConditional }) => { + // Never analyze or proxy internal modules + if (source.startsWith('\0')) { + return { id: source, allowProxy: false }; + } + currentlyResolvingForParent.add(source); + const resolved = + (await rollupContext.resolve(source, parentId, { + custom: { 'node-resolve': { isRequire: true } } + })) || resolveExtensions(source, parentId, extensions); + currentlyResolvingForParent.delete(source); + if (!resolved) { + return { id: wrapId(source, EXTERNAL_SUFFIX), allowProxy: false }; + } + const childId = resolved.id; + if (resolved.external) { + return { id: wrapId(childId, EXTERNAL_SUFFIX), allowProxy: false }; + } + parentMeta.requires.push({ resolved, isConditional }); + await analyzeRequiredModule(parentId, resolved, isConditional, rollupContext.load); + return { id: childId, allowProxy: true }; + }) + ); + parentMeta.isCommonJS = getTypeForFullyAnalyzedModule(parentId); + fullyAnalyzedModules[parentId] = true; + return requireTargets.map(({ id: dependencyId, allowProxy }, index) => { + // eslint-disable-next-line no-multi-assign + const isCommonJS = (parentMeta.isRequiredCommonJS[ + dependencyId + ] = getTypeForFullyAnalyzedModule(dependencyId)); + fullyAnalyzedModules[dependencyId] = true; + return { + source: sources[index].source, + id: allowProxy + ? isCommonJS === IS_WRAPPED_COMMONJS + ? wrapId(dependencyId, WRAPPED_SUFFIX) + : wrapId(dependencyId, PROXY_SUFFIX) + : dependencyId, + isCommonJS + }; + }); + }, + isCurrentlyResolving(source, parentId) { + const currentlyResolvingForParent = currentlyResolving.get(parentId); + return currentlyResolvingForParent && currentlyResolvingForParent.has(source); + } + }; +} diff --git a/packages/commonjs/src/rollup-version.js b/packages/commonjs/src/rollup-version.js index 3c9136cc6..c16b2a106 100644 --- a/packages/commonjs/src/rollup-version.js +++ b/packages/commonjs/src/rollup-version.js @@ -1,20 +1,30 @@ -export default function validateRollupVersion(rollupVersion, peerDependencyVersion) { - const [major, minor] = rollupVersion.split('.').map(Number); - const versionRegexp = /\^(\d+\.\d+)\.\d+/g; +export default function validateVersion(actualVersion, peerDependencyVersion, name) { + const versionRegexp = /\^(\d+\.\d+\.\d+)/g; let minMajor = Infinity; let minMinor = Infinity; + let minPatch = Infinity; let foundVersion; // eslint-disable-next-line no-cond-assign while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) { - const [foundMajor, foundMinor] = foundVersion[1].split('.').map(Number); + const [foundMajor, foundMinor, foundPatch] = foundVersion[1].split('.').map(Number); if (foundMajor < minMajor) { minMajor = foundMajor; minMinor = foundMinor; + minPatch = foundPatch; } } - if (major < minMajor || (major === minMajor && minor < minMinor)) { + if (!actualVersion) { throw new Error( - `Insufficient Rollup version: "@rollup/plugin-commonjs" requires at least rollup@${minMajor}.${minMinor} but found rollup@${rollupVersion}.` + `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch}.` + ); + } + const [major, minor, patch] = actualVersion.split('.').map(Number); + if ( + major < minMajor || + (major === minMajor && (minor < minMinor || (minor === minMinor && patch < minPatch))) + ) { + throw new Error( + `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch} but found ${name}@${actualVersion}.` ); } } diff --git a/packages/commonjs/src/transform-commonjs.js b/packages/commonjs/src/transform-commonjs.js index a86041c63..45507aa23 100644 --- a/packages/commonjs/src/transform-commonjs.js +++ b/packages/commonjs/src/transform-commonjs.js @@ -8,40 +8,34 @@ import MagicString from 'magic-string'; import { getKeypath, - isDefineCompiledEsm, hasDefineEsmProperty, + isDefineCompiledEsm, isFalsy, isReference, isShorthandProperty, isTruthy, KEY_COMPILED_ESM } from './ast-utils'; +import { COMMONJS_REQUIRE_EXPORT, CREATE_COMMONJS_REQUIRE_EXPORT } from './dynamic-modules'; import { rewriteExportsAndGetExportsBlock, wrapCode } from './generate-exports'; import { getRequireHandlers, getRequireStringArg, - hasDynamicModuleForPath, - isIgnoredRequireStatement, + hasDynamicArguments, isModuleRequire, isNodeRequirePropertyAccess, - isRequireStatement, - isStaticRequireStatement + isRequire, + isRequireExpression } from './generate-imports'; -import { - DYNAMIC_JSON_PREFIX, - DYNAMIC_REGISTER_SUFFIX, - isWrappedId, - unwrapId, - wrapId -} from './helpers'; +import { IS_WRAPPED_COMMONJS } from './helpers'; import { tryParse } from './parse'; -import { deconflict, getName, getVirtualPathForDynamicRequirePath } from './utils'; +import { capitalize, deconflict, getName, getVirtualPathForDynamicRequirePath } from './utils'; const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/; const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/; -export default function transformCommonjs( +export default async function transformCommonjs( parse, code, id, @@ -52,11 +46,15 @@ export default function transformCommonjs( getIgnoreTryCatchRequireStatementMode, sourceMap, isDynamicRequireModulesEnabled, - dynamicRequireModuleSet, - disableWrap, + dynamicRequireModules, commonDir, astCache, - defaultIsModuleExports + defaultIsModuleExports, + needsRequireWrapper, + resolveRequireSourcesAndUpdateMeta, + isRequired, + checkDynamicRequire, + commonjsMeta ) { const ast = astCache || tryParse(parse, code, id); const magicString = new MagicString(code); @@ -66,7 +64,6 @@ export default function transformCommonjs( global: false, require: false }; - let usesDynamicRequire = false; const virtualDynamicRequirePath = isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(dirname(id), commonDir); let scope = attachScopes(ast, 'scope'); @@ -74,26 +71,21 @@ export default function transformCommonjs( let programDepth = 0; let currentTryBlockEnd = null; let shouldWrap = false; + let reexports = false; const globals = new Set(); - - // TODO technically wrong since globals isn't populated yet, but ¯\_(ツ)_/¯ - const HELPERS_NAME = deconflict([scope], globals, 'commonjsHelpers'); - const dynamicRegisterSources = new Set(); - let hasRemovedRequire = false; - - const { - addRequireStatement, - requiredSources, - rewriteRequireExpressionsAndGetImportBlock - } = getRequireHandlers(); + // A conditionalNode is a node for which execution is not guaranteed. If such a node is a require + // or contains nested requires, those should be handled as function calls unless there is an + // unconditional require elsewhere. + let currentConditionalNodeEnd = null; + const conditionalNodes = new Set(); + const { addRequireExpression, rewriteRequireExpressionsAndGetImportBlock } = getRequireHandlers(); // See which names are assigned to. This is necessary to prevent // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`, // where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh) const reassignedNames = new Set(); const topLevelDeclarations = []; - const topLevelRequireDeclarators = new Set(); const skippedNodes = new Set(); const moduleAccessScopes = new Set([scope]); const exportsAccessScopes = new Set([scope]); @@ -102,6 +94,9 @@ export default function transformCommonjs( const exportsAssignmentsByName = new Map(); const topLevelAssignments = new Set(); const topLevelDefineCompiledEsmExpressions = []; + const replacedGlobal = []; + const replacedDynamicRequires = []; + const importedVariables = new Set(); walk(ast, { enter(node, parent) { @@ -113,6 +108,12 @@ export default function transformCommonjs( if (currentTryBlockEnd !== null && node.start > currentTryBlockEnd) { currentTryBlockEnd = null; } + if (currentConditionalNodeEnd !== null && node.start > currentConditionalNodeEnd) { + currentConditionalNodeEnd = null; + } + if (currentConditionalNodeEnd === null && conditionalNodes.has(node)) { + currentConditionalNodeEnd = node.end; + } programDepth += 1; if (node.scope) ({ scope } = node); @@ -124,11 +125,6 @@ export default function transformCommonjs( // eslint-disable-next-line default-case switch (node.type) { - case 'TryStatement': - if (currentTryBlockEnd === null) { - currentTryBlockEnd = node.block.end; - } - return; case 'AssignmentExpression': if (node.left.type === 'MemberExpression') { const flattened = getKeypath(node.left); @@ -156,8 +152,9 @@ export default function transformCommonjs( if (hasDefineEsmProperty(node.right)) { shouldWrap = true; } - } else if (defaultIsModuleExports === false) { + } else if (isRequireExpression(node.right, scope)) { shouldWrap = true; + reexports = true; } } } else if (exportName === KEY_COMPILED_ESM) { @@ -199,110 +196,66 @@ export default function transformCommonjs( return; } + // Transform require.resolve if ( + isDynamicRequireModulesEnabled && node.callee.object && - node.callee.object.name === 'require' && - node.callee.property.name === 'resolve' && - hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet) + isRequire(node.callee.object, scope) && + node.callee.property.name === 'resolve' ) { + checkDynamicRequire(node.start); + uses.require = true; const requireNode = node.callee.object; - magicString.appendLeft( - node.end - 1, - `,${JSON.stringify( - dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath - )}` - ); - magicString.overwrite( - requireNode.start, - requireNode.end, - `${HELPERS_NAME}.commonjsRequire`, - { - storeName: true - } - ); + replacedDynamicRequires.push(requireNode); return; } - if (!isStaticRequireStatement(node, scope)) return; - if (!isDynamicRequireModulesEnabled) { - skippedNodes.add(node.callee); + if (!isRequireExpression(node, scope)) { + const keypath = getKeypath(node.callee); + if (keypath && importedVariables.has(keypath.name)) { + // Heuristic to deoptimize requires after a required function has been called + currentConditionalNodeEnd = Infinity; + } + return; } - if (!isIgnoredRequireStatement(node, ignoreRequire)) { - skippedNodes.add(node.callee); - const usesReturnValue = parent.type !== 'ExpressionStatement'; - let canConvertRequire = true; - let shouldRemoveRequireStatement = false; + skippedNodes.add(node.callee); + uses.require = true; - if (currentTryBlockEnd !== null) { - ({ - canConvertRequire, - shouldRemoveRequireStatement - } = getIgnoreTryCatchRequireStatementMode(node.arguments[0].value)); - - if (shouldRemoveRequireStatement) { - hasRemovedRequire = true; - } + if (hasDynamicArguments(node)) { + if (isDynamicRequireModulesEnabled) { + checkDynamicRequire(node.start); } - - let sourceId = getRequireStringArg(node); - const isDynamicRegister = isWrappedId(sourceId, DYNAMIC_REGISTER_SUFFIX); - if (isDynamicRegister) { - sourceId = unwrapId(sourceId, DYNAMIC_REGISTER_SUFFIX); - if (sourceId.endsWith('.json')) { - sourceId = DYNAMIC_JSON_PREFIX + sourceId; - } - dynamicRegisterSources.add(wrapId(sourceId, DYNAMIC_REGISTER_SUFFIX)); - } else { - if ( - !sourceId.endsWith('.json') && - hasDynamicModuleForPath(sourceId, id, dynamicRequireModuleSet) - ) { - if (shouldRemoveRequireStatement) { - magicString.overwrite(node.start, node.end, `undefined`); - } else if (canConvertRequire) { - magicString.overwrite( - node.start, - node.end, - `${HELPERS_NAME}.commonjsRequire(${JSON.stringify( - getVirtualPathForDynamicRequirePath(sourceId, commonDir) - )}, ${JSON.stringify( - dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath - )})` - ); - usesDynamicRequire = true; - } - return; - } - - if (canConvertRequire) { - addRequireStatement(sourceId, node, scope, usesReturnValue); - } + if (!ignoreDynamicRequires) { + replacedDynamicRequires.push(node.callee); } + return; + } - if (usesReturnValue) { - if (shouldRemoveRequireStatement) { - magicString.overwrite(node.start, node.end, `undefined`); - return; - } - - if ( - parent.type === 'VariableDeclarator' && - !scope.parent && - parent.id.type === 'Identifier' - ) { - // This will allow us to reuse this variable name as the imported variable if it is not reassigned - // and does not conflict with variables in other places where this is imported - topLevelRequireDeclarators.add(parent); - } - } else { - // This is a bare import, e.g. `require('foo');` - - if (!canConvertRequire && !shouldRemoveRequireStatement) { - return; + const requireStringArg = getRequireStringArg(node); + if (!ignoreRequire(requireStringArg)) { + const usesReturnValue = parent.type !== 'ExpressionStatement'; + const toBeRemoved = + parent.type === 'ExpressionStatement' && + (!currentConditionalNodeEnd || + // We should completely remove requires directly in a try-catch + // so that Rollup can remove up the try-catch + (currentTryBlockEnd !== null && currentTryBlockEnd < currentConditionalNodeEnd)) + ? parent + : node; + addRequireExpression( + requireStringArg, + node, + scope, + usesReturnValue, + currentTryBlockEnd !== null, + currentConditionalNodeEnd !== null, + toBeRemoved + ); + if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') { + for (const name of extractAssignedNames(parent.id)) { + importedVariables.add(name); } - - magicString.remove(parent.start, parent.end); } } return; @@ -312,45 +265,43 @@ export default function transformCommonjs( // skip dead branches if (isFalsy(node.test)) { skippedNodes.add(node.consequent); - } else if (node.alternate && isTruthy(node.test)) { - skippedNodes.add(node.alternate); + } else if (isTruthy(node.test)) { + if (node.alternate) { + skippedNodes.add(node.alternate); + } + } else { + conditionalNodes.add(node.consequent); + if (node.alternate) { + conditionalNodes.add(node.alternate); + } + } + return; + case 'ArrowFunctionExpression': + case 'FunctionDeclaration': + case 'FunctionExpression': + // requires in functions should be conditional unless it is an IIFE + if ( + currentConditionalNodeEnd === null && + !(parent.type === 'CallExpression' && parent.callee === node) + ) { + currentConditionalNodeEnd = node.end; } return; case 'Identifier': { const { name } = node; - if (!(isReference(node, parent) && !scope.contains(name))) return; + if (!isReference(node, parent) || scope.contains(name)) return; switch (name) { case 'require': + uses.require = true; if (isNodeRequirePropertyAccess(parent)) { - if (hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet)) { - if (parent.property.name === 'cache') { - magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, { - storeName: true - }); - } - } - return; } - - if (isDynamicRequireModulesEnabled && isRequireStatement(parent, scope)) { - magicString.appendLeft( - parent.end - 1, - `,${JSON.stringify( - dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath - )}` - ); - } if (!ignoreDynamicRequires) { if (isShorthandProperty(parent)) { - magicString.appendRight(node.end, `: ${HELPERS_NAME}.commonjsRequire`); - } else { - magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, { - storeName: true - }); + magicString.prependRight(node.start, 'require: '); } + replacedDynamicRequires.push(node); } - usesDynamicRequire = true; return; case 'module': case 'exports': @@ -360,9 +311,7 @@ export default function transformCommonjs( case 'global': uses.global = true; if (!ignoreGlobal) { - magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, { - storeName: true - }); + replacedGlobal.push(node); } return; case 'define': @@ -375,11 +324,26 @@ export default function transformCommonjs( return; } } + case 'LogicalExpression': + // skip dead branches + if (node.operator === '&&') { + if (isFalsy(node.left)) { + skippedNodes.add(node.right); + } else if (!isTruthy(node.left)) { + conditionalNodes.add(node.right); + } + } else if (node.operator === '||') { + if (isTruthy(node.left)) { + skippedNodes.add(node.right); + } else if (!isFalsy(node.left)) { + conditionalNodes.add(node.right); + } + } + return; case 'MemberExpression': if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) { - magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, { - storeName: true - }); + uses.require = true; + replacedDynamicRequires.push(node); skippedNodes.add(node.object); skippedNodes.add(node.property); } @@ -395,12 +359,18 @@ export default function transformCommonjs( if (lexicalDepth === 0) { uses.global = true; if (!ignoreGlobal) { - magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, { - storeName: true - }); + replacedGlobal.push(node); } } return; + case 'TryStatement': + if (currentTryBlockEnd === null) { + currentTryBlockEnd = node.block.end; + } + if (currentConditionalNodeEnd === null) { + currentConditionalNodeEnd = node.end; + } + return; case 'UnaryExpression': // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151) if (node.operator === 'typeof') { @@ -410,9 +380,10 @@ export default function transformCommonjs( if (scope.contains(flattened.name)) return; if ( - flattened.keypath === 'module.exports' || - flattened.keypath === 'module' || - flattened.keypath === 'exports' + !isEsModule && + (flattened.keypath === 'module.exports' || + flattened.keypath === 'module' || + flattened.keypath === 'exports') ) { magicString.overwrite(node.start, node.end, `'object'`, { storeName: false @@ -437,29 +408,56 @@ export default function transformCommonjs( const nameBase = getName(id); const exportsName = deconflict([...exportsAccessScopes], globals, nameBase); const moduleName = deconflict([...moduleAccessScopes], globals, `${nameBase}Module`); + const requireName = deconflict([scope], globals, `require${capitalize(nameBase)}`); + const isRequiredName = deconflict([scope], globals, `hasRequired${capitalize(nameBase)}`); + const helpersName = deconflict([scope], globals, 'commonjsHelpers'); + const dynamicRequireName = + replacedDynamicRequires.length > 0 && + deconflict( + [scope], + globals, + isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT + ); const deconflictedExportNames = Object.create(null); for (const [exportName, { scopes }] of exportsAssignmentsByName) { deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName); } + for (const node of replacedGlobal) { + magicString.overwrite(node.start, node.end, `${helpersName}.commonjsGlobal`, { + storeName: true + }); + } + for (const node of replacedDynamicRequires) { + magicString.overwrite( + node.start, + node.end, + isDynamicRequireModulesEnabled + ? `${dynamicRequireName}(${JSON.stringify(virtualDynamicRequirePath)})` + : dynamicRequireName, + { + contentOnly: true, + storeName: true + } + ); + } + // We cannot wrap ES/mixed modules - shouldWrap = - !isEsModule && - !disableWrap && - (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0)); + shouldWrap = !isEsModule && (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0)); const detectWrappedDefault = shouldWrap && - (topLevelDefineCompiledEsmExpressions.length > 0 || code.indexOf('__esModule') >= 0); + (reexports || + topLevelDefineCompiledEsmExpressions.length > 0 || + code.indexOf('__esModule') >= 0); if ( !( - requiredSources.length || - dynamicRegisterSources.size || + shouldWrap || + isRequired || + needsRequireWrapper || uses.module || uses.exports || uses.require || - usesDynamicRequire || - hasRemovedRequire || topLevelDefineCompiledEsmExpressions.length > 0 ) && (ignoreGlobal || !uses.global) @@ -474,7 +472,9 @@ export default function transformCommonjs( magicString.remove(0, commentEnd).trim(); } - const exportMode = shouldWrap + const exportMode = isEsModule + ? 'none' + : shouldWrap ? uses.module ? 'module' : 'exports' @@ -486,19 +486,24 @@ export default function transformCommonjs( ? 'exports' : 'module'; - const importBlock = rewriteRequireExpressionsAndGetImportBlock( + const importBlock = await rewriteRequireExpressionsAndGetImportBlock( magicString, topLevelDeclarations, - topLevelRequireDeclarators, reassignedNames, - HELPERS_NAME, - dynamicRegisterSources, + helpersName, + dynamicRequireName, moduleName, exportsName, id, - exportMode + exportMode, + resolveRequireSourcesAndUpdateMeta, + needsRequireWrapper, + isEsModule, + isDynamicRequireModulesEnabled, + getIgnoreTryCatchRequireStatementMode, + commonjsMeta ); - + const usesRequireWrapper = commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS; const exportBlock = isEsModule ? '' : rewriteExportsAndGetExportsBlock( @@ -513,16 +518,35 @@ export default function transformCommonjs( topLevelDefineCompiledEsmExpressions, deconflictedExportNames, code, - HELPERS_NAME, + helpersName, exportMode, detectWrappedDefault, - defaultIsModuleExports + defaultIsModuleExports, + usesRequireWrapper, + requireName ); if (shouldWrap) { wrapCode(magicString, uses, moduleName, exportsName); } + if (usesRequireWrapper) { + magicString.trim().indent('\t'); + magicString.prepend( + `var ${isRequiredName}; + +function ${requireName} () { +\tif (${isRequiredName}) return ${exportsName}; +\t${isRequiredName} = 1; +` + ).append(` +\treturn ${exportsName}; +}`); + if (exportMode === 'replace') { + magicString.prepend(`var ${exportsName};\n`); + } + } + magicString .trim() .prepend(leadingComment + importBlock) @@ -531,7 +555,7 @@ export default function transformCommonjs( return { code: magicString.toString(), map: sourceMap ? magicString.generateMap() : null, - syntheticNamedExports: isEsModule ? false : '__moduleExports', - meta: { commonjs: { isCommonJS: !isEsModule } } + syntheticNamedExports: isEsModule || usesRequireWrapper ? false : '__moduleExports', + meta: { commonjs: commonjsMeta } }; } diff --git a/packages/commonjs/src/utils.js b/packages/commonjs/src/utils.js index e226a28fb..92866c706 100644 --- a/packages/commonjs/src/utils.js +++ b/packages/commonjs/src/utils.js @@ -1,8 +1,8 @@ /* eslint-disable import/prefer-default-export */ -import { basename, dirname, extname } from 'path'; +import { basename, dirname, extname, relative } from 'path'; -import { makeLegalIdentifier } from '@rollup/pluginutils'; +import { createFilter, makeLegalIdentifier } from '@rollup/pluginutils'; export function deconflict(scopes, globals, identifier) { let i = 1; @@ -34,10 +34,32 @@ export function normalizePathSlashes(path) { return path.replace(/\\/g, '/'); } -const VIRTUAL_PATH_BASE = '/$$rollup_base$$'; -export const getVirtualPathForDynamicRequirePath = (path, commonDir) => { - const normalizedPath = normalizePathSlashes(path); - return normalizedPath.startsWith(commonDir) - ? VIRTUAL_PATH_BASE + normalizedPath.slice(commonDir.length) - : normalizedPath; -}; +export const getVirtualPathForDynamicRequirePath = (path, commonDir) => + `/${normalizePathSlashes(relative(commonDir, path))}`; + +export function capitalize(name) { + return name[0].toUpperCase() + name.slice(1); +} + +export function getStrictRequiresFilter({ strictRequires }) { + switch (strictRequires) { + case true: + return { strictRequiresFilter: () => true, detectCyclesAndConditional: false }; + // eslint-disable-next-line no-undefined + case undefined: + case 'auto': + case 'debug': + case null: + return { strictRequiresFilter: () => false, detectCyclesAndConditional: true }; + case false: + return { strictRequiresFilter: () => false, detectCyclesAndConditional: false }; + default: + if (typeof strictRequires === 'string' || Array.isArray(strictRequires)) { + return { + strictRequiresFilter: createFilter(strictRequires), + detectCyclesAndConditional: false + }; + } + throw new Error('Unexpected value for "strictRequires" option.'); + } +} diff --git a/packages/commonjs/test/fixtures/form/constant-template-literal/output.js b/packages/commonjs/test/fixtures/form/constant-template-literal/output.js index ec6ef23c9..ed766a8a3 100644 --- a/packages/commonjs/test/fixtures/form/constant-template-literal/output.js +++ b/packages/commonjs/test/fixtures/form/constant-template-literal/output.js @@ -1,10 +1,8 @@ import * as commonjsHelpers from "_commonjsHelpers.js"; import { __exports as input } from "\u0000fixtures/form/constant-template-literal/input.js?commonjs-exports" -import "\u0000tape?commonjs-require"; -import require$$0 from "\u0000tape?commonjs-proxy"; +import require$$0 from "\u0000CWD/fixtures/form/constant-template-literal/tape.js?commonjs-proxy"; var foo = require$$0; console.log(foo); -export default input; -export { input as __moduleExports }; +export { input as __moduleExports, input as default }; diff --git a/packages/commonjs/test/fixtures/form/defaultIsModuleExports-auto-no-__esModule/output.js b/packages/commonjs/test/fixtures/form/defaultIsModuleExports-auto-no-__esModule/output.js index a180c0faa..24b6fab18 100755 --- a/packages/commonjs/test/fixtures/form/defaultIsModuleExports-auto-no-__esModule/output.js +++ b/packages/commonjs/test/fixtures/form/defaultIsModuleExports-auto-no-__esModule/output.js @@ -4,5 +4,4 @@ import { __exports as input } from "\u0000fixtures/form/defaultIsModuleExports-a var _default = input.default = 2; var named = input.named = 3; -export default input; -export { input as __moduleExports, named }; +export { input as __moduleExports, named, input as default }; diff --git a/packages/commonjs/test/fixtures/form/defaultIsModuleExports-auto-reassign-exports-__esModule/output.js b/packages/commonjs/test/fixtures/form/defaultIsModuleExports-auto-reassign-exports-__esModule/output.js index 54f0fd3f5..5d2e8817a 100644 --- a/packages/commonjs/test/fixtures/form/defaultIsModuleExports-auto-reassign-exports-__esModule/output.js +++ b/packages/commonjs/test/fixtures/form/defaultIsModuleExports-auto-reassign-exports-__esModule/output.js @@ -2,8 +2,8 @@ import * as commonjsHelpers from "_commonjsHelpers.js"; import { __module as inputModule, exports as input } from "\u0000fixtures/form/defaultIsModuleExports-auto-reassign-exports-__esModule/input.js?commonjs-module" (function (module) { -module.exports = { __esModule: true, default: { foo: 'bar' }} -}(inputModule)); + module.exports = { __esModule: true, default: { foo: 'bar' }} +} (inputModule)); export default /*@__PURE__*/commonjsHelpers.getDefaultExportFromCjs(input); export { input as __moduleExports }; diff --git a/packages/commonjs/test/fixtures/form/defaultIsModuleExports-auto-reassign-exports-no-__esModule/output.js b/packages/commonjs/test/fixtures/form/defaultIsModuleExports-auto-reassign-exports-no-__esModule/output.js index ac266b81e..a0c3ed4d7 100644 --- a/packages/commonjs/test/fixtures/form/defaultIsModuleExports-auto-reassign-exports-no-__esModule/output.js +++ b/packages/commonjs/test/fixtures/form/defaultIsModuleExports-auto-reassign-exports-no-__esModule/output.js @@ -3,4 +3,4 @@ import * as commonjsHelpers from "_commonjsHelpers.js"; var input = { default: { foo: 'bar' }} export default input; -export { input as __moduleExports }; \ No newline at end of file +export { input as __moduleExports }; diff --git a/packages/commonjs/test/fixtures/form/defaultIsModuleExports-false-no-__esModule/output.js b/packages/commonjs/test/fixtures/form/defaultIsModuleExports-false-no-__esModule/output.js index 59c3241c0..c0cde8ae9 100755 --- a/packages/commonjs/test/fixtures/form/defaultIsModuleExports-false-no-__esModule/output.js +++ b/packages/commonjs/test/fixtures/form/defaultIsModuleExports-false-no-__esModule/output.js @@ -4,5 +4,4 @@ import { __exports as input } from "\u0000fixtures/form/defaultIsModuleExports-f var _default = input.default = 2; var named = input.named = 3; -export default input; -export { input as __moduleExports, named }; +export { input as __moduleExports, named, input as default }; diff --git a/packages/commonjs/test/fixtures/form/defaultIsModuleExports-false-no-default/output.js b/packages/commonjs/test/fixtures/form/defaultIsModuleExports-false-no-default/output.js index 7376b2e0f..fd8c2d238 100755 --- a/packages/commonjs/test/fixtures/form/defaultIsModuleExports-false-no-default/output.js +++ b/packages/commonjs/test/fixtures/form/defaultIsModuleExports-false-no-default/output.js @@ -3,5 +3,4 @@ import { __exports as input } from "\u0000fixtures/form/defaultIsModuleExports-f var named = input.named = 3; -export default input; -export { input as __moduleExports, named }; +export { input as __moduleExports, named, input as default }; diff --git a/packages/commonjs/test/fixtures/form/defaultIsModuleExports-false-reassign-exports-__esModule/output.js b/packages/commonjs/test/fixtures/form/defaultIsModuleExports-false-reassign-exports-__esModule/output.js index 3d98b2c44..06b76067d 100644 --- a/packages/commonjs/test/fixtures/form/defaultIsModuleExports-false-reassign-exports-__esModule/output.js +++ b/packages/commonjs/test/fixtures/form/defaultIsModuleExports-false-reassign-exports-__esModule/output.js @@ -2,8 +2,8 @@ import * as commonjsHelpers from "_commonjsHelpers.js"; import { __module as inputModule, exports as input } from "\u0000fixtures/form/defaultIsModuleExports-false-reassign-exports-__esModule/input.js?commonjs-module" (function (module) { -module.exports = { __esModule: true, default: { foo: 'bar' }}; -}(inputModule)); + module.exports = { __esModule: true, default: { foo: 'bar' }}; +} (inputModule)); export default input.default; export { input as __moduleExports }; diff --git a/packages/commonjs/test/fixtures/form/defaultIsModuleExports-false-reassign-exports-no-__esModule/output.js b/packages/commonjs/test/fixtures/form/defaultIsModuleExports-false-reassign-exports-no-__esModule/output.js index 2c8183e6e..448a18947 100644 --- a/packages/commonjs/test/fixtures/form/defaultIsModuleExports-false-reassign-exports-no-__esModule/output.js +++ b/packages/commonjs/test/fixtures/form/defaultIsModuleExports-false-reassign-exports-no-__esModule/output.js @@ -2,8 +2,8 @@ import * as commonjsHelpers from "_commonjsHelpers.js"; import { __module as inputModule, exports as input } from "\u0000fixtures/form/defaultIsModuleExports-false-reassign-exports-no-__esModule/input.js?commonjs-module" (function (module) { -module.exports = { default: { foo: 'bar' }}; -}(inputModule)); + module.exports = { default: { foo: 'bar' }}; +} (inputModule)); export default input.default; export { input as __moduleExports }; diff --git a/packages/commonjs/test/fixtures/form/defaultIsModuleExports-true-__esModule/output.js b/packages/commonjs/test/fixtures/form/defaultIsModuleExports-true-__esModule/output.js index 481eb01bc..48a71f980 100755 --- a/packages/commonjs/test/fixtures/form/defaultIsModuleExports-true-__esModule/output.js +++ b/packages/commonjs/test/fixtures/form/defaultIsModuleExports-true-__esModule/output.js @@ -5,5 +5,4 @@ input.__esModule = true; var _default = input.default = 2; var named = input.named = 3; -export default input; -export { input as __moduleExports, named }; +export { input as __moduleExports, named, input as default }; diff --git a/packages/commonjs/test/fixtures/form/defaultIsModuleExports-true-no-__esModule/output.js b/packages/commonjs/test/fixtures/form/defaultIsModuleExports-true-no-__esModule/output.js index 1dcb6d233..512b2330e 100755 --- a/packages/commonjs/test/fixtures/form/defaultIsModuleExports-true-no-__esModule/output.js +++ b/packages/commonjs/test/fixtures/form/defaultIsModuleExports-true-no-__esModule/output.js @@ -4,5 +4,4 @@ import { __exports as input } from "\u0000fixtures/form/defaultIsModuleExports-t var _default = input.default = 2; var named = input.named = 3; -export default input; -export { input as __moduleExports, named }; +export { input as __moduleExports, named, input as default }; diff --git a/packages/commonjs/test/fixtures/form/dynamic-template-literal/input.js b/packages/commonjs/test/fixtures/form/dynamic-template-literal/input.js deleted file mode 100644 index 12767b60b..000000000 --- a/packages/commonjs/test/fixtures/form/dynamic-template-literal/input.js +++ /dev/null @@ -1,3 +0,0 @@ -var pe = 'pe'; -var foo = require(`ta${pe}`); -console.log(foo); diff --git a/packages/commonjs/test/fixtures/form/dynamic-template-literal/output.js b/packages/commonjs/test/fixtures/form/dynamic-template-literal/output.js deleted file mode 100644 index dda7d8f08..000000000 --- a/packages/commonjs/test/fixtures/form/dynamic-template-literal/output.js +++ /dev/null @@ -1,9 +0,0 @@ -import * as commonjsHelpers from "_commonjsHelpers.js"; -import { __exports as input } from "\u0000fixtures/form/dynamic-template-literal/input.js?commonjs-exports" - -var pe = 'pe'; -var foo = commonjsHelpers.commonjsRequire(`ta${pe}`); -console.log(foo); - -export default input; -export { input as __moduleExports }; diff --git a/packages/commonjs/test/fixtures/form/ignore-ids-function/output.js b/packages/commonjs/test/fixtures/form/ignore-ids-function/output.js index 8e03d7deb..9bf413331 100644 --- a/packages/commonjs/test/fixtures/form/ignore-ids-function/output.js +++ b/packages/commonjs/test/fixtures/form/ignore-ids-function/output.js @@ -1,10 +1,8 @@ import * as commonjsHelpers from "_commonjsHelpers.js"; import { __exports as input } from "\u0000fixtures/form/ignore-ids-function/input.js?commonjs-exports" -import "\u0000bar?commonjs-require"; -import require$$0 from "\u0000bar?commonjs-proxy"; +import require$$0 from "\u0000CWD/fixtures/form/ignore-ids-function/bar.js?commonjs-proxy"; var foo = require( 'foo' ); var bar = require$$0; -export default input; -export { input as __moduleExports }; +export { input as __moduleExports, input as default }; diff --git a/packages/commonjs/test/fixtures/form/ignore-ids/output.js b/packages/commonjs/test/fixtures/form/ignore-ids/output.js index 278e805a2..7bf69819c 100644 --- a/packages/commonjs/test/fixtures/form/ignore-ids/output.js +++ b/packages/commonjs/test/fixtures/form/ignore-ids/output.js @@ -1,10 +1,8 @@ import * as commonjsHelpers from "_commonjsHelpers.js"; import { __exports as input } from "\u0000fixtures/form/ignore-ids/input.js?commonjs-exports" -import "\u0000bar?commonjs-require"; -import require$$0 from "\u0000bar?commonjs-proxy"; +import require$$0 from "\u0000CWD/fixtures/form/ignore-ids/bar.js?commonjs-proxy"; var foo = require( 'foo' ); var bar = require$$0; -export default input; -export { input as __moduleExports }; +export { input as __moduleExports, input as default }; diff --git a/packages/commonjs/test/fixtures/form/multi-entry-module-exports/output1.js b/packages/commonjs/test/fixtures/form/multi-entry-module-exports/output1.js index 7cf227a40..214e817e3 100644 --- a/packages/commonjs/test/fixtures/form/multi-entry-module-exports/output1.js +++ b/packages/commonjs/test/fixtures/form/multi-entry-module-exports/output1.js @@ -1,6 +1,5 @@ import * as commonjsHelpers from "_commonjsHelpers.js"; -import "\u0000./input2.js?commonjs-require"; -import require$$0 from "\u0000./input2.js?commonjs-proxy"; +import require$$0 from "\u0000CWD/fixtures/form/multi-entry-module-exports/input2.js?commonjs-proxy"; const t2 = require$$0; diff --git a/packages/commonjs/test/fixtures/form/multiple-var-declarations-b/output.js b/packages/commonjs/test/fixtures/form/multiple-var-declarations-b/output.js index 2537be812..93cf331d5 100644 --- a/packages/commonjs/test/fixtures/form/multiple-var-declarations-b/output.js +++ b/packages/commonjs/test/fixtures/form/multiple-var-declarations-b/output.js @@ -1,12 +1,10 @@ import * as commonjsHelpers from "_commonjsHelpers.js"; import { __exports as input } from "\u0000fixtures/form/multiple-var-declarations-b/input.js?commonjs-exports" -import "\u0000./a?commonjs-require"; -import require$$0 from "\u0000./a?commonjs-proxy"; +import require$$0 from "\u0000CWD/fixtures/form/multiple-var-declarations-b/a.js?commonjs-proxy"; var a = require$$0 , b = 42; console.log( a, b ); -export default input; -export { input as __moduleExports }; +export { input as __moduleExports, input as default }; diff --git a/packages/commonjs/test/fixtures/form/multiple-var-declarations-c/output.js b/packages/commonjs/test/fixtures/form/multiple-var-declarations-c/output.js index 0e9886246..d5d652e50 100644 --- a/packages/commonjs/test/fixtures/form/multiple-var-declarations-c/output.js +++ b/packages/commonjs/test/fixtures/form/multiple-var-declarations-c/output.js @@ -1,7 +1,6 @@ import * as commonjsHelpers from "_commonjsHelpers.js"; import { __exports as input } from "\u0000fixtures/form/multiple-var-declarations-c/input.js?commonjs-exports" -import "\u0000./b?commonjs-require"; -import require$$0 from "\u0000./b?commonjs-proxy"; +import require$$0 from "\u0000CWD/fixtures/form/multiple-var-declarations-c/b.js?commonjs-proxy"; var a = 'a' , b = require$$0 @@ -9,5 +8,4 @@ var a = 'a' console.log( a, b, c ); -export default input; -export { input as __moduleExports }; +export { input as __moduleExports, input as default }; diff --git a/packages/commonjs/test/fixtures/form/multiple-var-declarations/output.js b/packages/commonjs/test/fixtures/form/multiple-var-declarations/output.js index 275bd35b0..3e05dfdb0 100644 --- a/packages/commonjs/test/fixtures/form/multiple-var-declarations/output.js +++ b/packages/commonjs/test/fixtures/form/multiple-var-declarations/output.js @@ -1,14 +1,11 @@ import * as commonjsHelpers from "_commonjsHelpers.js"; import { __exports as input } from "\u0000fixtures/form/multiple-var-declarations/input.js?commonjs-exports" -import "\u0000./a?commonjs-require"; -import require$$0 from "\u0000./a?commonjs-proxy"; -import "\u0000./b?commonjs-require"; -import require$$1 from "\u0000./b?commonjs-proxy"; +import require$$0 from "\u0000CWD/fixtures/form/multiple-var-declarations/a.js?commonjs-proxy"; +import require$$1 from "\u0000CWD/fixtures/form/multiple-var-declarations/b.js?commonjs-proxy"; var a = require$$0() , b = require$$1; console.log( a, b ); -export default input; -export { input as __moduleExports }; +export { input as __moduleExports, input as default }; diff --git a/packages/commonjs/test/fixtures/form/no-exports-entry/output.js b/packages/commonjs/test/fixtures/form/no-exports-entry/output.js index b9a72362d..252fd167f 100644 --- a/packages/commonjs/test/fixtures/form/no-exports-entry/output.js +++ b/packages/commonjs/test/fixtures/form/no-exports-entry/output.js @@ -1,7 +1,6 @@ import * as commonjsHelpers from "_commonjsHelpers.js"; import { __exports as input_1 } from "\u0000fixtures/form/no-exports-entry/input.js?commonjs-exports" -import "\u0000./dummy?commonjs-require"; -import require$$0 from "\u0000./dummy?commonjs-proxy"; +import require$$0 from "\u0000CWD/fixtures/form/no-exports-entry/dummy.js?commonjs-proxy"; var dummy = require$$0; @@ -11,5 +10,4 @@ var foo = function () { var input = 42; -export default input_1; -export { input_1 as __moduleExports }; +export { input_1 as __moduleExports, input_1 as default }; diff --git a/packages/commonjs/test/fixtures/form/node-require-methods/output.js b/packages/commonjs/test/fixtures/form/node-require-methods/output.js index 1192a708d..6aff4d3e1 100644 --- a/packages/commonjs/test/fixtures/form/node-require-methods/output.js +++ b/packages/commonjs/test/fixtures/form/node-require-methods/output.js @@ -5,5 +5,4 @@ var getFilePath = input.getFilePath = function getFilePath(someFile) { return require.resolve(someFile); }; -export default input; -export { input as __moduleExports, getFilePath }; +export { input as __moduleExports, getFilePath, input as default }; diff --git a/packages/commonjs/test/fixtures/form/optimised-named-export-conflicts/output.js b/packages/commonjs/test/fixtures/form/optimised-named-export-conflicts/output.js index 2a8ab72b4..a91b08d2d 100644 --- a/packages/commonjs/test/fixtures/form/optimised-named-export-conflicts/output.js +++ b/packages/commonjs/test/fixtures/form/optimised-named-export-conflicts/output.js @@ -7,5 +7,4 @@ var bar = 2; var foo_1 = input.foo = 'a'; var bar_1 = input.bar = 'b'; -export default input; -export { input as __moduleExports, foo_1 as foo, bar_1 as bar }; +export { input as __moduleExports, foo_1 as foo, bar_1 as bar, input as default }; diff --git a/packages/commonjs/test/fixtures/form/optimised-named-export/output.js b/packages/commonjs/test/fixtures/form/optimised-named-export/output.js index 4f5d1feca..e5ca89b12 100644 --- a/packages/commonjs/test/fixtures/form/optimised-named-export/output.js +++ b/packages/commonjs/test/fixtures/form/optimised-named-export/output.js @@ -4,5 +4,4 @@ import { __exports as input } from "\u0000fixtures/form/optimised-named-export/i var foo = input.foo = 'a'; var bar = input.bar = 'b'; -export default input; -export { input as __moduleExports, foo, bar }; +export { input as __moduleExports, foo, bar, input as default }; diff --git a/packages/commonjs/test/fixtures/form/require-collision/output.js b/packages/commonjs/test/fixtures/form/require-collision/output.js index ff0f5b1ba..44fd7b388 100644 --- a/packages/commonjs/test/fixtures/form/require-collision/output.js +++ b/packages/commonjs/test/fixtures/form/require-collision/output.js @@ -1,7 +1,6 @@ import * as commonjsHelpers from "_commonjsHelpers.js"; import { __exports as input } from "\u0000fixtures/form/require-collision/input.js?commonjs-exports" -import "\u0000foo?commonjs-require"; -import require$$1 from "\u0000foo?commonjs-proxy"; +import require$$1 from "\u0000CWD/fixtures/form/require-collision/foo.js?commonjs-proxy"; (function() { var foo = require$$1; @@ -9,5 +8,4 @@ import require$$1 from "\u0000foo?commonjs-proxy"; console.log(foo); })(); -export default input; -export { input as __moduleExports }; +export { input as __moduleExports, input as default }; diff --git a/packages/commonjs/test/fixtures/form/try-catch-remove/_config.js b/packages/commonjs/test/fixtures/form/try-catch-remove/_config.js deleted file mode 100644 index de5563f0d..000000000 --- a/packages/commonjs/test/fixtures/form/try-catch-remove/_config.js +++ /dev/null @@ -1,5 +0,0 @@ -module.exports = { - options: { - ignoreTryCatch: (id) => id === 'uninstalled-external-module' ? 'remove' : false - } -}; diff --git a/packages/commonjs/test/fixtures/form/try-catch-remove/output.js b/packages/commonjs/test/fixtures/form/try-catch-remove/output.js deleted file mode 100644 index 1b73e073c..000000000 --- a/packages/commonjs/test/fixtures/form/try-catch-remove/output.js +++ /dev/null @@ -1,12 +0,0 @@ -/* eslint-disable global-require */ -import * as commonjsHelpers from "_commonjsHelpers.js"; -import { __exports as input } from "\u0000fixtures/form/try-catch-remove/input.js?commonjs-exports" - -try { - -} catch (ignored) { - /* ignore */ -} - -export default input; -export { input as __moduleExports }; diff --git a/packages/commonjs/test/fixtures/form/typeof-module-exports/output.js b/packages/commonjs/test/fixtures/form/typeof-module-exports/output.js index 174b58185..17e00f801 100644 --- a/packages/commonjs/test/fixtures/form/typeof-module-exports/output.js +++ b/packages/commonjs/test/fixtures/form/typeof-module-exports/output.js @@ -2,16 +2,16 @@ import * as commonjsHelpers from "_commonjsHelpers.js"; import { __module as inputModule, exports as input } from "\u0000fixtures/form/typeof-module-exports/input.js?commonjs-module" (function (module, exports) { -var foo = 42; + var foo = 42; -if ( 'object' === 'object' && 'object' === 'object' ) { - module.exports = foo; -} else if ( typeof undefined === 'function' && undefined.amd ) { - undefined([], function () { return foo; }); -} else { - window.foo = foo; -} -}(inputModule, input)); + if ( 'object' === 'object' && 'object' === 'object' ) { + module.exports = foo; + } else if ( typeof undefined === 'function' && undefined.amd ) { + undefined([], function () { return foo; }); + } else { + window.foo = foo; + } +} (inputModule, input)); export default input; export { input as __moduleExports }; diff --git a/packages/commonjs/test/fixtures/form/unambiguous-with-default-export/output.js b/packages/commonjs/test/fixtures/form/unambiguous-with-default-export/output.js index fb8c36ea6..2d6dac42c 100644 --- a/packages/commonjs/test/fixtures/form/unambiguous-with-default-export/output.js +++ b/packages/commonjs/test/fixtures/form/unambiguous-with-default-export/output.js @@ -1,6 +1,4 @@ import * as commonjsHelpers from "_commonjsHelpers.js"; -import { __exports as input } from "\u0000fixtures/form/unambiguous-with-default-export/input.js?commonjs-exports" -import "\u0000./foo.js?commonjs-require"; -import "\u0000./foo.js?commonjs-proxy"; +import "\u0000CWD/fixtures/form/unambiguous-with-default-export/foo.js?commonjs-proxy"; export default {}; diff --git a/packages/commonjs/test/fixtures/form/unambiguous-with-import/output.js b/packages/commonjs/test/fixtures/form/unambiguous-with-import/output.js index 2b859d8d7..0a89b5bf6 100644 --- a/packages/commonjs/test/fixtures/form/unambiguous-with-import/output.js +++ b/packages/commonjs/test/fixtures/form/unambiguous-with-import/output.js @@ -1,6 +1,4 @@ import * as commonjsHelpers from "_commonjsHelpers.js"; -import { __exports as input } from "\u0000fixtures/form/unambiguous-with-import/input.js?commonjs-exports" -import "\u0000./foo.js?commonjs-require"; -import "\u0000./foo.js?commonjs-proxy"; +import "\u0000CWD/fixtures/form/unambiguous-with-import/foo.js?commonjs-proxy"; import './bar.js'; diff --git a/packages/commonjs/test/fixtures/form/unambiguous-with-named-export/output.js b/packages/commonjs/test/fixtures/form/unambiguous-with-named-export/output.js index 98d732a34..13bee26c4 100644 --- a/packages/commonjs/test/fixtures/form/unambiguous-with-named-export/output.js +++ b/packages/commonjs/test/fixtures/form/unambiguous-with-named-export/output.js @@ -1,6 +1,4 @@ import * as commonjsHelpers from "_commonjsHelpers.js"; -import { __exports as input } from "\u0000fixtures/form/unambiguous-with-named-export/input.js?commonjs-exports" -import "\u0000./foo.js?commonjs-require"; -import "\u0000./foo.js?commonjs-proxy"; +import "\u0000CWD/fixtures/form/unambiguous-with-named-export/foo.js?commonjs-proxy"; export {}; diff --git a/packages/commonjs/test/fixtures/function/call-non-local-function-semantics/_config.js b/packages/commonjs/test/fixtures/function/call-non-local-function-semantics/_config.js new file mode 100644 index 000000000..ac0ea14e6 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/call-non-local-function-semantics/_config.js @@ -0,0 +1,4 @@ +module.exports = { + description: + 'uses strict require semantics for all modules that are required after an imported function is called' +}; diff --git a/packages/commonjs/test/fixtures/function/call-non-local-function-semantics/browser.js b/packages/commonjs/test/fixtures/function/call-non-local-function-semantics/browser.js new file mode 100644 index 000000000..842765579 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/call-non-local-function-semantics/browser.js @@ -0,0 +1 @@ +module.exports = 'browser'; diff --git a/packages/commonjs/test/fixtures/function/call-non-local-function-semantics/main.js b/packages/commonjs/test/fixtures/function/call-non-local-function-semantics/main.js new file mode 100644 index 000000000..f9e23dd6c --- /dev/null +++ b/packages/commonjs/test/fixtures/function/call-non-local-function-semantics/main.js @@ -0,0 +1,7 @@ +// simplified from dd-trace +const platform = require('./platform'); +const browser = require('./browser'); + +platform.use(browser); + +require('./proxy'); diff --git a/packages/commonjs/test/fixtures/function/call-non-local-function-semantics/platform.js b/packages/commonjs/test/fixtures/function/call-non-local-function-semantics/platform.js new file mode 100644 index 000000000..93634d9df --- /dev/null +++ b/packages/commonjs/test/fixtures/function/call-non-local-function-semantics/platform.js @@ -0,0 +1 @@ +exports.use = (platform) => (exports.platform = platform); diff --git a/packages/commonjs/test/fixtures/function/call-non-local-function-semantics/proxy.js b/packages/commonjs/test/fixtures/function/call-non-local-function-semantics/proxy.js new file mode 100644 index 000000000..e490667ea --- /dev/null +++ b/packages/commonjs/test/fixtures/function/call-non-local-function-semantics/proxy.js @@ -0,0 +1,3 @@ +const { platform } = require('./platform.js'); + +t.is(platform, 'browser'); diff --git a/packages/commonjs/test/fixtures/function/circular-dependencies-wrapped/_config.js b/packages/commonjs/test/fixtures/function/circular-dependencies-wrapped/_config.js index 0b7a53026..cda7e0f2f 100644 --- a/packages/commonjs/test/fixtures/function/circular-dependencies-wrapped/_config.js +++ b/packages/commonjs/test/fixtures/function/circular-dependencies-wrapped/_config.js @@ -9,5 +9,8 @@ module.exports = { output: { exports: 'named' } + }, + pluginOptions: { + strictRequires: false } }; diff --git a/packages/commonjs/test/fixtures/function/circular-dependencies/_config.js b/packages/commonjs/test/fixtures/function/circular-dependencies/_config.js index 78fe11373..c561742f0 100644 --- a/packages/commonjs/test/fixtures/function/circular-dependencies/_config.js +++ b/packages/commonjs/test/fixtures/function/circular-dependencies/_config.js @@ -9,5 +9,8 @@ module.exports = { output: { exports: 'named' } + }, + pluginOptions: { + strictRequires: false } }; diff --git a/packages/commonjs/test/fixtures/function/cjs-extension/_config.js b/packages/commonjs/test/fixtures/function/cjs-extension/_config.js new file mode 100644 index 000000000..1edda6c48 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/cjs-extension/_config.js @@ -0,0 +1,3 @@ +module.exports = { + description: 'imports .cjs file extension by default' +}; diff --git a/packages/commonjs/test/fixtures/samples/cjs-extension/export.cjs b/packages/commonjs/test/fixtures/function/cjs-extension/export.cjs similarity index 100% rename from packages/commonjs/test/fixtures/samples/cjs-extension/export.cjs rename to packages/commonjs/test/fixtures/function/cjs-extension/export.cjs diff --git a/packages/commonjs/test/fixtures/samples/cjs-extension/main.js b/packages/commonjs/test/fixtures/function/cjs-extension/main.js similarity index 69% rename from packages/commonjs/test/fixtures/samples/cjs-extension/main.js rename to packages/commonjs/test/fixtures/function/cjs-extension/main.js index b76e19952..fc1029fd7 100644 --- a/packages/commonjs/test/fixtures/samples/cjs-extension/main.js +++ b/packages/commonjs/test/fixtures/function/cjs-extension/main.js @@ -1,3 +1,3 @@ const { test } = require('./export.cjs'); -console.log(test); +t.is(test, 42); diff --git a/packages/commonjs/test/fixtures/function/conditional-require-chain/_config.js b/packages/commonjs/test/fixtures/function/conditional-require-chain/_config.js new file mode 100644 index 000000000..e0666eccc --- /dev/null +++ b/packages/commonjs/test/fixtures/function/conditional-require-chain/_config.js @@ -0,0 +1,3 @@ +module.exports = { + description: 'makes requires in conditionally required modules conditional as well' +}; diff --git a/packages/commonjs/test/fixtures/function/conditional-require-chain/dep.js b/packages/commonjs/test/fixtures/function/conditional-require-chain/dep.js new file mode 100644 index 000000000..3b1998d8e --- /dev/null +++ b/packages/commonjs/test/fixtures/function/conditional-require-chain/dep.js @@ -0,0 +1 @@ +require('./throws.js'); diff --git a/packages/commonjs/test/fixtures/function/conditional-require-chain/main.js b/packages/commonjs/test/fixtures/function/conditional-require-chain/main.js new file mode 100644 index 000000000..1aa85f1c1 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/conditional-require-chain/main.js @@ -0,0 +1,6 @@ +global.false = false; + +if (global.false) { + // eslint-disable-next-line global-require + require('./dep.js'); +} diff --git a/packages/commonjs/test/fixtures/function/conditional-require-chain/throws.js b/packages/commonjs/test/fixtures/function/conditional-require-chain/throws.js new file mode 100644 index 000000000..eb8668af4 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/conditional-require-chain/throws.js @@ -0,0 +1 @@ +throw new Error('This should not be executed'); diff --git a/packages/commonjs/test/fixtures/function/conditional-require-non-strict/_config.js b/packages/commonjs/test/fixtures/function/conditional-require-non-strict/_config.js new file mode 100644 index 000000000..fc1671434 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/conditional-require-non-strict/_config.js @@ -0,0 +1,4 @@ +module.exports = { + description: 'handles conditional require statements in non-strict mode', + pluginOptions: { strictRequires: false } +}; diff --git a/packages/commonjs/test/fixtures/function/conditional-require-non-strict/bar.js b/packages/commonjs/test/fixtures/function/conditional-require-non-strict/bar.js new file mode 100644 index 000000000..4a625a917 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/conditional-require-non-strict/bar.js @@ -0,0 +1 @@ +global.bar = true; diff --git a/packages/commonjs/test/fixtures/function/conditional-require-non-strict/foo.js b/packages/commonjs/test/fixtures/function/conditional-require-non-strict/foo.js new file mode 100644 index 000000000..a446ce3ad --- /dev/null +++ b/packages/commonjs/test/fixtures/function/conditional-require-non-strict/foo.js @@ -0,0 +1 @@ +global.foo = true; diff --git a/packages/commonjs/test/fixtures/function/conditional-require-non-strict/main.js b/packages/commonjs/test/fixtures/function/conditional-require-non-strict/main.js new file mode 100644 index 000000000..e64d67ec9 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/conditional-require-non-strict/main.js @@ -0,0 +1,7 @@ +if (Math.random() < 2) require('./foo.js'); +if (Math.random() > 2) require('./bar.js'); + +global.main = true; + +t.is(global.foo, true, 'foo'); +t.is(global.main, true, 'main'); diff --git a/packages/commonjs/test/fixtures/function/custom-options/_config.js b/packages/commonjs/test/fixtures/function/custom-options/_config.js index a54562867..ebbb4a496 100644 --- a/packages/commonjs/test/fixtures/function/custom-options/_config.js +++ b/packages/commonjs/test/fixtures/function/custom-options/_config.js @@ -18,14 +18,7 @@ module.exports = { buildEnd() { assert.deepStrictEqual(resolveIdArgs, [ ['other.js', 'main.js', { custom: { test: 42 }, isEntry: true }], - [ - 'other.js', - 'main.js', - // This is the important one - { custom: { test: 42, 'node-resolve': { isRequire: false } }, isEntry: true } - ], - ['main.js', void 0, { custom: {}, isEntry: true }], - ['main.js', void 0, { custom: { 'node-resolve': { isRequire: false } }, isEntry: true }] + ['main.js', void 0, { custom: {}, isEntry: true }] ]); }, resolveId(source, importer, options) { diff --git a/packages/commonjs/test/fixtures/function/custom-options/main.js b/packages/commonjs/test/fixtures/function/custom-options/main.js index c0b933d7b..36aa4b64f 100644 --- a/packages/commonjs/test/fixtures/function/custom-options/main.js +++ b/packages/commonjs/test/fixtures/function/custom-options/main.js @@ -1 +1 @@ -console.log('main'); +t.is('main', 'main'); diff --git a/packages/commonjs/test/fixtures/function/custom-options/other.js b/packages/commonjs/test/fixtures/function/custom-options/other.js index 8bbad80dc..edd7566fb 100644 --- a/packages/commonjs/test/fixtures/function/custom-options/other.js +++ b/packages/commonjs/test/fixtures/function/custom-options/other.js @@ -1 +1 @@ -console.log('other'); +throw new Error('Other should not be executed'); diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-alias-hack/_config.js b/packages/commonjs/test/fixtures/function/dynamic-require-alias-hack/_config.js new file mode 100755 index 000000000..f52126137 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/dynamic-require-alias-hack/_config.js @@ -0,0 +1,7 @@ +module.exports = { + description: 'resolves both windows and posix paths', + pluginOptions: { + dynamicRequireTargets: ['fixtures/function/dynamic-require-alias-hack/stub.js'], + ignoreDynamicRequires: true + } +}; diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-alias-hack/main.js b/packages/commonjs/test/fixtures/function/dynamic-require-alias-hack/main.js new file mode 100755 index 000000000..636d42e03 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/dynamic-require-alias-hack/main.js @@ -0,0 +1,9 @@ +/* eslint-disable global-require */ +// noinspection UnnecessaryLocalVariableJS + +// A hack used in many old libraries, saying "workaround to exclude package from browserify list." +// Will bypass rollup-commonjs finding out that this is a require that should not go through the plugin, and will do an infinite search. +const _require = require; +const buffer = _require('buffer'); + +t.is(buffer, require('buffer')); diff --git a/packages/commonjs/test/fixtures/samples/dynamic-require-different-loader/submodule2.js b/packages/commonjs/test/fixtures/function/dynamic-require-alias-hack/stub.js similarity index 100% rename from packages/commonjs/test/fixtures/samples/dynamic-require-different-loader/submodule2.js rename to packages/commonjs/test/fixtures/function/dynamic-require-alias-hack/stub.js diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-cache-reference/_config.js b/packages/commonjs/test/fixtures/function/dynamic-require-cache-reference/_config.js deleted file mode 100755 index 6085df3dc..000000000 --- a/packages/commonjs/test/fixtures/function/dynamic-require-cache-reference/_config.js +++ /dev/null @@ -1,13 +0,0 @@ -const { nodeResolve } = require('@rollup/plugin-node-resolve'); - -module.exports = { - description: 'accesses commonjsRequire.cache', - options: { - plugins: [nodeResolve()] - }, - pluginOptions: { - dynamicRequireTargets: [ - 'fixtures/function/dynamic-require-cache-reference/node_modules/{custom-module,custom-module2}{,/*.js}' - ] - } -}; diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-cache-reference/main.js b/packages/commonjs/test/fixtures/function/dynamic-require-cache-reference/main.js deleted file mode 100755 index b60c0f9dd..000000000 --- a/packages/commonjs/test/fixtures/function/dynamic-require-cache-reference/main.js +++ /dev/null @@ -1,5 +0,0 @@ -const a = require('custom-module2'); -const b = require('custom-module'); - -t.is(a.foo, 'baz'); -t.is(b.foo, 'bar'); diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-cache-reference/node_modules/custom-module/index.js b/packages/commonjs/test/fixtures/function/dynamic-require-cache-reference/node_modules/custom-module/index.js deleted file mode 100755 index 5b4c8fd7a..000000000 --- a/packages/commonjs/test/fixtures/function/dynamic-require-cache-reference/node_modules/custom-module/index.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = { - foo: 'bar', -}; diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-cache-reference/node_modules/custom-module2/index.js b/packages/commonjs/test/fixtures/function/dynamic-require-cache-reference/node_modules/custom-module2/index.js deleted file mode 100755 index 1e06b7638..000000000 --- a/packages/commonjs/test/fixtures/function/dynamic-require-cache-reference/node_modules/custom-module2/index.js +++ /dev/null @@ -1,7 +0,0 @@ -const stealthRequire = require('stealthy'); - -module.exports = stealthRequire(require.cache, () => { - let m = require('custom-module'); - m.foo = 'baz'; - return m; -}); diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-cache-reference/node_modules/stealthy/index.js b/packages/commonjs/test/fixtures/function/dynamic-require-cache-reference/node_modules/stealthy/index.js deleted file mode 100644 index 20b1da1c0..000000000 --- a/packages/commonjs/test/fixtures/function/dynamic-require-cache-reference/node_modules/stealthy/index.js +++ /dev/null @@ -1,25 +0,0 @@ -function mv(from, to) { - for (let [key, value] of Object.entries(from)) { - to[key] = value; - } -} - -function clear(obj) { - for (let key of Array.from(Object.keys(obj))) { - delete obj[key]; - } -} - -module.exports = function stealth(cacheObject, cb) { - let orig = Object.create(null); - - mv(cacheObject, orig) - clear(cacheObject) - - let res = cb(); - - clear(cacheObject) - mv(orig, cacheObject) - - return res; -}; diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-different-loader/_config.js b/packages/commonjs/test/fixtures/function/dynamic-require-different-loader/_config.js new file mode 100644 index 000000000..886b59564 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/dynamic-require-different-loader/_config.js @@ -0,0 +1,21 @@ +const path = require('path'); + +module.exports = { + description: 'handles dynamic requires when entry is from a custom loader', + options: { + plugins: [ + { + load(id) { + if (id === path.resolve('fixtures/function/dynamic-require-different-loader/main.js')) { + return 'import submodule1 from "./submodule1"; export default submodule1();'; + } + return null; + } + } + ] + }, + pluginOptions: { + dynamicRequireTargets: ['fixtures/function/dynamic-require-different-loader/submodule2.js'], + transformMixedEsModules: true + } +}; diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-different-loader/main.js b/packages/commonjs/test/fixtures/function/dynamic-require-different-loader/main.js new file mode 100755 index 000000000..4b24999ae --- /dev/null +++ b/packages/commonjs/test/fixtures/function/dynamic-require-different-loader/main.js @@ -0,0 +1 @@ +throw new Error('Should be replaced by a custom loader'); diff --git a/packages/commonjs/test/fixtures/samples/dynamic-require-different-loader/submodule1.js b/packages/commonjs/test/fixtures/function/dynamic-require-different-loader/submodule1.js similarity index 100% rename from packages/commonjs/test/fixtures/samples/dynamic-require-different-loader/submodule1.js rename to packages/commonjs/test/fixtures/function/dynamic-require-different-loader/submodule1.js diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-different-loader/submodule2.js b/packages/commonjs/test/fixtures/function/dynamic-require-different-loader/submodule2.js new file mode 100755 index 000000000..28a021e39 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/dynamic-require-different-loader/submodule2.js @@ -0,0 +1,3 @@ +module.exports = function () { + return 'Hello there'; +}; diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-empty/_config.js b/packages/commonjs/test/fixtures/function/dynamic-require-empty/_config.js new file mode 100755 index 000000000..a416647cf --- /dev/null +++ b/packages/commonjs/test/fixtures/function/dynamic-require-empty/_config.js @@ -0,0 +1,6 @@ +module.exports = { + description: 'allows dynamically requiring an empty file', + pluginOptions: { + dynamicRequireTargets: ['fixtures/function/dynamic-require-empty/submodule.js'] + } +}; diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-empty/main.js b/packages/commonjs/test/fixtures/function/dynamic-require-empty/main.js new file mode 100755 index 000000000..d1c0f89d7 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/dynamic-require-empty/main.js @@ -0,0 +1,6 @@ +/* eslint-disable import/no-dynamic-require, global-require */ +function takeModule(withName) { + return require(`./${withName}`); +} + +t.deepEqual(takeModule('submodule'), {}); diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-empty/submodule.js b/packages/commonjs/test/fixtures/function/dynamic-require-empty/submodule.js new file mode 100755 index 000000000..e69de29bb diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-es-mixed-helpers/_config.js b/packages/commonjs/test/fixtures/function/dynamic-require-es-mixed-helpers/_config.js new file mode 100755 index 000000000..d9b26bed7 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/dynamic-require-es-mixed-helpers/_config.js @@ -0,0 +1,7 @@ +module.exports = { + description: 'supports strict require semantic in mixed modules', + pluginOptions: { + strictRequires: true, + transformMixedEsModules: true + } +}; diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-es-mixed-helpers/importer.js b/packages/commonjs/test/fixtures/function/dynamic-require-es-mixed-helpers/importer.js new file mode 100755 index 000000000..ab6eb9fa2 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/dynamic-require-es-mixed-helpers/importer.js @@ -0,0 +1,7 @@ +t.is(global.hasSubmoduleRun, undefined, 'before require'); + +// eslint-disable-next-line global-require +export default require('./submodule.js'); + +t.is(global.hasSubmoduleRun, true, 'after require'); +delete global.hasSubmoduleRun; diff --git a/packages/commonjs/test/fixtures/samples/dynamic-require-es-mixed-helpers/main.js b/packages/commonjs/test/fixtures/function/dynamic-require-es-mixed-helpers/main.js similarity index 50% rename from packages/commonjs/test/fixtures/samples/dynamic-require-es-mixed-helpers/main.js rename to packages/commonjs/test/fixtures/function/dynamic-require-es-mixed-helpers/main.js index 523e6c2dc..a7add1fba 100755 --- a/packages/commonjs/test/fixtures/samples/dynamic-require-es-mixed-helpers/main.js +++ b/packages/commonjs/test/fixtures/function/dynamic-require-es-mixed-helpers/main.js @@ -1,5 +1,3 @@ -/* eslint-disable import/no-dynamic-require, global-require */ - import result from './importer.js'; t.is(result, 'submodule'); diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-es-mixed-helpers/submodule.js b/packages/commonjs/test/fixtures/function/dynamic-require-es-mixed-helpers/submodule.js new file mode 100755 index 000000000..15eb5a9b1 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/dynamic-require-es-mixed-helpers/submodule.js @@ -0,0 +1,2 @@ +global.hasSubmoduleRun = true; +module.exports = 'submodule'; diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-resolve-reference/main.js b/packages/commonjs/test/fixtures/function/dynamic-require-resolve-reference/main.js index 5dcdc0b90..90dd10156 100755 --- a/packages/commonjs/test/fixtures/function/dynamic-require-resolve-reference/main.js +++ b/packages/commonjs/test/fixtures/function/dynamic-require-resolve-reference/main.js @@ -1,4 +1,8 @@ +t.is( + require('custom-module')(), + '/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module2' +); t.is( require('custom-module2')(), - '/$$rollup_base$$/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module' + '/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module' ); diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module/index.js b/packages/commonjs/test/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module/index.js index 5b4c8fd7a..7eabc0d90 100755 --- a/packages/commonjs/test/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module/index.js +++ b/packages/commonjs/test/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module/index.js @@ -1,3 +1 @@ -module.exports = { - foo: 'bar', -}; +module.exports = () => module.require.resolve('custom-module2'); diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module2/index.js b/packages/commonjs/test/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module2/index.js index 4ffedfe58..f7ec4a019 100755 --- a/packages/commonjs/test/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module2/index.js +++ b/packages/commonjs/test/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module2/index.js @@ -1,3 +1 @@ -module.exports = () => { - return require.resolve('custom-module'); -}; +module.exports = () => require.resolve('custom-module'); diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-root-circular/_config.js b/packages/commonjs/test/fixtures/function/dynamic-require-root-circular/_config.js index c426b3756..15ca843d9 100755 --- a/packages/commonjs/test/fixtures/function/dynamic-require-root-circular/_config.js +++ b/packages/commonjs/test/fixtures/function/dynamic-require-root-circular/_config.js @@ -1,7 +1,7 @@ const { nodeResolve } = require('@rollup/plugin-node-resolve'); module.exports = { - description: 'resolves circular references through indirect access (../ to module\'s root)', + description: "resolves circular references through indirect access (../ to module's root)", options: { plugins: [nodeResolve()] }, diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-root/_config.js b/packages/commonjs/test/fixtures/function/dynamic-require-root/_config.js new file mode 100755 index 000000000..04b381c33 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/dynamic-require-root/_config.js @@ -0,0 +1,7 @@ +module.exports = { + description: 'supports specifying a dynamic require root', + pluginOptions: { + dynamicRequireTargets: ['fixtures/function/dynamic-require-root/submodule.js'], + dynamicRequireRoot: 'fixtures/function/dynamic-require-root' + } +}; diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-root/main.js b/packages/commonjs/test/fixtures/function/dynamic-require-root/main.js new file mode 100755 index 000000000..28c3ae84d --- /dev/null +++ b/packages/commonjs/test/fixtures/function/dynamic-require-root/main.js @@ -0,0 +1,16 @@ +/* eslint-disable import/no-dynamic-require, global-require */ + +let message; + +function takeModule(withName) { + return require(`./${withName}`); +} + +try { + const submodule = takeModule('submodule'); + message = submodule(); +} catch (err) { + ({ message } = err); +} + +t.is(message, 'Hello there'); diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-root/submodule.js b/packages/commonjs/test/fixtures/function/dynamic-require-root/submodule.js new file mode 100755 index 000000000..28a021e39 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/dynamic-require-root/submodule.js @@ -0,0 +1,3 @@ +module.exports = function () { + return 'Hello there'; +}; diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-slash-access/_config.js b/packages/commonjs/test/fixtures/function/dynamic-require-slash-access/_config.js index 0713326f6..013229479 100755 --- a/packages/commonjs/test/fixtures/function/dynamic-require-slash-access/_config.js +++ b/packages/commonjs/test/fixtures/function/dynamic-require-slash-access/_config.js @@ -1,9 +1,6 @@ const { nodeResolve } = require('@rollup/plugin-node-resolve'); module.exports = { - // TODO This test is broken because for dynamic require targets with dependencies, the dependencies are hoisted - // above the dynamic register calls at the moment - skip: true, description: 'resolves imports of node_modules module with halfway / subfolder access', options: { plugins: [nodeResolve()] diff --git a/packages/commonjs/test/fixtures/function/dynamic-require-slash-access/main.js b/packages/commonjs/test/fixtures/function/dynamic-require-slash-access/main.js index cee139817..111bd1688 100755 --- a/packages/commonjs/test/fixtures/function/dynamic-require-slash-access/main.js +++ b/packages/commonjs/test/fixtures/function/dynamic-require-slash-access/main.js @@ -4,13 +4,13 @@ function takeModule(name) { return require(name); } -t.is(takeModule('.'), 'same-directory'); -t.is(takeModule('./'), 'same-directory'); -t.is(takeModule('.//'), 'same-directory'); +t.is(takeModule('.'), 'same-directory', '.'); +t.is(takeModule('./'), 'same-directory', './'); +t.is(takeModule('.//'), 'same-directory', './/'); -t.is(takeModule('./sub'), 'sub'); +t.is(takeModule('./sub'), 'sub', './sub'); -t.is(takeModule('custom-module'), 'custom-module + sub'); +t.is(takeModule('custom-module'), 'custom-module + sub', 'custom-module'); t.deepEqual(require('./sub/sub'), { parent: 'same-directory', customModule: 'custom-module + sub' diff --git a/packages/commonjs/test/fixtures/function/esm-mixed-exports-function-default/_config.js b/packages/commonjs/test/fixtures/function/esm-mixed-exports-function-default/_config.js new file mode 100644 index 000000000..7891cab61 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/esm-mixed-exports-function-default/_config.js @@ -0,0 +1,4 @@ +module.exports = { + description: + 'allows accessing function default exports as require return value even when there are named exports' +}; diff --git a/packages/commonjs/test/fixtures/function/esm-mixed-exports-function-default/esm-constructor.js b/packages/commonjs/test/fixtures/function/esm-mixed-exports-function-default/esm-constructor.js new file mode 100644 index 000000000..da6746c02 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/esm-mixed-exports-function-default/esm-constructor.js @@ -0,0 +1,9 @@ +export default function Foo(...args) { + this.foo = args; +} + +Foo.prototype.update = function () { + this.foo = 'updated'; +}; + +export const bar = 'bar'; diff --git a/packages/commonjs/test/fixtures/function/esm-mixed-exports-function-default/esm-function.js b/packages/commonjs/test/fixtures/function/esm-mixed-exports-function-default/esm-function.js new file mode 100644 index 000000000..b9b50f89f --- /dev/null +++ b/packages/commonjs/test/fixtures/function/esm-mixed-exports-function-default/esm-function.js @@ -0,0 +1,5 @@ +export default function foo(...args) { + return args; +} + +export const bar = 'bar'; diff --git a/packages/commonjs/test/fixtures/function/esm-mixed-exports-function-default/main.js b/packages/commonjs/test/fixtures/function/esm-mixed-exports-function-default/main.js new file mode 100644 index 000000000..fc760a469 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/esm-mixed-exports-function-default/main.js @@ -0,0 +1,19 @@ +const foo = require('./esm-function.js'); +const Foo = require('./esm-constructor.js'); + +t.is(foo.bar, 'bar'); +t.deepEqual(foo.default('first'), ['first']); +t.deepEqual(foo('second'), ['second']); + +t.is(Foo.bar, 'bar'); + +// eslint-disable-next-line new-cap +const newDefault = new Foo.default('third'); +t.deepEqual(newDefault.foo, ['third']); +newDefault.update(); +t.is(newDefault.foo, 'updated'); + +const newFoo = new Foo('fourth'); +t.deepEqual(newFoo.foo, ['fourth']); +newFoo.update(); +t.is(newFoo.foo, 'updated'); diff --git a/packages/commonjs/test/fixtures/function/import-esm-require-returns-default-false/main.js b/packages/commonjs/test/fixtures/function/import-esm-require-returns-default-false/main.js index 658db2cdd..67b995725 100644 --- a/packages/commonjs/test/fixtures/function/import-esm-require-returns-default-false/main.js +++ b/packages/commonjs/test/fixtures/function/import-esm-require-returns-default-false/main.js @@ -14,3 +14,11 @@ t.deepEqual(noExports, {}, 'no exports'); t.deepEqual(externalNamed, { foo: 'foo' }, 'external named'); t.deepEqual(externalMixed, { foo: 'foo', default: 'bar' }, 'external mixed'); t.deepEqual(externalDefault, { default: 'bar' }, 'external default'); + +/* eslint-disable no-prototype-builtins */ +t.is(namedExports.hasOwnProperty('foo'), true); +t.is(mixedExports.hasOwnProperty('foo'), true); +t.is(defaultExport.hasOwnProperty('foo'), false); +t.is(externalNamed.hasOwnProperty('foo'), true); +t.is(externalMixed.hasOwnProperty('foo'), true); +t.is(externalDefault.hasOwnProperty('foo'), false); diff --git a/packages/commonjs/test/fixtures/function/load-cycle-parallel/_config.js b/packages/commonjs/test/fixtures/function/load-cycle-parallel/_config.js new file mode 100644 index 000000000..73cd1001e --- /dev/null +++ b/packages/commonjs/test/fixtures/function/load-cycle-parallel/_config.js @@ -0,0 +1,3 @@ +module.exports = { + description: 'handles loading all modules of a cycle in parallel' +}; diff --git a/packages/commonjs/test/fixtures/function/load-cycle-parallel/a.js b/packages/commonjs/test/fixtures/function/load-cycle-parallel/a.js new file mode 100644 index 000000000..ed897bbc6 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/load-cycle-parallel/a.js @@ -0,0 +1 @@ +require('./b.js'); diff --git a/packages/commonjs/test/fixtures/function/load-cycle-parallel/b.js b/packages/commonjs/test/fixtures/function/load-cycle-parallel/b.js new file mode 100644 index 000000000..60204ed1e --- /dev/null +++ b/packages/commonjs/test/fixtures/function/load-cycle-parallel/b.js @@ -0,0 +1 @@ +require('./c.js'); diff --git a/packages/commonjs/test/fixtures/function/load-cycle-parallel/c.js b/packages/commonjs/test/fixtures/function/load-cycle-parallel/c.js new file mode 100644 index 000000000..d87ec6cce --- /dev/null +++ b/packages/commonjs/test/fixtures/function/load-cycle-parallel/c.js @@ -0,0 +1 @@ +require('./a.js'); diff --git a/packages/commonjs/test/fixtures/function/load-cycle-parallel/main.js b/packages/commonjs/test/fixtures/function/load-cycle-parallel/main.js new file mode 100644 index 000000000..c6d056017 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/load-cycle-parallel/main.js @@ -0,0 +1,3 @@ +require('./a.js'); +require('./b.js'); +require('./c.js'); diff --git a/packages/commonjs/test/fixtures/function/module-meta-properties/_config.js b/packages/commonjs/test/fixtures/function/module-meta-properties/_config.js new file mode 100644 index 000000000..63b09ffad --- /dev/null +++ b/packages/commonjs/test/fixtures/function/module-meta-properties/_config.js @@ -0,0 +1,27 @@ +module.exports = { + description: 'preserves meta properties attached to modules by resolvers', + options: { + plugins: [ + { + async resolveId(source, importer, options) { + if (source.endsWith('dep.js')) { + return { + ...(await this.resolve(source, importer, { skipSelf: true, ...options })), + meta: { test: 'provided' } + }; + } + return null; + }, + moduleParsed({ id, meta: { test } }) { + if (id.endsWith('dep.js')) { + if (test !== 'provided') { + throw new Error(`Meta property missing for ${id}.`); + } + } else if (test === 'provided') { + throw new Error(`Meta property was unexpectedly added to ${id}.`); + } + } + } + ] + } +}; diff --git a/packages/commonjs/test/fixtures/function/module-meta-properties/dep.js b/packages/commonjs/test/fixtures/function/module-meta-properties/dep.js new file mode 100644 index 000000000..94ecacb72 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/module-meta-properties/dep.js @@ -0,0 +1 @@ +exports.foo = 'foo'; diff --git a/packages/commonjs/test/fixtures/function/module-meta-properties/main.js b/packages/commonjs/test/fixtures/function/module-meta-properties/main.js new file mode 100644 index 000000000..ccf2c9e41 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/module-meta-properties/main.js @@ -0,0 +1,3 @@ +const dep = require('./dep.js'); + +t.is(dep.foo, 'foo'); diff --git a/packages/commonjs/test/fixtures/function/module-side-effects-late-entry/_config.js b/packages/commonjs/test/fixtures/function/module-side-effects-late-entry/_config.js new file mode 100644 index 000000000..8c1d053bd --- /dev/null +++ b/packages/commonjs/test/fixtures/function/module-side-effects-late-entry/_config.js @@ -0,0 +1,22 @@ +const path = require('path'); + +module.exports = { + description: + 'use correct side-effects flags for files that become entry points after they are loaded', + options: { + treeshake: { moduleSideEffects: false }, + plugins: [ + { + load(id) { + if (id.endsWith('foo.js')) { + this.emitFile({ type: 'chunk', id: path.join(__dirname, 'foo.js') }); + } + } + } + ], + output: { chunkFileNames: 'generated-[name].js' } + }, + global: (global, t) => { + t.is(global.foo, 'foo'); + } +}; diff --git a/packages/commonjs/test/fixtures/function/module-side-effects-late-entry/foo.js b/packages/commonjs/test/fixtures/function/module-side-effects-late-entry/foo.js new file mode 100644 index 000000000..53d1fab39 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/module-side-effects-late-entry/foo.js @@ -0,0 +1,2 @@ +// This side-effect will only be respected if this is an entry point +global.foo = 'foo'; diff --git a/packages/commonjs/test/fixtures/function/module-side-effects-late-entry/main.js b/packages/commonjs/test/fixtures/function/module-side-effects-late-entry/main.js new file mode 100644 index 000000000..60af16024 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/module-side-effects-late-entry/main.js @@ -0,0 +1,3 @@ +import './foo.js'; + +export default 'main'; diff --git a/packages/commonjs/test/fixtures/function/no-default-export-live-binding/_config.js b/packages/commonjs/test/fixtures/function/no-default-export-live-binding/_config.js deleted file mode 100644 index 13fadfa24..000000000 --- a/packages/commonjs/test/fixtures/function/no-default-export-live-binding/_config.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = { - description: 'there should not be a live-binding for the default export' -}; diff --git a/packages/commonjs/test/fixtures/function/no-default-export-live-binding/dep1.js b/packages/commonjs/test/fixtures/function/no-default-export-live-binding/dep1.js deleted file mode 100644 index ec206b365..000000000 --- a/packages/commonjs/test/fixtures/function/no-default-export-live-binding/dep1.js +++ /dev/null @@ -1,4 +0,0 @@ -module.exports = { - foo: 'foo', - update: () => (module.exports = { foo: 'bar' }) -}; diff --git a/packages/commonjs/test/fixtures/function/no-default-export-live-binding/dep2.js b/packages/commonjs/test/fixtures/function/no-default-export-live-binding/dep2.js deleted file mode 100644 index f3b624c2e..000000000 --- a/packages/commonjs/test/fixtures/function/no-default-export-live-binding/dep2.js +++ /dev/null @@ -1,2 +0,0 @@ -module.exports.foo = 'foo'; -module.exports.update = () => (module.exports = { foo: 'bar' }); diff --git a/packages/commonjs/test/fixtures/function/no-default-export-live-binding/dep3.js b/packages/commonjs/test/fixtures/function/no-default-export-live-binding/dep3.js deleted file mode 100644 index 2254de7eb..000000000 --- a/packages/commonjs/test/fixtures/function/no-default-export-live-binding/dep3.js +++ /dev/null @@ -1,2 +0,0 @@ -exports.foo = 'foo'; -module.exports.update = () => (module.exports = { foo: 'bar' }); diff --git a/packages/commonjs/test/fixtures/function/no-default-export-live-binding/main.js b/packages/commonjs/test/fixtures/function/no-default-export-live-binding/main.js deleted file mode 100644 index 75edbb4f4..000000000 --- a/packages/commonjs/test/fixtures/function/no-default-export-live-binding/main.js +++ /dev/null @@ -1,15 +0,0 @@ -import dep1 from './dep1.js'; -import dep2 from './dep2.js'; -import dep3 from './dep3.js'; - -t.is(dep1.foo, 'foo', 'dep1'); -dep1.update(); -t.is(dep1.foo, 'foo', 'dep1 updated'); - -t.is(dep2.foo, 'foo', 'dep2'); -dep2.update(); -t.is(dep2.foo, 'foo', 'dep2 updated'); - -t.is(dep3.foo, 'foo', 'dep3'); -dep3.update(); -t.is(dep3.foo, 'foo', 'dep3 updated'); diff --git a/packages/commonjs/test/fixtures/function/plugin-isentry/_config.js b/packages/commonjs/test/fixtures/function/plugin-isentry/_config.js new file mode 100644 index 000000000..156176ad9 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/plugin-isentry/_config.js @@ -0,0 +1,36 @@ +const fs = require('fs'); +const path = require('path'); +const assert = require('assert'); + +const ID_MAIN = path.join(__dirname, 'main.js'); +const ID_OTHER = path.join(__dirname, 'other.js'); + +module.exports = { + description: 'provides correct values for ModuleInfo.isEntry to not break legacy plugins', + options: { + input: [ID_MAIN, ID_OTHER], + output: { + chunkFileNames: '[name].js' + }, + plugins: [ + { + transform(code, id) { + if (this.getModuleInfo(id).isEntry) { + return `import "polyfill";\n${code}`; + } + return null; + }, + resolveId(id) { + if (id === 'polyfill') return id; + return null; + }, + load(id) { + if (id === 'polyfill') { + return `global.entryDetected = true;`; + } + return null; + } + } + ] + } +}; diff --git a/packages/commonjs/test/fixtures/function/plugin-isentry/dep.js b/packages/commonjs/test/fixtures/function/plugin-isentry/dep.js new file mode 100644 index 000000000..2f5dc9fbe --- /dev/null +++ b/packages/commonjs/test/fixtures/function/plugin-isentry/dep.js @@ -0,0 +1,2 @@ +t.is(global.entryDetected, true); +module.exports = 'dep'; diff --git a/packages/commonjs/test/fixtures/function/plugin-isentry/main.js b/packages/commonjs/test/fixtures/function/plugin-isentry/main.js new file mode 100644 index 000000000..811a39ee5 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/plugin-isentry/main.js @@ -0,0 +1,2 @@ +t.is(global.entryDetected, true); +module.exports = require('./dep.js'); diff --git a/packages/commonjs/test/fixtures/function/plugin-isentry/other.js b/packages/commonjs/test/fixtures/function/plugin-isentry/other.js new file mode 100644 index 000000000..661ce2f2e --- /dev/null +++ b/packages/commonjs/test/fixtures/function/plugin-isentry/other.js @@ -0,0 +1 @@ +export const other = true; diff --git a/packages/commonjs/test/fixtures/function/preserve-modules/_config.js b/packages/commonjs/test/fixtures/function/preserve-modules/_config.js new file mode 100644 index 000000000..dbca5a506 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/preserve-modules/_config.js @@ -0,0 +1,14 @@ +module.exports = { + description: 'uses correct entry files names when preserving modules', + options: { + preserveModules: true + }, + pluginOptions: { + // Our entry is wrapped, so it will not be functional without a proper proxy + strictRequires: true + }, + // This will only work if "main" corresponds to the actual entry point that unwraps main.js + global: (global, t) => { + t.is(global.main, 'main'); + } +}; diff --git a/packages/commonjs/test/fixtures/function/preserve-modules/main.js b/packages/commonjs/test/fixtures/function/preserve-modules/main.js new file mode 100644 index 000000000..7696217a1 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/preserve-modules/main.js @@ -0,0 +1,4 @@ +global.main = 'main'; +console.log('main'); + +module.exports = 'main'; diff --git a/packages/commonjs/test/fixtures/function/reassign-module/main.js b/packages/commonjs/test/fixtures/function/reassign-module/main.js index 1e30b5021..17bbecf93 100644 --- a/packages/commonjs/test/fixtures/function/reassign-module/main.js +++ b/packages/commonjs/test/fixtures/function/reassign-module/main.js @@ -3,7 +3,7 @@ const property = require('./property'); const arrayPattern = require('./array-pattern.js'); const assignmentPattern = require('./assignment-pattern.js'); -t.deepEqual(identifier, {}); -t.deepEqual(property, {}); -t.deepEqual(arrayPattern, {}); -t.deepEqual(assignmentPattern, {}); +t.deepEqual(identifier, {}, 'identifier'); +t.deepEqual(property, {}, 'property'); +t.deepEqual(arrayPattern, {}, 'arrayPattern'); +t.deepEqual(assignmentPattern, {}, 'assignmentPattern'); diff --git a/packages/commonjs/test/fixtures/function/relative-external/_config.js b/packages/commonjs/test/fixtures/function/relative-external/_config.js new file mode 100755 index 000000000..620b6e4d4 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/relative-external/_config.js @@ -0,0 +1,7 @@ +module.exports = { + description: 'allows treating relative requires as external', + options: { + // This import needs to be relative to /test/helpers/util.js + external: ['../fixtures/function/relative-external/external.js'] + } +}; diff --git a/packages/commonjs/test/fixtures/function/relative-external/external.js b/packages/commonjs/test/fixtures/function/relative-external/external.js new file mode 100755 index 000000000..94ecacb72 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/relative-external/external.js @@ -0,0 +1 @@ +exports.foo = 'foo'; diff --git a/packages/commonjs/test/fixtures/function/relative-external/main.js b/packages/commonjs/test/fixtures/function/relative-external/main.js new file mode 100755 index 000000000..e495f65f1 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/relative-external/main.js @@ -0,0 +1,3 @@ +const { foo } = require('../fixtures/function/relative-external/external.js'); + +t.is(foo, 'foo'); diff --git a/packages/commonjs/test/fixtures/function/shorthand-require/_config.js b/packages/commonjs/test/fixtures/function/shorthand-require/_config.js new file mode 100755 index 000000000..00d2b9db7 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/shorthand-require/_config.js @@ -0,0 +1,3 @@ +module.exports = { + description: 'correctly replaces shorthand `require` property in object' +}; diff --git a/packages/commonjs/test/fixtures/samples/shorthand-require/main.js b/packages/commonjs/test/fixtures/function/shorthand-require/main.js similarity index 100% rename from packages/commonjs/test/fixtures/samples/shorthand-require/main.js rename to packages/commonjs/test/fixtures/function/shorthand-require/main.js diff --git a/packages/commonjs/test/fixtures/function/skips-dead-branches/main.js b/packages/commonjs/test/fixtures/function/skips-dead-branches/main.js index 0066d0550..03d934380 100644 --- a/packages/commonjs/test/fixtures/function/skips-dead-branches/main.js +++ b/packages/commonjs/test/fixtures/function/skips-dead-branches/main.js @@ -3,4 +3,9 @@ if ('development' === 'production') { require('./a.js'); } -module.exports = true ? require('./b.js') : require('./c.js'); +exports.conditionalTrue = true ? require('./b.js') : require('./c.js'); +exports.conditionalFalse = false ? require('./c.js') : require('./b.js'); +exports.logicalAnd1 = true && require('./b.js'); +exports.logicalAnd2 = false && require('./c.js'); +exports.logicalOr1 = true || require('./c.js'); +exports.logicalOr2 = false || require('./b.js'); diff --git a/packages/commonjs/test/fixtures/function/strict-requires-auto/_config.js b/packages/commonjs/test/fixtures/function/strict-requires-auto/_config.js new file mode 100644 index 000000000..8249fa044 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-auto/_config.js @@ -0,0 +1,7 @@ +module.exports = { + description: + 'automatically detects cycles and switches those modules to strict semantics for "auto"', + pluginOptions: { + strictRequires: 'auto' + } +}; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-auto/a-imports-b.js b/packages/commonjs/test/fixtures/function/strict-requires-auto/a-imports-b.js new file mode 100644 index 000000000..f3e51c119 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-auto/a-imports-b.js @@ -0,0 +1,2 @@ +exports.a = 'a'; +t.is(require('./b-imports-c').a, 'a'); diff --git a/packages/commonjs/test/fixtures/function/strict-requires-auto/b-imports-c.js b/packages/commonjs/test/fixtures/function/strict-requires-auto/b-imports-c.js new file mode 100644 index 000000000..53d3bc879 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-auto/b-imports-c.js @@ -0,0 +1 @@ +exports.a = require('./c-imports-a.js').a; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-auto/c-imports-a.js b/packages/commonjs/test/fixtures/function/strict-requires-auto/c-imports-a.js new file mode 100644 index 000000000..dc755f527 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-auto/c-imports-a.js @@ -0,0 +1 @@ +exports.a = require('./a-imports-b').a; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-auto/main.js b/packages/commonjs/test/fixtures/function/strict-requires-auto/main.js new file mode 100644 index 000000000..7aa9154de --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-auto/main.js @@ -0,0 +1 @@ +require('./a-imports-b'); diff --git a/packages/commonjs/test/fixtures/function/strict-requires-circular/_config.js b/packages/commonjs/test/fixtures/function/strict-requires-circular/_config.js new file mode 100644 index 000000000..04efeeef1 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-circular/_config.js @@ -0,0 +1,6 @@ +module.exports = { + description: 'handles circular dependencies with strict require semantic', + pluginOptions: { + strictRequires: true + } +}; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-circular/main.js b/packages/commonjs/test/fixtures/function/strict-requires-circular/main.js new file mode 100644 index 000000000..b49deee73 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-circular/main.js @@ -0,0 +1,2 @@ +exports.foo = 'foo'; +t.is(require('./other.js').foo, 'foo'); diff --git a/packages/commonjs/test/fixtures/function/strict-requires-circular/other.js b/packages/commonjs/test/fixtures/function/strict-requires-circular/other.js new file mode 100644 index 000000000..fbe0d2a97 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-circular/other.js @@ -0,0 +1 @@ +exports.foo = require('./main.js').foo; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-cycle-detection/_config.js b/packages/commonjs/test/fixtures/function/strict-requires-cycle-detection/_config.js new file mode 100644 index 000000000..52f7e94ef --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-cycle-detection/_config.js @@ -0,0 +1,3 @@ +module.exports = { + description: 'automatically detects cycles and switches those modules to strict semantics' +}; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-cycle-detection/a-imports-b.js b/packages/commonjs/test/fixtures/function/strict-requires-cycle-detection/a-imports-b.js new file mode 100644 index 000000000..f3e51c119 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-cycle-detection/a-imports-b.js @@ -0,0 +1,2 @@ +exports.a = 'a'; +t.is(require('./b-imports-c').a, 'a'); diff --git a/packages/commonjs/test/fixtures/function/strict-requires-cycle-detection/b-imports-c.js b/packages/commonjs/test/fixtures/function/strict-requires-cycle-detection/b-imports-c.js new file mode 100644 index 000000000..53d3bc879 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-cycle-detection/b-imports-c.js @@ -0,0 +1 @@ +exports.a = require('./c-imports-a.js').a; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-cycle-detection/c-imports-a.js b/packages/commonjs/test/fixtures/function/strict-requires-cycle-detection/c-imports-a.js new file mode 100644 index 000000000..dc755f527 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-cycle-detection/c-imports-a.js @@ -0,0 +1 @@ +exports.a = require('./a-imports-b').a; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-cycle-detection/main.js b/packages/commonjs/test/fixtures/function/strict-requires-cycle-detection/main.js new file mode 100644 index 000000000..7aa9154de --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-cycle-detection/main.js @@ -0,0 +1 @@ +require('./a-imports-b'); diff --git a/packages/commonjs/test/fixtures/function/strict-requires-debug-none/_config.js b/packages/commonjs/test/fixtures/function/strict-requires-debug-none/_config.js new file mode 100644 index 000000000..d570e0882 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-debug-none/_config.js @@ -0,0 +1,23 @@ +const assert = require('assert'); + +const warnings = []; + +module.exports = { + description: 'has correct debug output when there are no cycles', + pluginOptions: { + strictRequires: 'debug' + }, + options: { + onwarn(warning) { + if (warning.pluginCode !== 'WRAPPED_IDS') { + throw new Error(`Unexpected warning ${warning.code}: ${warning.message}`); + } + warnings.push(warning); + } + }, + exports() { + assert.strictEqual(warnings.length, 1); + assert.deepStrictEqual(warnings[0].ids, []); + assert.strictEqual(warnings[0].message, 'The commonjs plugin did not wrap any files.'); + } +}; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-debug-none/main.js b/packages/commonjs/test/fixtures/function/strict-requires-debug-none/main.js new file mode 100644 index 000000000..cb1c2c01e --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-debug-none/main.js @@ -0,0 +1 @@ +module.exports = 'bar'; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-debug/_config.js b/packages/commonjs/test/fixtures/function/strict-requires-debug/_config.js new file mode 100644 index 000000000..1845e2eb9 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-debug/_config.js @@ -0,0 +1,29 @@ +const assert = require('assert'); +const path = require('path'); + +const warnings = []; + +module.exports = { + description: + 'automatically detects cycles and switches those modules to strict semantics for "debug"', + pluginOptions: { + strictRequires: 'debug' + }, + options: { + onwarn(warning) { + if (warning.code === 'CIRCULAR_DEPENDENCY') return; + if (warning.pluginCode !== 'WRAPPED_IDS') { + throw new Error(`Unexpected warning ${warning.code}: ${warning.message}`); + } + warnings.push(warning); + } + }, + exports() { + assert.strictEqual(warnings.length, 1); + assert.deepStrictEqual(warnings[0].ids, [ + path.join(__dirname, 'a-imports-b.js'), + path.join(__dirname, 'b-imports-c.js'), + path.join(__dirname, 'c-imports-a.js') + ]); + } +}; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-debug/a-imports-b.js b/packages/commonjs/test/fixtures/function/strict-requires-debug/a-imports-b.js new file mode 100644 index 000000000..f3e51c119 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-debug/a-imports-b.js @@ -0,0 +1,2 @@ +exports.a = 'a'; +t.is(require('./b-imports-c').a, 'a'); diff --git a/packages/commonjs/test/fixtures/function/strict-requires-debug/b-imports-c.js b/packages/commonjs/test/fixtures/function/strict-requires-debug/b-imports-c.js new file mode 100644 index 000000000..53d3bc879 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-debug/b-imports-c.js @@ -0,0 +1 @@ +exports.a = require('./c-imports-a.js').a; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-debug/c-imports-a.js b/packages/commonjs/test/fixtures/function/strict-requires-debug/c-imports-a.js new file mode 100644 index 000000000..dc755f527 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-debug/c-imports-a.js @@ -0,0 +1 @@ +exports.a = require('./a-imports-b').a; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-debug/main.js b/packages/commonjs/test/fixtures/function/strict-requires-debug/main.js new file mode 100644 index 000000000..7aa9154de --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-debug/main.js @@ -0,0 +1 @@ +require('./a-imports-b'); diff --git a/packages/commonjs/test/fixtures/function/strict-requires-detect-conditionals/_config.js b/packages/commonjs/test/fixtures/function/strict-requires-detect-conditionals/_config.js new file mode 100644 index 000000000..d926d0b82 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-detect-conditionals/_config.js @@ -0,0 +1,3 @@ +module.exports = { + description: 'automatically detects requires nested in conditionals' +}; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-detect-conditionals/hoisted.js b/packages/commonjs/test/fixtures/function/strict-requires-detect-conditionals/hoisted.js new file mode 100644 index 000000000..705851f9f --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-detect-conditionals/hoisted.js @@ -0,0 +1 @@ +module.exports = 'this should be top-level'; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-detect-conditionals/main.js b/packages/commonjs/test/fixtures/function/strict-requires-detect-conditionals/main.js new file mode 100644 index 000000000..b7fc6ea58 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-detect-conditionals/main.js @@ -0,0 +1,44 @@ +/* eslint-disable global-require */ +global.false = false; +global.true = true; + +if (global.false) { + require('./throws.js'); +} + +if (global.true) { + /* do nothing */ +} else { + require('./throws.js'); +} + +const conditionalFalse = global.false ? require('./throws.js') : null; +const conditionalTrue = global.true ? null : require('./throws.js'); + +const logicalAnd = global.false && require('./throws.js'); +const logicalOr = global.true || require('./throws.js'); + +function requireFunctionDeclaration() { + require('./throws.js'); +} + +const requireFunctionExpression = function () { + require('./throws.js'); +}; + +const requireArrowFunction = () => require('./throws.js'); + +if (global.false) { + requireFunctionDeclaration(); + requireFunctionExpression(); + requireArrowFunction(); +} + +// These should not cause wrapping +t.is( + (function () { + return require('./hoisted.js'); + })(), + 'this should be top-level' +); +t.is((() => require('./hoisted.js'))(), 'this should be top-level'); diff --git a/packages/commonjs/test/fixtures/function/strict-requires-detect-conditionals/throws.js b/packages/commonjs/test/fixtures/function/strict-requires-detect-conditionals/throws.js new file mode 100644 index 000000000..d11e026e6 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-detect-conditionals/throws.js @@ -0,0 +1 @@ +throw new Error('This should never be executed or imported'); diff --git a/packages/commonjs/test/fixtures/function/strict-requires-entry-node-resolve/_config.js b/packages/commonjs/test/fixtures/function/strict-requires-entry-node-resolve/_config.js new file mode 100644 index 000000000..327d47b1a --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-entry-node-resolve/_config.js @@ -0,0 +1,31 @@ +const assert = require('assert'); + +const { nodeResolve } = require('@rollup/plugin-node-resolve'); + +module.exports = { + description: + 'strict require semantic modules can be entry points when the node-resolve plugin is used', + pluginOptions: { + strictRequires: true + }, + options: { + plugins: [ + { + name: 'before-node', + buildStart({ plugins }) { + assert.deepStrictEqual( + plugins.map((plugin) => plugin.name), + ['commonjs--resolver', 'before-node', 'node-resolve', 'after-node', 'commonjs'] + ); + } + }, + nodeResolve(), + { + name: 'after-node' + } + ] + }, + exports(exports) { + assert.deepStrictEqual(exports, { foo: 'foo' }); + } +}; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-entry-node-resolve/main.js b/packages/commonjs/test/fixtures/function/strict-requires-entry-node-resolve/main.js new file mode 100644 index 000000000..94ecacb72 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-entry-node-resolve/main.js @@ -0,0 +1 @@ +exports.foo = 'foo'; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-exportmode-exports/_config.js b/packages/commonjs/test/fixtures/function/strict-requires-exportmode-exports/_config.js new file mode 100644 index 000000000..350658699 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-exportmode-exports/_config.js @@ -0,0 +1,6 @@ +module.exports = { + description: 'supports using function wrappers for modules for export mode "exports"', + pluginOptions: { + strictRequires: ['fixtures/function/strict-requires-exportmode-exports/*E*.js'] + } +}; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-exportmode-exports/assignExports.js b/packages/commonjs/test/fixtures/function/strict-requires-exportmode-exports/assignExports.js new file mode 100644 index 000000000..8c69cda39 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-exportmode-exports/assignExports.js @@ -0,0 +1,3 @@ +exports.foo = 'foo'; +module.exports.bar = 'bar'; +global.hasAssignExportsRun = true; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-exportmode-exports/compiledEsm.js b/packages/commonjs/test/fixtures/function/strict-requires-exportmode-exports/compiledEsm.js new file mode 100644 index 000000000..b011461c8 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-exportmode-exports/compiledEsm.js @@ -0,0 +1,4 @@ +exports.__esModule = true; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.foo = 'foo'; +global.hasCompiledEsmRun = true; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-exportmode-exports/main.js b/packages/commonjs/test/fixtures/function/strict-requires-exportmode-exports/main.js new file mode 100644 index 000000000..c8523a512 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-exportmode-exports/main.js @@ -0,0 +1,17 @@ +t.is(global.hasAssignExportsRun, undefined, 'before require'); +t.deepEqual(require('./assignExports.js'), { foo: 'foo', bar: 'bar' }); + +t.is(global.hasAssignExportsRun, true, 'after require'); +delete global.hasAssignExportsRun; + +t.is(global.hasCompiledEsmRun, undefined, 'before require'); +t.deepEqual(require('./compiledEsm.js'), { foo: 'foo', __esModule: true }); + +t.is(global.hasCompiledEsmRun, true, 'after require'); +delete global.hasCompiledEsmRun; + +t.is(global.hasWrappedExportsRun, undefined, 'before require'); +t.deepEqual(require('./wrappedExports.js'), { foo: 'foo' }); + +t.is(global.hasWrappedExportsRun, true, 'after require'); +delete global.hasWrappedExportsRun; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-exportmode-exports/wrappedExports.js b/packages/commonjs/test/fixtures/function/strict-requires-exportmode-exports/wrappedExports.js new file mode 100644 index 000000000..11c17d4cc --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-exportmode-exports/wrappedExports.js @@ -0,0 +1,4 @@ +exports.foo = 'foo'; +exports = {}; +exports.bar = 'bar'; +global.hasWrappedExportsRun = true; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-exportmode-module/_config.js b/packages/commonjs/test/fixtures/function/strict-requires-exportmode-module/_config.js new file mode 100644 index 000000000..6ca355ff8 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-exportmode-module/_config.js @@ -0,0 +1,6 @@ +module.exports = { + description: 'supports using function wrappers for modules for export mode "module"', + pluginOptions: { + strictRequires: ['fixtures/function/strict-requires-exportmode-module/*E*.js'] + } +}; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-exportmode-module/assignModuleAndExports.js b/packages/commonjs/test/fixtures/function/strict-requires-exportmode-module/assignModuleAndExports.js new file mode 100644 index 000000000..887e1707f --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-exportmode-module/assignModuleAndExports.js @@ -0,0 +1,3 @@ +module.exports = { foo: 'foo' }; +module.exports.bar = 'bar'; +global.hasAssignModuleAndExportsRun = true; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-exportmode-module/assignModuleExports.js b/packages/commonjs/test/fixtures/function/strict-requires-exportmode-module/assignModuleExports.js new file mode 100644 index 000000000..654fd144a --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-exportmode-module/assignModuleExports.js @@ -0,0 +1,6 @@ +if (Math.random() > 0.5) { + module.exports = { foo: 'foo' }; +} else { + module.exports = { foo: 'foo' }; +} +global.hasAssignModuleExportsRun = true; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-exportmode-module/main.js b/packages/commonjs/test/fixtures/function/strict-requires-exportmode-module/main.js new file mode 100644 index 000000000..3e28a77a2 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-exportmode-module/main.js @@ -0,0 +1,17 @@ +t.is(global.hasAssignModuleExportsRun, undefined, 'before require'); +t.is(require('./assignModuleExports.js').foo, 'foo'); + +t.is(global.hasAssignModuleExportsRun, true, 'after require'); +delete global.hasAssignModuleExportsRun; + +t.is(global.hasAssignModuleAndExportsRun, undefined, 'before require'); +t.is(require('./assignModuleAndExports.js').foo, 'foo'); + +t.is(global.hasAssignModuleAndExportsRun, true, 'after require'); +delete global.hasAssignModuleAndExportsRun; + +t.is(global.hasWrappedModuleExportsRun, undefined, 'before require'); +t.is(require('./wrappedModuleExports.js').foo, 'foo'); + +t.is(global.hasWrappedModuleExportsRun, true, 'after require'); +delete global.hasWrappedModuleExportsRun; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-exportmode-module/wrappedModuleExports.js b/packages/commonjs/test/fixtures/function/strict-requires-exportmode-module/wrappedModuleExports.js new file mode 100644 index 000000000..00b083b31 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-exportmode-module/wrappedModuleExports.js @@ -0,0 +1,3 @@ +module.exports = { foo: 'foo' }; +exports = {}; +global.hasWrappedModuleExportsRun = true; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-exportmode-replace/_config.js b/packages/commonjs/test/fixtures/function/strict-requires-exportmode-replace/_config.js new file mode 100644 index 000000000..1766448d1 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-exportmode-replace/_config.js @@ -0,0 +1,6 @@ +module.exports = { + description: 'supports using function wrappers for modules for export mode "replace"', + pluginOptions: { + strictRequires: ['fixtures/function/strict-requires-exportmode-replace/*E*.js'] + } +}; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-exportmode-replace/main.js b/packages/commonjs/test/fixtures/function/strict-requires-exportmode-replace/main.js new file mode 100644 index 000000000..4b6423503 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-exportmode-replace/main.js @@ -0,0 +1,5 @@ +t.is(global.hasReplaceModuleExportsRun, undefined, 'before require'); +t.is(require('./replaceModuleExports.js').foo, 'foo'); + +t.is(global.hasReplaceModuleExportsRun, true, 'after require'); +delete global.hasReplaceModuleExportsRun; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-exportmode-replace/replaceModuleExports.js b/packages/commonjs/test/fixtures/function/strict-requires-exportmode-replace/replaceModuleExports.js new file mode 100644 index 000000000..07a8f2e9a --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-exportmode-replace/replaceModuleExports.js @@ -0,0 +1,2 @@ +module.exports = { foo: 'foo' }; +global.hasReplaceModuleExportsRun = true; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-external/_config.js b/packages/commonjs/test/fixtures/function/strict-requires-external/_config.js new file mode 100644 index 000000000..d16da2049 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-external/_config.js @@ -0,0 +1,18 @@ +module.exports = { + description: 'still does not wrap external dependencies with strict require semantic', + pluginOptions: { + strictRequires: true + }, + options: { + plugins: [ + { + resolveId(source) { + if (source === 'external') { + return { id: 'external', external: true }; + } + return null; + } + } + ] + } +}; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-external/main.js b/packages/commonjs/test/fixtures/function/strict-requires-external/main.js new file mode 100644 index 000000000..a657096b0 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-external/main.js @@ -0,0 +1 @@ +t.is(require('external').message, 'it works'); diff --git a/packages/commonjs/test/fixtures/function/strict-requires-external/other.js b/packages/commonjs/test/fixtures/function/strict-requires-external/other.js new file mode 100644 index 000000000..fbe0d2a97 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-external/other.js @@ -0,0 +1 @@ +exports.foo = require('./main.js').foo; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-file-without-module-type/_config.js b/packages/commonjs/test/fixtures/function/strict-requires-file-without-module-type/_config.js new file mode 100644 index 000000000..aa3d115c7 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-file-without-module-type/_config.js @@ -0,0 +1,7 @@ +module.exports = { + description: + 'identifies files without module features as commonjs if they are required by another file', + pluginOptions: { + strictRequires: true + } +}; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-file-without-module-type/error.js b/packages/commonjs/test/fixtures/function/strict-requires-file-without-module-type/error.js new file mode 100644 index 000000000..85dbb8dd0 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-file-without-module-type/error.js @@ -0,0 +1 @@ +throw new Error('FAIL'); diff --git a/packages/commonjs/test/fixtures/function/strict-requires-file-without-module-type/main.js b/packages/commonjs/test/fixtures/function/strict-requires-file-without-module-type/main.js new file mode 100644 index 000000000..8e5f0208b --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-file-without-module-type/main.js @@ -0,0 +1,4 @@ +global.null = 0; + +// eslint-disable-next-line global-require +t.is(global.null && require('./error.js'), 0); diff --git a/packages/commonjs/test/fixtures/function/strict-requires-from-esm/_config.js b/packages/commonjs/test/fixtures/function/strict-requires-from-esm/_config.js new file mode 100644 index 000000000..f445b5c88 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-from-esm/_config.js @@ -0,0 +1,6 @@ +module.exports = { + description: 'handles importing wrapped modules from ESM', + pluginOptions: { + strictRequires: ['fixtures/function/strict-requires-from-esm/strict.js'] + } +}; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-from-esm/dep.js b/packages/commonjs/test/fixtures/function/strict-requires-from-esm/dep.js new file mode 100644 index 000000000..242f91140 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-from-esm/dep.js @@ -0,0 +1 @@ +t.is(require('./strict').foo, 'foo'); diff --git a/packages/commonjs/test/fixtures/function/strict-requires-from-esm/main.js b/packages/commonjs/test/fixtures/function/strict-requires-from-esm/main.js new file mode 100644 index 000000000..95d8d3beb --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-from-esm/main.js @@ -0,0 +1,4 @@ +import { foo } from './strict.js'; +import './dep.js'; + +t.is(foo, 'foo'); diff --git a/packages/commonjs/test/fixtures/function/strict-requires-from-esm/strict.js b/packages/commonjs/test/fixtures/function/strict-requires-from-esm/strict.js new file mode 100644 index 000000000..94ecacb72 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-from-esm/strict.js @@ -0,0 +1 @@ +exports.foo = 'foo'; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-mixed-esm/_config.js b/packages/commonjs/test/fixtures/function/strict-requires-mixed-esm/_config.js new file mode 100644 index 000000000..033c7379f --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-mixed-esm/_config.js @@ -0,0 +1,12 @@ +const { nodeResolve } = require('@rollup/plugin-node-resolve'); + +module.exports = { + description: 'supports strictRequires with mixed ESM', + pluginOptions: { + strictRequires: true, + transformMixedEsModules: true + }, + options: { + plugins: [nodeResolve()] + } +}; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-mixed-esm/import.js b/packages/commonjs/test/fixtures/function/strict-requires-mixed-esm/import.js new file mode 100644 index 000000000..94ecacb72 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-mixed-esm/import.js @@ -0,0 +1 @@ +exports.foo = 'foo'; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-mixed-esm/main.js b/packages/commonjs/test/fixtures/function/strict-requires-mixed-esm/main.js new file mode 100644 index 000000000..89c777a42 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-mixed-esm/main.js @@ -0,0 +1,6 @@ +import esm from './import.js'; + +const cjs = require('./require.js'); + +t.is(esm.foo, 'foo'); +t.is(cjs.foo, 'foo'); diff --git a/packages/commonjs/test/fixtures/function/strict-requires-mixed-esm/require.js b/packages/commonjs/test/fixtures/function/strict-requires-mixed-esm/require.js new file mode 100644 index 000000000..94ecacb72 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-mixed-esm/require.js @@ -0,0 +1 @@ +exports.foo = 'foo'; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-multiple-entry/_config.js b/packages/commonjs/test/fixtures/function/strict-requires-multiple-entry/_config.js new file mode 100644 index 000000000..6e3b65ee2 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-multiple-entry/_config.js @@ -0,0 +1,20 @@ +const assert = require('assert'); + +module.exports = { + description: 'strict require semantic modules can be entry points', + options: { + input: [ + 'fixtures/function/strict-requires-multiple-entry/main.js', + 'fixtures/function/strict-requires-multiple-entry/other.js' + ], + output: { + chunkFileNames: 'generated-[name].js' + } + }, + pluginOptions: { + strictRequires: ['fixtures/function/strict-requires-multiple-entry/main.js'] + }, + exports(exports) { + assert.deepStrictEqual(exports, { foo: 'foo' }); + } +}; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-multiple-entry/main.js b/packages/commonjs/test/fixtures/function/strict-requires-multiple-entry/main.js new file mode 100644 index 000000000..94ecacb72 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-multiple-entry/main.js @@ -0,0 +1 @@ +exports.foo = 'foo'; diff --git a/packages/commonjs/test/fixtures/function/strict-requires-multiple-entry/other.js b/packages/commonjs/test/fixtures/function/strict-requires-multiple-entry/other.js new file mode 100644 index 000000000..44c7e1527 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/strict-requires-multiple-entry/other.js @@ -0,0 +1 @@ +t.is(require('./main.js').foo, 'foo'); diff --git a/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-default/_config.js b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-default/_config.js new file mode 100644 index 000000000..8f05f508a --- /dev/null +++ b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-default/_config.js @@ -0,0 +1,3 @@ +module.exports = { + description: 'creates the correct exports from CJS module re-exporting a transpiled ES module', +}; diff --git a/packages/commonjs/test/fixtures/samples/dynamic-require-double-wrap/submodule.js b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-default/dep.js similarity index 67% rename from packages/commonjs/test/fixtures/samples/dynamic-require-double-wrap/submodule.js rename to packages/commonjs/test/fixtures/function/transpiled-esm-reexported-default/dep.js index 837892314..fb5eac450 100644 --- a/packages/commonjs/test/fixtures/samples/dynamic-require-double-wrap/submodule.js +++ b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-default/dep.js @@ -1,3 +1,2 @@ Object.defineProperty(exports, '__esModule', { value: true }); - -module.exports = 'submodule'; +exports.default = 'default'; diff --git a/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-default/main.js b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-default/main.js new file mode 100644 index 000000000..b84f4f5e7 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-default/main.js @@ -0,0 +1,3 @@ +import dep from './proxy'; + +t.is(dep, 'default'); diff --git a/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-default/proxy.js b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-default/proxy.js new file mode 100644 index 000000000..4e05226db --- /dev/null +++ b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-default/proxy.js @@ -0,0 +1 @@ +module.exports = require('./dep'); diff --git a/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-default/_config.js b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-default/_config.js new file mode 100644 index 000000000..8f05f508a --- /dev/null +++ b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-default/_config.js @@ -0,0 +1,3 @@ +module.exports = { + description: 'creates the correct exports from CJS module re-exporting a transpiled ES module', +}; diff --git a/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-default/entry.js b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-default/entry.js new file mode 100644 index 000000000..fb5eac450 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-default/entry.js @@ -0,0 +1,2 @@ +Object.defineProperty(exports, '__esModule', { value: true }); +exports.default = 'default'; diff --git a/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-default/main.js b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-default/main.js new file mode 100644 index 000000000..0e8346288 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-default/main.js @@ -0,0 +1,3 @@ +import * as entry from './proxy'; + +t.deepEqual(entry, { default: 'default' }); diff --git a/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-default/proxy.js b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-default/proxy.js new file mode 100644 index 000000000..e9fb5b056 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-default/proxy.js @@ -0,0 +1 @@ +module.exports = require('./entry'); diff --git a/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-mixed/_config.js b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-mixed/_config.js new file mode 100644 index 000000000..8f05f508a --- /dev/null +++ b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-mixed/_config.js @@ -0,0 +1,3 @@ +module.exports = { + description: 'creates the correct exports from CJS module re-exporting a transpiled ES module', +}; diff --git a/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-mixed/entry.js b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-mixed/entry.js new file mode 100644 index 000000000..8b154e2ff --- /dev/null +++ b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-mixed/entry.js @@ -0,0 +1,3 @@ +Object.defineProperty(exports, '__esModule', { value: true }); +exports.default = 'default'; +exports.named = 'named'; diff --git a/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-mixed/main.js b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-mixed/main.js new file mode 100644 index 000000000..c89f3ba76 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-mixed/main.js @@ -0,0 +1,3 @@ +import * as entry from './proxy'; + +t.deepEqual(entry, { default: 'default', named: 'named' }); diff --git a/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-mixed/proxy.js b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-mixed/proxy.js new file mode 100644 index 000000000..e9fb5b056 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-mixed/proxy.js @@ -0,0 +1 @@ +module.exports = require('./entry'); diff --git a/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-named/_config.js b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-named/_config.js new file mode 100644 index 000000000..8f05f508a --- /dev/null +++ b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-named/_config.js @@ -0,0 +1,3 @@ +module.exports = { + description: 'creates the correct exports from CJS module re-exporting a transpiled ES module', +}; diff --git a/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-named/entry.js b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-named/entry.js new file mode 100644 index 000000000..51016a8e7 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-named/entry.js @@ -0,0 +1,2 @@ +Object.defineProperty(exports, '__esModule', { value: true }); +exports.named = 'named'; diff --git a/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-named/main.js b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-named/main.js new file mode 100644 index 000000000..70f090348 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-named/main.js @@ -0,0 +1,8 @@ +import * as entry from './proxy'; + +t.deepEqual(entry, { + default: { + named: 'named', + }, + named: 'named' +}); diff --git a/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-named/proxy.js b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-named/proxy.js new file mode 100644 index 000000000..e9fb5b056 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-entry-named/proxy.js @@ -0,0 +1 @@ +module.exports = require('./entry'); diff --git a/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-mixed/_config.js b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-mixed/_config.js new file mode 100644 index 000000000..8f05f508a --- /dev/null +++ b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-mixed/_config.js @@ -0,0 +1,3 @@ +module.exports = { + description: 'creates the correct exports from CJS module re-exporting a transpiled ES module', +}; diff --git a/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-mixed/dep.js b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-mixed/dep.js new file mode 100644 index 000000000..1522ddc2b --- /dev/null +++ b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-mixed/dep.js @@ -0,0 +1,3 @@ +Object.defineProperty(exports, '__esModule', { value: true }); +exports.named = 'named'; +exports.default = 'default'; diff --git a/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-mixed/main.js b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-mixed/main.js new file mode 100644 index 000000000..3209dd8a0 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-mixed/main.js @@ -0,0 +1,4 @@ +import dep, { named } from './proxy'; + +t.is(dep, 'default'); +t.is(named, 'named'); diff --git a/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-mixed/proxy.js b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-mixed/proxy.js new file mode 100644 index 000000000..4e05226db --- /dev/null +++ b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-mixed/proxy.js @@ -0,0 +1 @@ +module.exports = require('./dep'); diff --git a/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-named/_config.js b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-named/_config.js new file mode 100644 index 000000000..8f05f508a --- /dev/null +++ b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-named/_config.js @@ -0,0 +1,3 @@ +module.exports = { + description: 'creates the correct exports from CJS module re-exporting a transpiled ES module', +}; diff --git a/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-named/dep.js b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-named/dep.js new file mode 100644 index 000000000..51016a8e7 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-named/dep.js @@ -0,0 +1,2 @@ +Object.defineProperty(exports, '__esModule', { value: true }); +exports.named = 'named'; diff --git a/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-named/main.js b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-named/main.js new file mode 100644 index 000000000..070b383ed --- /dev/null +++ b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-named/main.js @@ -0,0 +1,3 @@ +import { named } from './proxy'; + +t.is(named, 'named'); diff --git a/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-named/proxy.js b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-named/proxy.js new file mode 100644 index 000000000..4e05226db --- /dev/null +++ b/packages/commonjs/test/fixtures/function/transpiled-esm-reexported-named/proxy.js @@ -0,0 +1 @@ +module.exports = require('./dep'); diff --git a/packages/commonjs/test/fixtures/function/try-catch-internal/_config.js b/packages/commonjs/test/fixtures/function/try-catch-internal/_config.js new file mode 100644 index 000000000..fec6f7626 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/try-catch-internal/_config.js @@ -0,0 +1,7 @@ +module.exports = { + description: + 'inlines internal require statements in try-catch blocks even when try-catch is ignored', + pluginOptions: { + ignoreTryCatch: true + } +}; diff --git a/packages/commonjs/test/fixtures/function/try-catch-internal/dep.js b/packages/commonjs/test/fixtures/function/try-catch-internal/dep.js new file mode 100644 index 000000000..94ecacb72 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/try-catch-internal/dep.js @@ -0,0 +1 @@ +exports.foo = 'foo'; diff --git a/packages/commonjs/test/fixtures/function/try-catch-internal/main.js b/packages/commonjs/test/fixtures/function/try-catch-internal/main.js new file mode 100644 index 000000000..5d3875d55 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/try-catch-internal/main.js @@ -0,0 +1,13 @@ +/* eslint-disable global-require */ + +try { + t.is(require('./dep.js').foo, 'foo'); +} catch (err) { + throw new Error(`Could not require: ${err}`); +} + +try { + require('./throws.js'); +} catch (err) { + t.is(err.message, 'Expected error'); +} diff --git a/packages/commonjs/test/fixtures/function/try-catch-internal/throws.js b/packages/commonjs/test/fixtures/function/try-catch-internal/throws.js new file mode 100644 index 000000000..dcf80a10e --- /dev/null +++ b/packages/commonjs/test/fixtures/function/try-catch-internal/throws.js @@ -0,0 +1 @@ +throw new Error('Expected error'); diff --git a/packages/commonjs/test/fixtures/function/try-catch-remove/_config.js b/packages/commonjs/test/fixtures/function/try-catch-remove/_config.js new file mode 100644 index 000000000..c7d4363f4 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/try-catch-remove/_config.js @@ -0,0 +1,5 @@ +module.exports = { + pluginOptions: { + ignoreTryCatch: (id) => (id === 'uninstalled-external-module' ? 'remove' : false) + } +}; diff --git a/packages/commonjs/test/fixtures/form/try-catch-remove/input.js b/packages/commonjs/test/fixtures/function/try-catch-remove/main.js similarity index 56% rename from packages/commonjs/test/fixtures/form/try-catch-remove/input.js rename to packages/commonjs/test/fixtures/function/try-catch-remove/main.js index 1aae6b291..fa5fa693e 100644 --- a/packages/commonjs/test/fixtures/form/try-catch-remove/input.js +++ b/packages/commonjs/test/fixtures/function/try-catch-remove/main.js @@ -3,5 +3,5 @@ try { require('uninstalled-external-module'); } catch (ignored) { - /* ignore */ + throw new Error('This should no longer be reached as the require is removed.'); } diff --git a/packages/commonjs/test/fixtures/function/typeof-module-require/foo.js b/packages/commonjs/test/fixtures/function/typeof-module-require/foo.js index 8ddba70a6..8efe5218f 100644 --- a/packages/commonjs/test/fixtures/function/typeof-module-require/foo.js +++ b/packages/commonjs/test/fixtures/function/typeof-module-require/foo.js @@ -1,5 +1,5 @@ if (typeof module.require === 'function' && module.require) { - module.exports = 1; + module.exports = 'require detected'; } else { - module.exports = 2; + module.exports = 'could not detect require'; } diff --git a/packages/commonjs/test/fixtures/function/typeof-module-require/main.js b/packages/commonjs/test/fixtures/function/typeof-module-require/main.js index 6f32f015a..57de0e64f 100644 --- a/packages/commonjs/test/fixtures/function/typeof-module-require/main.js +++ b/packages/commonjs/test/fixtures/function/typeof-module-require/main.js @@ -1,3 +1,3 @@ import foo from './foo.js'; -t.is(foo, 1); +t.is(foo, 'require detected'); diff --git a/packages/commonjs/test/fixtures/function/unresolved-dependencies/_config.js b/packages/commonjs/test/fixtures/function/unresolved-dependencies/_config.js index a7daf279e..72b184cf6 100644 --- a/packages/commonjs/test/fixtures/function/unresolved-dependencies/_config.js +++ b/packages/commonjs/test/fixtures/function/unresolved-dependencies/_config.js @@ -11,9 +11,12 @@ module.exports = { plugins: [ { buildEnd() { - assert.strictEqual(warnings.length, 1); - assert.strictEqual(warnings[0].code, 'UNRESOLVED_IMPORT'); - assert.strictEqual(warnings[0].source, 'path'); + assert.deepStrictEqual( + warnings.map(({ code, source }) => { + return { code, source }; + }), + [{ code: 'UNRESOLVED_IMPORT', source: 'path' }] + ); } } ] diff --git a/packages/commonjs/test/fixtures/function/warn-this-resolve-without-options/_config.js b/packages/commonjs/test/fixtures/function/warn-this-resolve-without-options/_config.js new file mode 100644 index 000000000..a79b74cb8 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/warn-this-resolve-without-options/_config.js @@ -0,0 +1,29 @@ +const assert = require('assert'); + +const warnings = []; + +module.exports = { + description: 'Warns when another plugin uses this.resolve without forwarding options', + options: { + onwarn(warning) { + warnings.push(warning); + }, + plugins: [ + { + name: 'test', + resolveId(source, importer) { + return this.resolve(source, importer, { skipSelf: true }); + }, + buildEnd() { + assert.strictEqual(warnings.length, 1); + assert.strictEqual( + warnings[0].message, + 'It appears a plugin has implemented a "resolveId" hook that uses "this.resolve" without forwarding the third "options" parameter of "resolveId". This is problematic as it can lead to wrong module resolutions especially for the node-resolve plugin and in certain cases cause early exit errors for the commonjs plugin.\nIn rare cases, this warning can appear if the same file is both imported and required from the same mixed ES/CommonJS module, in which case it can be ignored.' + ); + assert.strictEqual(warnings[0].pluginCode, 'THIS_RESOLVE_WITHOUT_OPTIONS'); + assert.strictEqual(warnings[0].url, 'https://rollupjs.org/guide/en/#resolveid'); + } + } + ] + } +}; diff --git a/packages/commonjs/test/fixtures/function/warn-this-resolve-without-options/foo.js b/packages/commonjs/test/fixtures/function/warn-this-resolve-without-options/foo.js new file mode 100644 index 000000000..ce0fffb75 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/warn-this-resolve-without-options/foo.js @@ -0,0 +1 @@ +module.exports = 21; diff --git a/packages/commonjs/test/fixtures/function/warn-this-resolve-without-options/main.js b/packages/commonjs/test/fixtures/function/warn-this-resolve-without-options/main.js new file mode 100644 index 000000000..ba12948f6 --- /dev/null +++ b/packages/commonjs/test/fixtures/function/warn-this-resolve-without-options/main.js @@ -0,0 +1,3 @@ +const foo = require('./foo'); + +module.exports = foo * 2; diff --git a/packages/commonjs/test/fixtures/samples/caching/rollupWorker.js b/packages/commonjs/test/fixtures/samples/caching/rollupWorker.js index 2f80d6d4e..eb7e39ea6 100644 --- a/packages/commonjs/test/fixtures/samples/caching/rollupWorker.js +++ b/packages/commonjs/test/fixtures/samples/caching/rollupWorker.js @@ -2,7 +2,7 @@ const { workerData, parentPort } = require('worker_threads'); const { rollup } = require('rollup'); -const commonjs = require('../../../../dist/index'); +const commonjs = require('../../../..'); const { getCodeFromBundle } = require('../../../helpers/util'); generateCode(workerData); diff --git a/packages/commonjs/test/fixtures/samples/cjs-with-esm-property/lib.js b/packages/commonjs/test/fixtures/samples/cjs-with-esm-property/lib.js index 657003611..46d1bf449 100644 --- a/packages/commonjs/test/fixtures/samples/cjs-with-esm-property/lib.js +++ b/packages/commonjs/test/fixtures/samples/cjs-with-esm-property/lib.js @@ -1,4 +1,6 @@ -module.exports = { - "default": () => { console.log('beep') }, - __esModule: true -}; \ No newline at end of file +module.exports = { + default: () => { + t.is('beep', 'beep'); + }, + __esModule: true +}; diff --git a/packages/commonjs/test/fixtures/samples/cjs-with-esm-property/main.js b/packages/commonjs/test/fixtures/samples/cjs-with-esm-property/main.js index aed3937f1..e97281701 100644 --- a/packages/commonjs/test/fixtures/samples/cjs-with-esm-property/main.js +++ b/packages/commonjs/test/fixtures/samples/cjs-with-esm-property/main.js @@ -1,3 +1,3 @@ -import fn from './lib' +import fn from './lib'; -fn() \ No newline at end of file +fn(); diff --git a/packages/commonjs/test/fixtures/samples/dynamic-require-different-loader/main.js b/packages/commonjs/test/fixtures/samples/dynamic-require-different-loader/main.js deleted file mode 100755 index 8adb18ef2..000000000 --- a/packages/commonjs/test/fixtures/samples/dynamic-require-different-loader/main.js +++ /dev/null @@ -1 +0,0 @@ -// will be actually be loaded by the custom loader diff --git a/packages/commonjs/test/fixtures/samples/dynamic-require-double-wrap/main.js b/packages/commonjs/test/fixtures/samples/dynamic-require-double-wrap/main.js deleted file mode 100644 index d064297ec..000000000 --- a/packages/commonjs/test/fixtures/samples/dynamic-require-double-wrap/main.js +++ /dev/null @@ -1 +0,0 @@ -require('./submodule'); diff --git a/packages/commonjs/test/fixtures/samples/dynamic-require-es-mixed-helpers/importer.js b/packages/commonjs/test/fixtures/samples/dynamic-require-es-mixed-helpers/importer.js deleted file mode 100755 index 6acaa9d43..000000000 --- a/packages/commonjs/test/fixtures/samples/dynamic-require-es-mixed-helpers/importer.js +++ /dev/null @@ -1,2 +0,0 @@ -// eslint-disable-next-line global-require -export default require('./submodule.js'); diff --git a/packages/commonjs/test/fixtures/samples/dynamic-require-es-mixed-helpers/submodule.js b/packages/commonjs/test/fixtures/samples/dynamic-require-es-mixed-helpers/submodule.js deleted file mode 100755 index c285d34bc..000000000 --- a/packages/commonjs/test/fixtures/samples/dynamic-require-es-mixed-helpers/submodule.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = 'submodule'; diff --git a/packages/commonjs/test/fixtures/samples/dynamic-require-outside-root/main.js b/packages/commonjs/test/fixtures/samples/dynamic-require-outside-root/main.js new file mode 100644 index 000000000..18306355f --- /dev/null +++ b/packages/commonjs/test/fixtures/samples/dynamic-require-outside-root/main.js @@ -0,0 +1,6 @@ +function takeModule(path) { + // eslint-disable-next-line global-require,import/no-dynamic-require + return require(path); +} + +takeModule('./nested/target.js'); diff --git a/packages/commonjs/test/fixtures/samples/dynamic-require-outside-root/nested/target.js b/packages/commonjs/test/fixtures/samples/dynamic-require-outside-root/nested/target.js new file mode 100644 index 000000000..5fe5c46eb --- /dev/null +++ b/packages/commonjs/test/fixtures/samples/dynamic-require-outside-root/nested/target.js @@ -0,0 +1 @@ +module.exports = 'target'; diff --git a/packages/commonjs/test/fixtures/samples/mixed-module-typeof-exports/_config.js b/packages/commonjs/test/fixtures/samples/mixed-module-typeof-exports/_config.js new file mode 100644 index 000000000..3d25d8d4d --- /dev/null +++ b/packages/commonjs/test/fixtures/samples/mixed-module-typeof-exports/_config.js @@ -0,0 +1,4 @@ +module.exports = { + description: 'replaces "typeof exports" with "undefined" in mixed modules', + pluginOptions: { transformMixedEsModules: true } +}; diff --git a/packages/commonjs/test/fixtures/samples/mixed-module-typeof-exports/foo.js b/packages/commonjs/test/fixtures/samples/mixed-module-typeof-exports/foo.js new file mode 100644 index 000000000..ce0fffb75 --- /dev/null +++ b/packages/commonjs/test/fixtures/samples/mixed-module-typeof-exports/foo.js @@ -0,0 +1 @@ +module.exports = 21; diff --git a/packages/commonjs/test/fixtures/samples/mixed-module-typeof-exports/main.js b/packages/commonjs/test/fixtures/samples/mixed-module-typeof-exports/main.js new file mode 100644 index 000000000..b1f34e2a2 --- /dev/null +++ b/packages/commonjs/test/fixtures/samples/mixed-module-typeof-exports/main.js @@ -0,0 +1,7 @@ +const foo = require('./foo'); + +if (typeof exports !== 'undefined') { + throw new Error('There should be no global exports in an ES module'); +} + +export { foo as default }; diff --git a/packages/commonjs/test/form.js b/packages/commonjs/test/form.js index f9de9cb65..182498e8b 100644 --- a/packages/commonjs/test/form.js +++ b/packages/commonjs/test/form.js @@ -1,6 +1,7 @@ /* eslint-disable global-require, import/no-dynamic-require, no-console */ import * as fs from 'fs'; +import * as path from 'path'; import * as acorn from 'acorn'; import test from 'ava'; @@ -10,82 +11,97 @@ import { commonjs } from './helpers/util'; process.chdir(__dirname); const transformContext = { + error: (base, props) => { + let error = base; + if (!(base instanceof Error)) error = Object.assign(new Error(base.message), base); + if (props) Object.assign(error, props); + throw error; + }, + load: ({ id }) => Promise.resolve({ id, meta: {} }), parse: (input, options) => acorn.parse(input, { ecmaVersion: 9, sourceType: 'module', ...options + }), + resolve: (source, importer) => + Promise.resolve({ + id: `${path.resolve(path.dirname(importer), source)}${path.extname(source) ? '' : '.js'}` }) }; -fs.readdirSync('./fixtures/form').forEach((dir) => { - let config; +// Do not run on Windows as we have full path names in the output +if (path.sep === '/') { + fs.readdirSync('./fixtures/form').forEach((dir) => { + let config; - try { - config = require(`./fixtures/form/${dir}/_config.js`); - } catch (err) { - config = {}; - } - - const inputEntries = []; - - if (typeof config.multi === 'object') { - for (const [key, entry] of Object.entries(config.multi)) { - inputEntries.push([key, `fixtures/form/${dir}/${entry}`]); + try { + config = require(`./fixtures/form/${dir}/_config.js`); + } catch (err) { + config = {}; } - } else { - inputEntries.push(['output', `fixtures/form/${dir}/input.js`]); - } - - (config.solo ? test.only : test)(dir, async (t) => { - for (const [outputName, id] of inputEntries) { - const { transform } = commonjs(config.options); - - transformContext.getModuleInfo = (moduleId) => { - return { - isEntry: config.entry && moduleId === id, - importers: - config.importers && config.importers[outputName] - ? config.importers[outputName].map((x) => `fixtures/form/${dir}/${x}`) - : [] - }; - }; - transformContext.error = (base, props) => { - let error = base; - if (!(base instanceof Error)) error = Object.assign(new Error(base.message), base); - if (props) Object.assign(error, props); - throw error; - }; - const input = fs.readFileSync(id, 'utf-8'); + const inputEntries = []; - let outputFile = `fixtures/form/${dir}/${outputName}`; - if (fs.existsSync(`${outputFile}.${process.platform}.js`)) { - outputFile += `.${process.platform}.js`; - } else { - outputFile += '.js'; + if (typeof config.multi === 'object') { + for (const [key, entry] of Object.entries(config.multi)) { + inputEntries.push([key, `fixtures/form/${dir}/${entry}`]); } - - const expected = fs.readFileSync(outputFile, 'utf-8').trim(); - const transformed = transform.call(transformContext, input, id); - const actual = (transformed ? transformed.code : input).trim().replace(/\0/g, '_'); - - // uncomment to update snapshots - // fs.writeFileSync(outputFile, `${actual}\n`); - - // trim whitespace from line endings, - // this will benefit issues like `form/try-catch-remove` where whitespace is left in the line, - // and testing on windows (\r\n) - t.is( - actual - .split('\n') - .map((x) => x.trimEnd()) - .join('\n'), - expected - .split('\n') - .map((x) => x.trimEnd()) - .join('\n') - ); + } else { + inputEntries.push(['output', `fixtures/form/${dir}/input.js`]); } + + (config.solo ? test.only : test)(dir, (t) => + Promise.all( + inputEntries.map(async ([outputName, id]) => { + const { buildStart, transform } = commonjs(config.options); + buildStart.call({ meta: { rollupVersion: '99.0.0' } }, { plugins: [] }); + transformContext.getModuleInfo = (moduleId) => { + return { + isEntry: config.entry && moduleId === id, + importers: + config.importers && config.importers[outputName] + ? config.importers[outputName].map((x) => `fixtures/form/${dir}/${x}`) + : [], + meta: {} + }; + }; + const input = fs.readFileSync(id, 'utf-8'); + + let outputFile = `fixtures/form/${dir}/${outputName}`; + if (fs.existsSync(`${outputFile}.${process.platform}.js`)) { + outputFile += `.${process.platform}.js`; + } else { + outputFile += '.js'; + } + + const expected = fs.readFileSync(outputFile, 'utf-8').trim(); + // eslint-disable-next-line no-await-in-loop + const transformed = await transform.call(transformContext, input, id); + let actual = (transformed ? transformed.code : input).trim().replace(/\0/g, '_'); + const cwd = process.cwd(); + while (actual.indexOf(cwd) >= 0) { + actual = actual.replace(process.cwd(), 'CWD'); + } + + // uncomment to update snapshots + // fs.writeFileSync(outputFile, `${actual}\n`); + + // trim whitespace from line endings, + // this will benefit issues like `form/try-catch-remove` where whitespace is left in the line, + // and testing on windows (\r\n) + t.is( + actual + .split('\n') + .map((x) => x.trimEnd()) + .join('\n'), + expected + .split('\n') + .map((x) => x.trimEnd()) + .join('\n') + ); + }) + ) + ); }); -}); +} diff --git a/packages/commonjs/test/helpers/util.js b/packages/commonjs/test/helpers/util.js index 5a297d7d7..8e43b3778 100644 --- a/packages/commonjs/test/helpers/util.js +++ b/packages/commonjs/test/helpers/util.js @@ -1,6 +1,6 @@ const path = require('path'); -const commonjsPlugin = require('../../dist/index'); +const commonjsPlugin = require('../..'); function commonjs(options) { delete require.cache[require.resolve('../..')]; diff --git a/packages/commonjs/test/snapshots/function.js.md b/packages/commonjs/test/snapshots/function.js.md index 1b9a679b2..8f39e945e 100644 --- a/packages/commonjs/test/snapshots/function.js.md +++ b/packages/commonjs/test/snapshots/function.js.md @@ -11,16 +11,14 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ - var foo$2 = {exports: {}};␊ + var foo$1 = {exports: {}};␊ ␊ const foo = {};␊ ␊ - foo$2.exports = foo;␊ - foo$2.exports.bar = 1;␊ - ␊ - var foo$1 = foo$2.exports;␊ + foo$1.exports = foo;␊ + foo$1.exports.bar = 1;␊ ␊ - t.is(foo$1.bar, 1);␊ + t.is(foo$1.exports.bar, 1);␊ `, } @@ -31,19 +29,17 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ - var document$2 = {exports: {}};␊ + var document$1 = {exports: {}};␊ ␊ /* eslint-disable */␊ ␊ if (typeof document !== 'undefined') {␊ - document$2.exports = document;␊ + document$1.exports = document;␊ } else {␊ - document$2.exports = { fake: true };␊ + document$1.exports = { fake: true };␊ }␊ ␊ - var document$1 = document$2.exports;␊ - ␊ - t.deepEqual(document$1, { real: true });␊ + t.deepEqual(document$1.exports, { real: true });␊ `, } @@ -91,6 +87,46 @@ Generated by [AVA](https://avajs.dev). `, } +## call-non-local-function-semantics + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var main = {};␊ + ␊ + var platform$1 = {};␊ + ␊ + platform$1.use = (platform) => (platform$1.platform = platform);␊ + ␊ + var browser$1 = 'browser';␊ + ␊ + var proxy = {};␊ + ␊ + var hasRequiredProxy;␊ + ␊ + function requireProxy () {␊ + if (hasRequiredProxy) return proxy;␊ + hasRequiredProxy = 1;␊ + const { platform } = platform$1;␊ + ␊ + t.is(platform, 'browser');␊ + return proxy;␊ + }␊ + ␊ + // simplified from dd-trace␊ + const platform = platform$1;␊ + const browser = browser$1;␊ + ␊ + platform.use(browser);␊ + ␊ + requireProxy();␊ + ␊ + module.exports = main;␊ + `, + } + ## circular-dependencies > Snapshot 1 @@ -132,32 +168,120 @@ Generated by [AVA](https://avajs.dev). var dep = {};␊ ␊ (function (exports) {␊ - const main$1 = main;␊ + const main$1 = main;␊ ␊ - addExports(exports);␊ + addExports(exports);␊ ␊ - function addExports(exported) {␊ - // eslint-disable-next-line no-param-reassign␊ - exported.getMain = () => main$1;␊ - }␊ - }(dep));␊ + function addExports(exported) {␊ + // eslint-disable-next-line no-param-reassign␊ + exported.getMain = () => main$1;␊ + }␊ + } (dep));␊ ␊ (function (exports) {␊ - const dep$1 = dep;␊ + const dep$1 = dep;␊ ␊ - addExports();␊ - t.is(dep$1.getMain().foo, 'foo');␊ + addExports();␊ + t.is(dep$1.getMain().foo, 'foo');␊ ␊ - function addExports(exported) {␊ - // eslint-disable-next-line no-param-reassign␊ - exports.foo = 'foo';␊ - }␊ - }(main));␊ + function addExports(exported) {␊ + // eslint-disable-next-line no-param-reassign␊ + exports.foo = 'foo';␊ + }␊ + } (main));␊ ␊ exports["default"] = main;␊ `, } +## cjs-extension + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var main = {};␊ + ␊ + var _export = {␊ + test: 42␊ + };␊ + ␊ + const { test } = _export;␊ + ␊ + t.is(test, 42);␊ + ␊ + module.exports = main;␊ + `, + } + +## conditional-require-chain + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + ␊ + var main = {};␊ + ␊ + var dep = {};␊ + ␊ + var throws = {};␊ + ␊ + var hasRequiredThrows;␊ + ␊ + function requireThrows () {␊ + if (hasRequiredThrows) return throws;␊ + hasRequiredThrows = 1;␊ + throw new Error('This should not be executed');␊ + }␊ + ␊ + var hasRequiredDep;␊ + ␊ + function requireDep () {␊ + if (hasRequiredDep) return dep;␊ + hasRequiredDep = 1;␊ + requireThrows();␊ + return dep;␊ + }␊ + ␊ + commonjsGlobal.false = false;␊ + ␊ + if (commonjsGlobal.false) {␊ + // eslint-disable-next-line global-require␊ + requireDep();␊ + }␊ + ␊ + module.exports = main;␊ + `, + } + +## conditional-require-non-strict + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + ␊ + var main = {};␊ + ␊ + commonjsGlobal.foo = true;␊ + ␊ + commonjsGlobal.bar = true;␊ + ␊ + commonjsGlobal.main = true;␊ + ␊ + t.is(commonjsGlobal.foo, true, 'foo');␊ + t.is(commonjsGlobal.main, true, 'main');␊ + ␊ + module.exports = main;␊ + `, + } + ## custom-options > Snapshot 1 @@ -165,7 +289,7 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ - console.log('main');␊ + t.is('main', 'main');␊ `, } @@ -273,16 +397,14 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ - var x$2 = {exports: {}};␊ + var x$1 = {exports: {}};␊ ␊ const x = {};␊ ␊ - x$2.exports = x;␊ - x$2.exports.default = x;␊ - ␊ - var x$1 = x$2.exports;␊ + x$1.exports = x;␊ + x$1.exports.default = x;␊ ␊ - t.is(x$1.default, x$1);␊ + t.is(x$1.exports.default, x$1.exports);␊ `, } @@ -293,16 +415,14 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ - var x$2 = {exports: {}};␊ + var x$1 = {exports: {}};␊ ␊ const x = {};␊ ␊ - x$2.exports = x;␊ - x$2.exports.default = 42;␊ + x$1.exports = x;␊ + x$1.exports.default = 42;␊ ␊ - var x$1 = x$2.exports;␊ - ␊ - t.deepEqual(x$1, { default: 42 });␊ + t.deepEqual(x$1.exports, { default: 42 });␊ `, } @@ -341,29 +461,87 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + var submodule;␊ + var hasRequiredSubmodule;␊ + ␊ + function requireSubmodule () {␊ + if (hasRequiredSubmodule) return submodule;␊ + hasRequiredSubmodule = 1;␊ + submodule = function () {␊ + return 'Hello there';␊ + };␊ + return submodule;␊ + }␊ + ␊ + var dynamicModules;␊ + ␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/fixtures/function/dynamic-module-require/submodule.js": requireSubmodule␊ + });␊ + }␊ ␊ - function createModule(modulePath) {␊ - return {␊ - path: modulePath,␊ - exports: {},␊ - require: function (path, base) {␊ - return commonjsRequire(path, base == null ? modulePath : base);␊ + function createCommonjsRequire(originalModuleDir) {␊ + function handleRequire(path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ + }␊ + throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ + }␊ + handleRequire.resolve = function (path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ }␊ + return require.resolve(path);␊ };␊ + return handleRequire;␊ }␊ ␊ - function commonjsRegister$1 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ + function commonjsResolve (path, originalModuleDir) {␊ + var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ + path = normalize(path);␊ + var relPath;␊ + if (path[0] === '/') {␊ + originalModuleDir = '';␊ + }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ + while (true) {␊ + if (!shouldTryNodeModules) {␊ + relPath = normalize(originalModuleDir + '/' + path);␊ + } else {␊ + relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ + }␊ + ␊ + if (relPath.endsWith('/..')) {␊ + break; // Travelled too far up, avoid infinite loop␊ + }␊ + ␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ + return resolvedPath;␊ + }␊ + }␊ + if (!shouldTryNodeModules) break;␊ + var nextDir = normalize(originalModuleDir + '/..');␊ + if (nextDir === originalModuleDir) break;␊ + originalModuleDir = nextDir;␊ + }␊ + return null;␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ + }␊ ␊ function normalize (path) {␊ path = path.replace(/\\\\/g, '/');␊ @@ -382,93 +560,102 @@ Generated by [AVA](https://avajs.dev). }␊ }␊ path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ return path;␊ }␊ ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ - }␊ - if (joined === undefined)␊ - return '.';␊ + var main = {};␊ + ␊ + /* eslint-disable import/no-dynamic-require, global-require */␊ + ␊ + let message;␊ ␊ - return joined;␊ + function takeModule(withName) {␊ + return createCommonjsRequire("/fixtures/function/dynamic-module-require")(`./${withName}`);␊ }␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ + try {␊ + const submodule = takeModule('submodule');␊ + message = submodule();␊ + } catch (err) {␊ + ({ message } = err);␊ }␊ ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ + t.is(message, 'Hello there');␊ ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ + module.exports = main;␊ + `, + } + +## dynamic-require + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var submodule;␊ + var hasRequiredSubmodule;␊ + ␊ + function requireSubmodule () {␊ + if (hasRequiredSubmodule) return submodule;␊ + hasRequiredSubmodule = 1;␊ + submodule = function () {␊ + return 'Hello there';␊ + };␊ + return submodule;␊ + }␊ ␊ - if (i > 0)␊ - return path.substr(0, i);␊ + var dynamicModules;␊ ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/fixtures/function/dynamic-require/submodule.js": requireSubmodule␊ + });␊ + }␊ ␊ - return '.';␊ + function createCommonjsRequire(originalModuleDir) {␊ + function handleRequire(path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ + }␊ + throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ + }␊ + handleRequire.resolve = function (path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ + };␊ + return handleRequire;␊ }␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ + function commonjsResolve (path, originalModuleDir) {␊ var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ path = normalize(path);␊ var relPath;␊ if (path[0] === '/') {␊ - originalModuleDir = '/';␊ + originalModuleDir = '';␊ }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ while (true) {␊ if (!shouldTryNodeModules) {␊ - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ - } else if (originalModuleDir) {␊ - relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ + relPath = normalize(originalModuleDir + '/' + path);␊ } else {␊ - relPath = normalize(join('node_modules', path));␊ + relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ }␊ ␊ if (relPath.endsWith('/..')) {␊ break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -480,73 +667,46 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ }␊ ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ - ␊ - var main$1 = createModule("/$$rollup_base$$/fixtures/function/dynamic-module-require");␊ - ␊ - const commonjsRegister = commonjsRegister$1;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-module-require/submodule.js", function (module, exports) {␊ - module.exports = function () {␊ - return 'Hello there';␊ - };␊ + function normalize (path) {␊ + path = path.replace(/\\\\/g, '/');␊ + var parts = path.split('/');␊ + var slashed = parts[0] === '';␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] === '.' || parts[i] === '') {␊ + parts.splice(i--, 1);␊ + }␊ + }␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] !== '..') continue;␊ + if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ + parts.splice(--i, 2);␊ + i--;␊ + }␊ + }␊ + path = parts.join('/');␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ + return path;␊ + }␊ ␊ - });␊ + var main = {};␊ ␊ - (function (module) {␊ /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ let message;␊ ␊ function takeModule(withName) {␊ - return module.require(`./${withName}`);␊ + return createCommonjsRequire("/fixtures/function/dynamic-require")(`./${withName}`);␊ }␊ ␊ try {␊ @@ -557,139 +717,101 @@ Generated by [AVA](https://avajs.dev). }␊ ␊ t.is(message, 'Hello there');␊ - }(main$1));␊ - ␊ - var main = main$1.exports;␊ ␊ module.exports = main;␊ `, } -## dynamic-require +## dynamic-require-absolute-import > Snapshot 1 { 'main.js': `'use strict';␊ ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + var main = {};␊ ␊ - function commonjsRegister$1 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ + var direct;␊ + var hasRequiredDirect;␊ + ␊ + function requireDirect () {␊ + if (hasRequiredDirect) return direct;␊ + hasRequiredDirect = 1;␊ + direct = 'direct';␊ + return direct;␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ + var nested;␊ + var hasRequiredNested;␊ ␊ - function normalize (path) {␊ - path = path.replace(/\\\\/g, '/');␊ - var parts = path.split('/');␊ - var slashed = parts[0] === '';␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] === '.' || parts[i] === '') {␊ - parts.splice(i--, 1);␊ - }␊ - }␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] !== '..') continue;␊ - if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ - parts.splice(--i, 2);␊ - i--;␊ - }␊ - }␊ - path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ - return path;␊ + function requireNested () {␊ + if (hasRequiredNested) return nested;␊ + hasRequiredNested = 1;␊ + nested = 'nested';␊ + return nested;␊ }␊ ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ - }␊ - if (joined === undefined)␊ - return '.';␊ + var parent;␊ + var hasRequiredParent;␊ ␊ - return joined;␊ + function requireParent () {␊ + if (hasRequiredParent) return parent;␊ + hasRequiredParent = 1;␊ + parent = 'parent';␊ + return parent;␊ }␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ - }␊ + var dynamicModules;␊ ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ - ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ - ␊ - if (i > 0)␊ - return path.substr(0, i);␊ - ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/fixtures/function/dynamic-require-absolute-import/sub/node_modules/module/direct.js": requireDirect,␊ + "/fixtures/function/dynamic-require-absolute-import/sub/node_modules/module/nested/nested.js": requireNested,␊ + "/fixtures/function/dynamic-require-absolute-import/node_modules/parent-module/parent.js": requireParent␊ + });␊ + }␊ ␊ - return '.';␊ + function createCommonjsRequire(originalModuleDir) {␊ + function handleRequire(path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ + }␊ + throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ + }␊ + handleRequire.resolve = function (path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ + };␊ + return handleRequire;␊ }␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ + function commonjsResolve (path, originalModuleDir) {␊ var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ path = normalize(path);␊ var relPath;␊ if (path[0] === '/') {␊ - originalModuleDir = '/';␊ + originalModuleDir = '';␊ }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ while (true) {␊ if (!shouldTryNodeModules) {␊ - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ - } else if (originalModuleDir) {␊ - relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ + relPath = normalize(originalModuleDir + '/' + path);␊ } else {␊ - relPath = normalize(join('node_modules', path));␊ + relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ }␊ ␊ if (relPath.endsWith('/..')) {␊ break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -701,108 +823,16 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ - }␊ - ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ - ␊ - var main = {};␊ - ␊ - const commonjsRegister = commonjsRegister$1;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require/submodule.js", function (module, exports) {␊ - module.exports = function () {␊ - return 'Hello there';␊ - };␊ - ␊ - });␊ - ␊ - /* eslint-disable import/no-dynamic-require, global-require */␊ - ␊ - let message;␊ - ␊ - function takeModule(withName) {␊ - return commonjsRequire(`./${withName}`,"/$$rollup_base$$/fixtures/function/dynamic-require");␊ - }␊ - ␊ - try {␊ - const submodule = takeModule('submodule');␊ - message = submodule();␊ - } catch (err) {␊ - ({ message } = err);␊ - }␊ - ␊ - t.is(message, 'Hello there');␊ - ␊ - module.exports = main;␊ - `, - } - -## dynamic-require-absolute-import - -> Snapshot 1 - - { - 'main.js': `'use strict';␊ - ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ - ␊ - function commonjsRegister$3 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ - ␊ function normalize (path) {␊ path = path.replace(/\\\\/g, '/');␊ var parts = path.split('/');␊ @@ -820,93 +850,109 @@ Generated by [AVA](https://avajs.dev). }␊ }␊ path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ return path;␊ }␊ ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ - }␊ - if (joined === undefined)␊ - return '.';␊ + var submodule = {};␊ ␊ - return joined;␊ - }␊ + /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ + function takeModule(name) {␊ + return createCommonjsRequire("/fixtures/function/dynamic-require-absolute-import/sub")(name);␊ }␊ ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ + submodule.moduleDirect = takeModule('module/direct');␊ + submodule.moduleNested = takeModule('module/nested/nested');␊ + submodule.parentModule = takeModule('parent-module/parent');␊ ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ + /* eslint-disable import/no-dynamic-require, global-require */␊ + ␊ + t.deepEqual(submodule, {␊ + moduleDirect: 'direct',␊ + moduleNested: 'nested',␊ + parentModule: 'parent'␊ + });␊ + ␊ + module.exports = main;␊ + `, + } + +## dynamic-require-alias-hack + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var require$$0 = require('buffer');␊ + ␊ + function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }␊ ␊ - if (i > 0)␊ - return path.substr(0, i);␊ + var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);␊ + ␊ + var stub;␊ + var hasRequiredStub;␊ + ␊ + function requireStub () {␊ + if (hasRequiredStub) return stub;␊ + hasRequiredStub = 1;␊ + stub = function () {␊ + return 'Hello there';␊ + };␊ + return stub;␊ + }␊ + ␊ + var dynamicModules;␊ ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/fixtures/function/dynamic-require-alias-hack/stub.js": requireStub␊ + });␊ + }␊ ␊ - return '.';␊ + function createCommonjsRequire(originalModuleDir) {␊ + function handleRequire(path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ + }␊ + return require(path);␊ + }␊ + handleRequire.resolve = function (path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ + };␊ + return handleRequire;␊ }␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ + function commonjsResolve (path, originalModuleDir) {␊ var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ path = normalize(path);␊ var relPath;␊ if (path[0] === '/') {␊ - originalModuleDir = '/';␊ + originalModuleDir = '';␊ }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ while (true) {␊ if (!shouldTryNodeModules) {␊ - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ - } else if (originalModuleDir) {␊ - relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ + relPath = normalize(originalModuleDir + '/' + path);␊ } else {␊ - relPath = normalize(join('node_modules', path));␊ + relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ }␊ ␊ if (relPath.endsWith('/..')) {␊ break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -918,130 +964,16 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ - }␊ - ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ - ␊ - var main = {};␊ - ␊ - const commonjsRegister$2 = commonjsRegister$3;␊ - commonjsRegister$2("/$$rollup_base$$/fixtures/function/dynamic-require-absolute-import/sub/node_modules/module/direct.js", function (module, exports) {␊ - module.exports = 'direct';␊ - ␊ - });␊ - ␊ - const commonjsRegister$1 = commonjsRegister$3;␊ - commonjsRegister$1("/$$rollup_base$$/fixtures/function/dynamic-require-absolute-import/sub/node_modules/module/nested/nested.js", function (module, exports) {␊ - module.exports = 'nested';␊ - ␊ - });␊ - ␊ - const commonjsRegister = commonjsRegister$3;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-absolute-import/node_modules/parent-module/parent.js", function (module, exports) {␊ - module.exports = 'parent';␊ - ␊ - });␊ - ␊ - var submodule = {};␊ - ␊ - /* eslint-disable import/no-dynamic-require, global-require */␊ - ␊ - function takeModule(name) {␊ - return commonjsRequire(name,"/$$rollup_base$$/fixtures/function/dynamic-require-absolute-import/sub");␊ - }␊ - ␊ - submodule.moduleDirect = takeModule('module/direct');␊ - submodule.moduleNested = takeModule('module/nested/nested');␊ - submodule.parentModule = takeModule('parent-module/parent');␊ - ␊ - /* eslint-disable import/no-dynamic-require, global-require */␊ - ␊ - t.deepEqual(submodule, {␊ - moduleDirect: 'direct',␊ - moduleNested: 'nested',␊ - parentModule: 'parent'␊ - });␊ - ␊ - module.exports = main;␊ - `, - } - -## dynamic-require-cache-reference - -> Snapshot 1 - - { - 'main.js': `'use strict';␊ - ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ - ␊ - function commonjsRegister$2 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ - }␊ - ␊ - function commonjsRegisterOrShort$1 (path, to) {␊ - var resolvedPath = commonjsResolveImpl(path, null);␊ - if (resolvedPath !== null && DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - DYNAMIC_REQUIRE_CACHE[path] = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - } else {␊ - DYNAMIC_REQUIRE_SHORTS[path] = to;␊ - }␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ - ␊ function normalize (path) {␊ path = path.replace(/\\\\/g, '/');␊ var parts = path.split('/');␊ @@ -1059,93 +991,105 @@ Generated by [AVA](https://avajs.dev). }␊ }␊ path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ return path;␊ }␊ ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ - }␊ - if (joined === undefined)␊ - return '.';␊ + var main = {};␊ ␊ - return joined;␊ - }␊ + /* eslint-disable global-require */␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ + // noinspection UnnecessaryLocalVariableJS␊ + ␊ + // A hack used in many old libraries, saying "workaround to exclude package from browserify list."␊ + // Will bypass rollup-commonjs finding out that this is a require that should not go through the plugin, and will do an infinite search.␊ + const _require = createCommonjsRequire("/fixtures/function/dynamic-require-alias-hack");␊ + const buffer = _require('buffer');␊ + ␊ + t.is(buffer, require$$0__default["default"]);␊ + ␊ + module.exports = main;␊ + `, + } + +## dynamic-require-code-splitting + +> Snapshot 1 + + { + 'generated-lib2.js': `'use strict';␊ + ␊ + var target1;␊ + var hasRequiredTarget1;␊ + ␊ + function requireTarget1 () {␊ + if (hasRequiredTarget1) return target1;␊ + hasRequiredTarget1 = 1;␊ + target1 = '1';␊ + return target1;␊ }␊ ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ + var target2;␊ + var hasRequiredTarget2;␊ ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ + function requireTarget2 () {␊ + if (hasRequiredTarget2) return target2;␊ + hasRequiredTarget2 = 1;␊ + target2 = '2';␊ + return target2;␊ + }␊ ␊ - if (i > 0)␊ - return path.substr(0, i);␊ + var dynamicModules;␊ ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/fixtures/function/dynamic-require-code-splitting/target1.js": requireTarget1,␊ + "/fixtures/function/dynamic-require-code-splitting/target2.js": requireTarget2␊ + });␊ + }␊ ␊ - return '.';␊ + function createCommonjsRequire(originalModuleDir) {␊ + function handleRequire(path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ + }␊ + throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ + }␊ + handleRequire.resolve = function (path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ + };␊ + return handleRequire;␊ }␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ + function commonjsResolve (path, originalModuleDir) {␊ var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ path = normalize(path);␊ var relPath;␊ if (path[0] === '/') {␊ - originalModuleDir = '/';␊ + originalModuleDir = '';␊ }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ while (true) {␊ if (!shouldTryNodeModules) {␊ - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ - } else if (originalModuleDir) {␊ - relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ + relPath = normalize(originalModuleDir + '/' + path);␊ } else {␊ - relPath = normalize(join('node_modules', path));␊ + relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ }␊ ␊ if (relPath.endsWith('/..')) {␊ break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -1157,243 +1101,171 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ + }␊ + ␊ + function normalize (path) {␊ + path = path.replace(/\\\\/g, '/');␊ + var parts = path.split('/');␊ + var slashed = parts[0] === '';␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] === '.' || parts[i] === '') {␊ + parts.splice(i--, 1);␊ + }␊ }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] !== '..') continue;␊ + if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ + parts.splice(--i, 2);␊ + i--;␊ + }␊ + }␊ + path = parts.join('/');␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ + return path;␊ }␊ ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ + /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ - var main = {};␊ - ␊ - const commonjsRegister$1 = commonjsRegister$2;␊ - commonjsRegister$1("/$$rollup_base$$/fixtures/function/dynamic-require-cache-reference/node_modules/custom-module/index.js", function (module, exports) {␊ - module.exports = {␊ - foo: 'bar',␊ - };␊ - ␊ - });␊ - ␊ - function mv(from, to) {␊ - for (let [key, value] of Object.entries(from)) {␊ - to[key] = value;␊ - }␊ - }␊ + let message;␊ ␊ - function clear(obj) {␊ - for (let key of Array.from(Object.keys(obj))) {␊ - delete obj[key];␊ + for (const index of [1, 2]) {␊ + try {␊ + message = createCommonjsRequire("/fixtures/function/dynamic-require-code-splitting")(`./target${index}.js`);␊ + } catch (err) {␊ + ({ message } = err);␊ }␊ + t.is(message, index.toString());␊ }␊ ␊ - var stealthy = function stealth(cacheObject, cb) {␊ - let orig = Object.create(null);␊ + exports.createCommonjsRequire = createCommonjsRequire;␊ + `, + 'main.js': `'use strict';␊ ␊ - mv(cacheObject, orig);␊ - clear(cacheObject);␊ + var lib2 = require('./generated-lib2.js');␊ ␊ - let res = cb();␊ + /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ - clear(cacheObject);␊ - mv(orig, cacheObject);␊ + let message;␊ ␊ - return res;␊ - };␊ + for (const index of [1, 2]) {␊ + try {␊ + message = lib2.createCommonjsRequire("/fixtures/function/dynamic-require-code-splitting")(`./target${index}.js`);␊ + } catch (err) {␊ + ({ message } = err);␊ + }␊ + t.is(message, index.toString());␊ + }␊ + `, + 'main2.js': `'use strict';␊ ␊ - const commonjsRegister = commonjsRegister$2;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-cache-reference/node_modules/custom-module2/index.js", function (module, exports) {␊ - const stealthRequire = stealthy;␊ + require('./generated-lib2.js');␊ ␊ - module.exports = stealthRequire(commonjsRequire.cache, () => {␊ - let m = commonjsRequire("custom-module", "/$$rollup_base$$/fixtures/function/dynamic-require-cache-reference/node_modules/custom-module2");␊ - m.foo = 'baz';␊ - return m;␊ - });␊ + `, + } + +## dynamic-require-different-loader + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ ␊ - });␊ + var submodule2;␊ + var hasRequiredSubmodule2;␊ ␊ - const commonjsRegisterOrShort = commonjsRegisterOrShort$1;␊ - commonjsRegisterOrShort("/$$rollup_base$$/fixtures/function/dynamic-require-cache-reference/node_modules/custom-module", "/$$rollup_base$$/fixtures/function/dynamic-require-cache-reference/node_modules/custom-module/index.js");␊ - commonjsRegisterOrShort("/$$rollup_base$$/fixtures/function/dynamic-require-cache-reference/node_modules/custom-module2", "/$$rollup_base$$/fixtures/function/dynamic-require-cache-reference/node_modules/custom-module2/index.js");␊ + function requireSubmodule2 () {␊ + if (hasRequiredSubmodule2) return submodule2;␊ + hasRequiredSubmodule2 = 1;␊ + submodule2 = function () {␊ + return 'Hello there';␊ + };␊ + return submodule2;␊ + }␊ ␊ - const a = commonjsRequire("custom-module2", "/$$rollup_base$$/fixtures/function/dynamic-require-cache-reference");␊ - const b = commonjsRequire("custom-module", "/$$rollup_base$$/fixtures/function/dynamic-require-cache-reference");␊ + const fn = requireSubmodule2();␊ ␊ - t.is(a.foo, 'baz');␊ - t.is(b.foo, 'bar');␊ + var main = fn();␊ ␊ module.exports = main;␊ `, } -## dynamic-require-code-splitting +## dynamic-require-empty > Snapshot 1 { - 'generated-lib2.js': `'use strict';␊ + 'main.js': `'use strict';␊ ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + var submodule = {};␊ ␊ - function commonjsRegister$2 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ - }␊ + var hasRequiredSubmodule;␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ + function requireSubmodule () {␊ + if (hasRequiredSubmodule) return submodule;␊ + hasRequiredSubmodule = 1;␊ ␊ - function normalize (path) {␊ - path = path.replace(/\\\\/g, '/');␊ - var parts = path.split('/');␊ - var slashed = parts[0] === '';␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] === '.' || parts[i] === '') {␊ - parts.splice(i--, 1);␊ - }␊ - }␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] !== '..') continue;␊ - if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ - parts.splice(--i, 2);␊ - i--;␊ - }␊ - }␊ - path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ - return path;␊ + return submodule;␊ }␊ ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ - }␊ - if (joined === undefined)␊ - return '.';␊ - ␊ - return joined;␊ - }␊ + var dynamicModules;␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/fixtures/function/dynamic-require-empty/submodule.js": requireSubmodule␊ + });␊ }␊ ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ - ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ - ␊ - if (i > 0)␊ - return path.substr(0, i);␊ - ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ - ␊ - return '.';␊ + function createCommonjsRequire(originalModuleDir) {␊ + function handleRequire(path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ + }␊ + throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ + }␊ + handleRequire.resolve = function (path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ + };␊ + return handleRequire;␊ }␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ + function commonjsResolve (path, originalModuleDir) {␊ var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ path = normalize(path);␊ var relPath;␊ if (path[0] === '/') {␊ - originalModuleDir = '/';␊ + originalModuleDir = '';␊ }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ while (true) {␊ if (!shouldTryNodeModules) {␊ - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ - } else if (originalModuleDir) {␊ - relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ + relPath = normalize(originalModuleDir + '/' + path);␊ } else {␊ - relPath = normalize(join('node_modules', path));␊ + relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ }␊ ␊ if (relPath.endsWith('/..')) {␊ break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -1405,128 +1277,16 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ - }␊ - ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ - ␊ - const commonjsRegister$1 = commonjsRegister$2;␊ - commonjsRegister$1("/$$rollup_base$$/fixtures/function/dynamic-require-code-splitting/target1.js", function (module, exports) {␊ - module.exports = '1';␊ - ␊ - });␊ - ␊ - const commonjsRegister = commonjsRegister$2;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-code-splitting/target2.js", function (module, exports) {␊ - module.exports = '2';␊ - ␊ - });␊ - ␊ - /* eslint-disable import/no-dynamic-require, global-require */␊ - ␊ - let message;␊ - ␊ - for (const index of [1, 2]) {␊ - try {␊ - message = commonjsRequire(`./target${index}.js`,"/$$rollup_base$$/fixtures/function/dynamic-require-code-splitting");␊ - } catch (err) {␊ - ({ message } = err);␊ - }␊ - t.is(message, index.toString());␊ - }␊ - ␊ - exports.commonjsRequire = commonjsRequire;␊ - `, - 'main.js': `'use strict';␊ - ␊ - var lib2 = require('./generated-lib2.js');␊ - ␊ - /* eslint-disable import/no-dynamic-require, global-require */␊ - ␊ - let message;␊ - ␊ - for (const index of [1, 2]) {␊ - try {␊ - message = lib2.commonjsRequire(`./target${index}.js`,"/$$rollup_base$$/fixtures/function/dynamic-require-code-splitting");␊ - } catch (err) {␊ - ({ message } = err);␊ - }␊ - t.is(message, index.toString());␊ - }␊ - `, - 'main2.js': `'use strict';␊ - ␊ - require('./generated-lib2.js');␊ - ␊ - `, - } - -## dynamic-require-es-entry - -> Snapshot 1 - - { - 'main.js': `'use strict';␊ - ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ - ␊ - function commonjsRegister$1 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ - ␊ function normalize (path) {␊ path = path.replace(/\\\\/g, '/');␊ var parts = path.split('/');␊ @@ -1544,93 +1304,91 @@ Generated by [AVA](https://avajs.dev). }␊ }␊ path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ return path;␊ }␊ ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ - }␊ - if (joined === undefined)␊ - return '.';␊ + var main = {};␊ ␊ - return joined;␊ - }␊ + /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ + function takeModule(withName) {␊ + return createCommonjsRequire("/fixtures/function/dynamic-require-empty")(`./${withName}`);␊ }␊ ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ + t.deepEqual(takeModule('submodule'), {});␊ ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ + module.exports = main;␊ + `, + } + +## dynamic-require-es-entry + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ ␊ - if (i > 0)␊ - return path.substr(0, i);␊ + var submodule;␊ + var hasRequiredSubmodule;␊ ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ + function requireSubmodule () {␊ + if (hasRequiredSubmodule) return submodule;␊ + hasRequiredSubmodule = 1;␊ + submodule = 'submodule';␊ + return submodule;␊ + }␊ + ␊ + var dynamicModules;␊ + ␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/fixtures/function/dynamic-require-es-entry/submodule.js": requireSubmodule␊ + });␊ + }␊ ␊ - return '.';␊ + function createCommonjsRequire(originalModuleDir) {␊ + function handleRequire(path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ + }␊ + throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ + }␊ + handleRequire.resolve = function (path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ + };␊ + return handleRequire;␊ }␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ + function commonjsResolve (path, originalModuleDir) {␊ var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ path = normalize(path);␊ var relPath;␊ if (path[0] === '/') {␊ - originalModuleDir = '/';␊ + originalModuleDir = '';␊ }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ while (true) {␊ if (!shouldTryNodeModules) {␊ - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ - } else if (originalModuleDir) {␊ - relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ + relPath = normalize(originalModuleDir + '/' + path);␊ } else {␊ - relPath = normalize(join('node_modules', path));␊ + relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ }␊ ␊ if (relPath.endsWith('/..')) {␊ break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -1642,95 +1400,16 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ - }␊ - ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ - ␊ - const commonjsRegister = commonjsRegister$1;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-es-entry/submodule.js", function (module, exports) {␊ - module.exports = 'submodule';␊ - ␊ - });␊ - ␊ - /* eslint-disable import/no-dynamic-require, global-require */␊ - ␊ - function takeModule(withName) {␊ - return commonjsRequire(`./${withName}`,"/$$rollup_base$$/fixtures/function/dynamic-require-es-entry");␊ - }␊ - ␊ - var importer = takeModule('submodule.js');␊ - ␊ - t.is(importer, 'submodule');␊ - `, - } - -## dynamic-require-extensions - -> Snapshot 1 - - { - 'main.js': `'use strict';␊ - ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ - ␊ - function commonjsRegister$1 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ - ␊ function normalize (path) {␊ path = path.replace(/\\\\/g, '/');␊ var parts = path.split('/');␊ @@ -1748,93 +1427,123 @@ Generated by [AVA](https://avajs.dev). }␊ }␊ path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ return path;␊ }␊ ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ - }␊ - if (joined === undefined)␊ - return '.';␊ - ␊ - return joined;␊ - }␊ + /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ + function takeModule(withName) {␊ + return createCommonjsRequire("/fixtures/function/dynamic-require-es-entry")(`./${withName}`);␊ }␊ ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ - ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ - ␊ - if (i > 0)␊ - return path.substr(0, i);␊ + var importer = takeModule('submodule.js');␊ ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ + /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ - return '.';␊ + t.is(importer, 'submodule');␊ + `, + } + +## dynamic-require-es-mixed-helpers + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + ␊ + var submodule;␊ + var hasRequiredSubmodule;␊ + ␊ + function requireSubmodule () {␊ + if (hasRequiredSubmodule) return submodule;␊ + hasRequiredSubmodule = 1;␊ + commonjsGlobal.hasSubmoduleRun = true;␊ + submodule = 'submodule';␊ + return submodule;␊ + }␊ + ␊ + t.is(global.hasSubmoduleRun, undefined, 'before require');␊ + ␊ + // eslint-disable-next-line global-require␊ + var result = requireSubmodule();␊ + ␊ + t.is(global.hasSubmoduleRun, true, 'after require');␊ + delete global.hasSubmoduleRun;␊ + ␊ + t.is(result, 'submodule');␊ + `, + } + +## dynamic-require-extensions + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var submodule;␊ + var hasRequiredSubmodule;␊ + ␊ + function requireSubmodule () {␊ + if (hasRequiredSubmodule) return submodule;␊ + hasRequiredSubmodule = 1;␊ + submodule = { name: 'submodule', value: null };␊ + return submodule;␊ + }␊ + ␊ + var dynamicModules;␊ + ␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/fixtures/function/dynamic-require-extensions/submodule.js": requireSubmodule␊ + });␊ + }␊ + ␊ + function createCommonjsRequire(originalModuleDir) {␊ + function handleRequire(path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ + }␊ + throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ + }␊ + handleRequire.resolve = function (path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ + };␊ + return handleRequire;␊ }␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ + function commonjsResolve (path, originalModuleDir) {␊ var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ path = normalize(path);␊ var relPath;␊ if (path[0] === '/') {␊ - originalModuleDir = '/';␊ + originalModuleDir = '';␊ }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ while (true) {␊ if (!shouldTryNodeModules) {␊ - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ - } else if (originalModuleDir) {␊ - relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ + relPath = normalize(originalModuleDir + '/' + path);␊ } else {␊ - relPath = normalize(join('node_modules', path));␊ + relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ }␊ ␊ if (relPath.endsWith('/..')) {␊ break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -1846,68 +1555,44 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ }␊ ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ + function normalize (path) {␊ + path = path.replace(/\\\\/g, '/');␊ + var parts = path.split('/');␊ + var slashed = parts[0] === '';␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] === '.' || parts[i] === '') {␊ + parts.splice(i--, 1);␊ + }␊ + }␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] !== '..') continue;␊ + if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ + parts.splice(--i, 2);␊ + i--;␊ + }␊ + }␊ + path = parts.join('/');␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ + return path;␊ + }␊ ␊ var main = {};␊ ␊ - const commonjsRegister = commonjsRegister$1;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-extensions/submodule.js", function (module, exports) {␊ - module.exports = { name: 'submodule', value: null };␊ - ␊ - });␊ - ␊ /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ function takeModule(withName) {␊ - return commonjsRequire(`./${withName}`,"/$$rollup_base$$/fixtures/function/dynamic-require-extensions");␊ + return createCommonjsRequire("/fixtures/function/dynamic-require-extensions")(`./${withName}`);␊ }␊ ␊ const withExtension = takeModule('submodule.js');␊ @@ -1953,124 +1638,110 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + var submodule;␊ + var hasRequiredSubmodule;␊ ␊ - function commonjsRegister$1 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ + function requireSubmodule () {␊ + if (hasRequiredSubmodule) return submodule;␊ + hasRequiredSubmodule = 1;␊ + submodule = 'submodule';␊ + return submodule;␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ + var submoduleExports = requireSubmodule();␊ ␊ - function normalize (path) {␊ - path = path.replace(/\\\\/g, '/');␊ - var parts = path.split('/');␊ - var slashed = parts[0] === '';␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] === '.' || parts[i] === '') {␊ - parts.splice(i--, 1);␊ - }␊ - }␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] !== '..') continue;␊ - if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ - parts.splice(--i, 2);␊ - i--;␊ - }␊ - }␊ - path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ - return path;␊ - }␊ + t.is(submoduleExports, 'submodule');␊ + `, + } + +## dynamic-require-globs + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ - }␊ - if (joined === undefined)␊ - return '.';␊ + var submodule1;␊ + var hasRequiredSubmodule1;␊ ␊ - return joined;␊ + function requireSubmodule1 () {␊ + if (hasRequiredSubmodule1) return submodule1;␊ + hasRequiredSubmodule1 = 1;␊ + submodule1 = 'submodule1';␊ + return submodule1;␊ }␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ + var submodule2;␊ + var hasRequiredSubmodule2;␊ + ␊ + function requireSubmodule2 () {␊ + if (hasRequiredSubmodule2) return submodule2;␊ + hasRequiredSubmodule2 = 1;␊ + submodule2 = 'submodule2';␊ + return submodule2;␊ }␊ ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ + var extramodule1;␊ + var hasRequiredExtramodule1;␊ ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ + function requireExtramodule1 () {␊ + if (hasRequiredExtramodule1) return extramodule1;␊ + hasRequiredExtramodule1 = 1;␊ + extramodule1 = 'extramodule1';␊ + return extramodule1;␊ + }␊ ␊ - if (i > 0)␊ - return path.substr(0, i);␊ + var dynamicModules;␊ ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/fixtures/function/dynamic-require-globs/submodule1.js": requireSubmodule1,␊ + "/fixtures/function/dynamic-require-globs/submodule2.js": requireSubmodule2,␊ + "/fixtures/function/dynamic-require-globs/extramodule1.js": requireExtramodule1␊ + });␊ + }␊ ␊ - return '.';␊ + function createCommonjsRequire(originalModuleDir) {␊ + function handleRequire(path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ + }␊ + throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ + }␊ + handleRequire.resolve = function (path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ + };␊ + return handleRequire;␊ }␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ + function commonjsResolve (path, originalModuleDir) {␊ var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ path = normalize(path);␊ var relPath;␊ if (path[0] === '/') {␊ - originalModuleDir = '/';␊ + originalModuleDir = '';␊ }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ while (true) {␊ if (!shouldTryNodeModules) {␊ - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ - } else if (originalModuleDir) {␊ - relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ + relPath = normalize(originalModuleDir + '/' + path);␊ } else {␊ - relPath = normalize(join('node_modules', path));␊ + relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ }␊ ␊ if (relPath.endsWith('/..')) {␊ break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -2082,89 +1753,16 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ - }␊ - ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ - ␊ - const commonjsRegister = commonjsRegister$1;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-from-es-import/submodule.js", function (module, exports) {␊ - module.exports = 'submodule';␊ - ␊ - });␊ - ␊ - var submodule = commonjsRequire("/$$rollup_base$$/fixtures/function/dynamic-require-from-es-import/submodule.js", "/$$rollup_base$$/fixtures/function/dynamic-require-from-es-import");␊ - ␊ - t.is(submodule, 'submodule');␊ - `, - } - -## dynamic-require-globs - -> Snapshot 1 - - { - 'main.js': `'use strict';␊ - ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ - ␊ - function commonjsRegister$3 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ - ␊ function normalize (path) {␊ path = path.replace(/\\\\/g, '/');␊ var parts = path.split('/');␊ @@ -2182,93 +1780,110 @@ Generated by [AVA](https://avajs.dev). }␊ }␊ path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ return path;␊ }␊ ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ - }␊ - if (joined === undefined)␊ - return '.';␊ + var main = {};␊ + ␊ + /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ - return joined;␊ + function takeModule(withName) {␊ + return createCommonjsRequire("/fixtures/function/dynamic-require-globs")(`./${withName}`);␊ }␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ + t.is(takeModule('submodule1.js'), 'submodule1');␊ + t.is(takeModule('submodule2.js'), 'submodule2');␊ + t.is(takeModule('extramodule1.js'), 'extramodule1');␊ + t.throws(() => takeModule('extramodule2.js'), {␊ + message:␊ + 'Could not dynamically require "./extramodule2.js". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.'␊ + });␊ + ␊ + module.exports = main;␊ + `, + } + +## dynamic-require-instances + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var direct;␊ + var hasRequiredDirect;␊ + ␊ + function requireDirect () {␊ + if (hasRequiredDirect) return direct;␊ + hasRequiredDirect = 1;␊ + direct = { name: 'direct', value: null };␊ + return direct;␊ }␊ ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ + var main$1;␊ + var hasRequiredMain;␊ ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ + function requireMain () {␊ + if (hasRequiredMain) return main$1;␊ + hasRequiredMain = 1;␊ + main$1 = { name: 'package', value: null };␊ + return main$1;␊ + }␊ ␊ - if (i > 0)␊ - return path.substr(0, i);␊ + var dynamicModules;␊ ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/fixtures/function/dynamic-require-instances/direct": requireDirect,␊ + "/fixtures/function/dynamic-require-instances/direct/index.js": requireDirect,␊ + "/fixtures/function/dynamic-require-instances/package": requireMain,␊ + "/fixtures/function/dynamic-require-instances/package/main.js": requireMain␊ + });␊ + }␊ ␊ - return '.';␊ + function createCommonjsRequire(originalModuleDir) {␊ + function handleRequire(path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ + }␊ + throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ + }␊ + handleRequire.resolve = function (path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ + };␊ + return handleRequire;␊ }␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ + function commonjsResolve (path, originalModuleDir) {␊ var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ path = normalize(path);␊ var relPath;␊ if (path[0] === '/') {␊ - originalModuleDir = '/';␊ + originalModuleDir = '';␊ }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ while (true) {␊ if (!shouldTryNodeModules) {␊ - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ - } else if (originalModuleDir) {␊ - relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ + relPath = normalize(originalModuleDir + '/' + path);␊ } else {␊ - relPath = normalize(join('node_modules', path));␊ + relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ }␊ ␊ if (relPath.endsWith('/..')) {␊ break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -2280,228 +1895,119 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ }␊ ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ + function normalize (path) {␊ + path = path.replace(/\\\\/g, '/');␊ + var parts = path.split('/');␊ + var slashed = parts[0] === '';␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] === '.' || parts[i] === '') {␊ + parts.splice(i--, 1);␊ + }␊ + }␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] !== '..') continue;␊ + if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ + parts.splice(--i, 2);␊ + i--;␊ + }␊ + }␊ + path = parts.join('/');␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ + return path;␊ + }␊ ␊ var main = {};␊ ␊ - const commonjsRegister$2 = commonjsRegister$3;␊ - commonjsRegister$2("/$$rollup_base$$/fixtures/function/dynamic-require-globs/submodule1.js", function (module, exports) {␊ - module.exports = 'submodule1';␊ - ␊ - });␊ - ␊ - const commonjsRegister$1 = commonjsRegister$3;␊ - commonjsRegister$1("/$$rollup_base$$/fixtures/function/dynamic-require-globs/submodule2.js", function (module, exports) {␊ - module.exports = 'submodule2';␊ - ␊ - });␊ - ␊ - const commonjsRegister = commonjsRegister$3;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-globs/extramodule1.js", function (module, exports) {␊ - module.exports = 'extramodule1';␊ - ␊ - });␊ - ␊ /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ function takeModule(withName) {␊ - return commonjsRequire(`./${withName}`,"/$$rollup_base$$/fixtures/function/dynamic-require-globs");␊ + return createCommonjsRequire("/fixtures/function/dynamic-require-instances")(withName);␊ }␊ ␊ - t.is(takeModule('submodule1.js'), 'submodule1');␊ - t.is(takeModule('submodule2.js'), 'submodule2');␊ - t.is(takeModule('extramodule1.js'), 'extramodule1');␊ - t.throws(() => takeModule('extramodule2.js'), {␊ - message:␊ - 'Could not dynamically require "./extramodule2.js". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.'␊ - });␊ + takeModule('./direct').value = 'direct-instance';␊ + t.is(takeModule('./direct/index.js').value, 'direct-instance');␊ + t.is(requireDirect().value, 'direct-instance');␊ + ␊ + takeModule('./package').value = 'package-instance';␊ + t.is(takeModule('./package/main.js').value, 'package-instance');␊ + t.is(requireMain().value, 'package-instance');␊ ␊ module.exports = main;␊ `, } -## dynamic-require-instances +## dynamic-require-json > Snapshot 1 { 'main.js': `'use strict';␊ ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + var value = "present";␊ + var json0 = {␊ + value: value␊ + };␊ ␊ - function commonjsRegister$2 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ - }␊ + var dynamicModules;␊ ␊ - function commonjsRegisterOrShort$1 (path, to) {␊ - var resolvedPath = commonjsResolveImpl(path, null);␊ - if (resolvedPath !== null && DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - DYNAMIC_REQUIRE_CACHE[path] = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - } else {␊ - DYNAMIC_REQUIRE_SHORTS[path] = to;␊ - }␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/fixtures/function/dynamic-require-json/dynamic.json": function () { return json0; }␊ + });␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ - ␊ - function normalize (path) {␊ - path = path.replace(/\\\\/g, '/');␊ - var parts = path.split('/');␊ - var slashed = parts[0] === '';␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] === '.' || parts[i] === '') {␊ - parts.splice(i--, 1);␊ + function createCommonjsRequire(originalModuleDir) {␊ + function handleRequire(path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ }␊ + throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ }␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] !== '..') continue;␊ - if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ - parts.splice(--i, 2);␊ - i--;␊ + handleRequire.resolve = function (path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ }␊ - }␊ - path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ - return path;␊ - }␊ - ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ - }␊ - if (joined === undefined)␊ - return '.';␊ - ␊ - return joined;␊ - }␊ - ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ - }␊ - ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ - ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ - ␊ - if (i > 0)␊ - return path.substr(0, i);␊ - ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ - ␊ - return '.';␊ + return require.resolve(path);␊ + };␊ + return handleRequire;␊ }␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ + function commonjsResolve (path, originalModuleDir) {␊ var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ path = normalize(path);␊ var relPath;␊ if (path[0] === '/') {␊ - originalModuleDir = '/';␊ + originalModuleDir = '';␊ }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ while (true) {␊ if (!shouldTryNodeModules) {␊ - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ - } else if (originalModuleDir) {␊ - relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ + relPath = normalize(originalModuleDir + '/' + path);␊ } else {␊ - relPath = normalize(join('node_modules', path));␊ + relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ }␊ ␊ if (relPath.endsWith('/..')) {␊ break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -2513,113 +2019,16 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ - }␊ - ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ - ␊ - var main = {};␊ - ␊ - const commonjsRegister$1 = commonjsRegister$2;␊ - commonjsRegister$1("/$$rollup_base$$/fixtures/function/dynamic-require-instances/direct/index.js", function (module, exports) {␊ - module.exports = { name: 'direct', value: null };␊ - ␊ - });␊ - ␊ - const commonjsRegister = commonjsRegister$2;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-instances/package/main.js", function (module, exports) {␊ - module.exports = { name: 'package', value: null };␊ - ␊ - });␊ - ␊ - const commonjsRegisterOrShort = commonjsRegisterOrShort$1;␊ - commonjsRegisterOrShort("/$$rollup_base$$/fixtures/function/dynamic-require-instances/direct", "/$$rollup_base$$/fixtures/function/dynamic-require-instances/direct/index.js");␊ - commonjsRegisterOrShort("/$$rollup_base$$/fixtures/function/dynamic-require-instances/package", "/$$rollup_base$$/fixtures/function/dynamic-require-instances/package/main.js");␊ - ␊ - /* eslint-disable import/no-dynamic-require, global-require */␊ - ␊ - function takeModule(withName) {␊ - return commonjsRequire(withName,"/$$rollup_base$$/fixtures/function/dynamic-require-instances");␊ - }␊ - ␊ - takeModule('./direct').value = 'direct-instance';␊ - t.is(takeModule('./direct/index.js').value, 'direct-instance');␊ - t.is(commonjsRequire("./direct/index.js", "/$$rollup_base$$/fixtures/function/dynamic-require-instances").value, 'direct-instance');␊ - ␊ - takeModule('./package').value = 'package-instance';␊ - t.is(takeModule('./package/main.js').value, 'package-instance');␊ - t.is(commonjsRequire("./package/main.js", "/$$rollup_base$$/fixtures/function/dynamic-require-instances").value, 'package-instance');␊ - ␊ - module.exports = main;␊ - `, - } - -## dynamic-require-json - -> Snapshot 1 - - { - 'main.js': `'use strict';␊ - ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ - ␊ - function commonjsRegister$1 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ - ␊ function normalize (path) {␊ path = path.replace(/\\\\/g, '/');␊ var parts = path.split('/');␊ @@ -2637,170 +2046,17 @@ Generated by [AVA](https://avajs.dev). }␊ }␊ path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ return path;␊ }␊ ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ - }␊ - if (joined === undefined)␊ - return '.';␊ - ␊ - return joined;␊ - }␊ - ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ - }␊ - ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ - ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ - ␊ - if (i > 0)␊ - return path.substr(0, i);␊ - ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ - ␊ - return '.';␊ - }␊ - ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ - var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ - path = normalize(path);␊ - var relPath;␊ - if (path[0] === '/') {␊ - originalModuleDir = '/';␊ - }␊ - while (true) {␊ - if (!shouldTryNodeModules) {␊ - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ - } else if (originalModuleDir) {␊ - relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ - } else {␊ - relPath = normalize(join('node_modules', path));␊ - }␊ - ␊ - if (relPath.endsWith('/..')) {␊ - break; // Travelled too far up, avoid infinite loop␊ - }␊ - ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - }␊ - if (!shouldTryNodeModules) break;␊ - var nextDir = normalize(originalModuleDir + '/..');␊ - if (nextDir === originalModuleDir) break;␊ - originalModuleDir = nextDir;␊ - }␊ - return null;␊ - }␊ - ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ - }␊ - ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ - ␊ var main = {};␊ ␊ - var value = "present";␊ - var require$$1 = {␊ - value: value␊ - };␊ - ␊ - const commonjsRegister = commonjsRegister$1;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-json/dynamic.json", function (module, exports) {␊ - module.exports = require$$1;␊ - });␊ - ␊ /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ function takeModule(withName) {␊ - return commonjsRequire(`./${withName}`,"/$$rollup_base$$/fixtures/function/dynamic-require-json");␊ + return createCommonjsRequire("/fixtures/function/dynamic-require-json")(`./${withName}`);␊ }␊ ␊ t.deepEqual(takeModule('dynamic.json'), { value: 'present' });␊ @@ -2817,7 +2073,7 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ - function commonjsRequire (path) {␊ + function commonjsRequire(path) {␊ throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ }␊ ␊ @@ -2845,133 +2101,90 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ - ␊ - function commonjsRegister$3 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ - }␊ + var entry$2;␊ + var hasRequiredEntry$2;␊ ␊ - function commonjsRegisterOrShort$1 (path, to) {␊ - var resolvedPath = commonjsResolveImpl(path, null);␊ - if (resolvedPath !== null && DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - DYNAMIC_REQUIRE_CACHE[path] = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - } else {␊ - DYNAMIC_REQUIRE_SHORTS[path] = to;␊ - }␊ + function requireEntry$2 () {␊ + if (hasRequiredEntry$2) return entry$2;␊ + hasRequiredEntry$2 = 1;␊ + entry$2 = 'same-directory';␊ + return entry$2;␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ + var entry$1;␊ + var hasRequiredEntry$1;␊ ␊ - function normalize (path) {␊ - path = path.replace(/\\\\/g, '/');␊ - var parts = path.split('/');␊ - var slashed = parts[0] === '';␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] === '.' || parts[i] === '') {␊ - parts.splice(i--, 1);␊ - }␊ - }␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] !== '..') continue;␊ - if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ - parts.splice(--i, 2);␊ - i--;␊ - }␊ - }␊ - path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ - return path;␊ + function requireEntry$1 () {␊ + if (hasRequiredEntry$1) return entry$1;␊ + hasRequiredEntry$1 = 1;␊ + entry$1 = 'sub';␊ + return entry$1;␊ }␊ ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ - }␊ - if (joined === undefined)␊ - return '.';␊ - ␊ - return joined;␊ - }␊ + var entry;␊ + var hasRequiredEntry;␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ + function requireEntry () {␊ + if (hasRequiredEntry) return entry;␊ + hasRequiredEntry = 1;␊ + entry = 'custom-module';␊ + return entry;␊ }␊ ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ + var dynamicModules;␊ ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ - ␊ - if (i > 0)␊ - return path.substr(0, i);␊ - ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/fixtures/function/dynamic-require-package": requireEntry$2,␊ + "/fixtures/function/dynamic-require-package/entry.js": requireEntry$2,␊ + "/fixtures/function/dynamic-require-package/sub": requireEntry$1,␊ + "/fixtures/function/dynamic-require-package/sub/entry.js": requireEntry$1,␊ + "/fixtures/function/dynamic-require-package/node_modules/custom-module": requireEntry,␊ + "/fixtures/function/dynamic-require-package/node_modules/custom-module/entry.js": requireEntry␊ + });␊ + }␊ ␊ - return '.';␊ + function createCommonjsRequire(originalModuleDir) {␊ + function handleRequire(path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ + }␊ + throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ + }␊ + handleRequire.resolve = function (path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ + };␊ + return handleRequire;␊ }␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ + function commonjsResolve (path, originalModuleDir) {␊ var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ path = normalize(path);␊ var relPath;␊ if (path[0] === '/') {␊ - originalModuleDir = '/';␊ + originalModuleDir = '';␊ }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ while (true) {␊ if (!shouldTryNodeModules) {␊ - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ - } else if (originalModuleDir) {␊ - relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ + relPath = normalize(originalModuleDir + '/' + path);␊ } else {␊ - relPath = normalize(join('node_modules', path));␊ + relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ }␊ ␊ if (relPath.endsWith('/..')) {␊ break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -2983,85 +2196,44 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ }␊ ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ + function normalize (path) {␊ + path = path.replace(/\\\\/g, '/');␊ + var parts = path.split('/');␊ + var slashed = parts[0] === '';␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] === '.' || parts[i] === '') {␊ + parts.splice(i--, 1);␊ + }␊ + }␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] !== '..') continue;␊ + if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ + parts.splice(--i, 2);␊ + i--;␊ + }␊ + }␊ + path = parts.join('/');␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ + return path;␊ + }␊ ␊ var main = {};␊ ␊ - const commonjsRegister$2 = commonjsRegister$3;␊ - commonjsRegister$2("/$$rollup_base$$/fixtures/function/dynamic-require-package/entry.js", function (module, exports) {␊ - module.exports = 'same-directory';␊ - ␊ - });␊ - ␊ - const commonjsRegister$1 = commonjsRegister$3;␊ - commonjsRegister$1("/$$rollup_base$$/fixtures/function/dynamic-require-package/sub/entry.js", function (module, exports) {␊ - module.exports = 'sub';␊ - ␊ - });␊ - ␊ - const commonjsRegister = commonjsRegister$3;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-package/node_modules/custom-module/entry.js", function (module, exports) {␊ - module.exports = 'custom-module';␊ - ␊ - });␊ - ␊ - const commonjsRegisterOrShort = commonjsRegisterOrShort$1;␊ - commonjsRegisterOrShort("/$$rollup_base$$/fixtures/function/dynamic-require-package", "/$$rollup_base$$/fixtures/function/dynamic-require-package/entry.js");␊ - commonjsRegisterOrShort("/$$rollup_base$$/fixtures/function/dynamic-require-package/sub", "/$$rollup_base$$/fixtures/function/dynamic-require-package/sub/entry.js");␊ - commonjsRegisterOrShort("/$$rollup_base$$/fixtures/function/dynamic-require-package/node_modules/custom-module", "/$$rollup_base$$/fixtures/function/dynamic-require-package/node_modules/custom-module/entry.js");␊ - ␊ - /* eslint-disable import/no-dynamic-require, global-require */␊ + /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ function takeModule$1(name) {␊ - return commonjsRequire(name,"/$$rollup_base$$/fixtures/function/dynamic-require-package/sub");␊ + return createCommonjsRequire("/fixtures/function/dynamic-require-package/sub")(name);␊ }␊ ␊ var sub = {␊ @@ -3072,7 +2244,7 @@ Generated by [AVA](https://avajs.dev). /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ function takeModule(name) {␊ - return commonjsRequire(name,"/$$rollup_base$$/fixtures/function/dynamic-require-package");␊ + return createCommonjsRequire("/fixtures/function/dynamic-require-package")(name);␊ }␊ ␊ t.is(takeModule('.'), 'same-directory');␊ @@ -3095,133 +2267,101 @@ Generated by [AVA](https://avajs.dev). { 'entry.js': `'use strict';␊ ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + var entry$1 = {};␊ ␊ - function commonjsRegister$2 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ - }␊ + var entry;␊ + var hasRequiredEntry;␊ ␊ - function commonjsRegisterOrShort$1 (path, to) {␊ - var resolvedPath = commonjsResolveImpl(path, null);␊ - if (resolvedPath !== null && DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - DYNAMIC_REQUIRE_CACHE[path] = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - } else {␊ - DYNAMIC_REQUIRE_SHORTS[path] = to;␊ - }␊ + function requireEntry () {␊ + if (hasRequiredEntry) return entry;␊ + hasRequiredEntry = 1;␊ + entry = 'custom-module';␊ + return entry;␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ - ␊ - function normalize (path) {␊ - path = path.replace(/\\\\/g, '/');␊ - var parts = path.split('/');␊ - var slashed = parts[0] === '';␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] === '.' || parts[i] === '') {␊ - parts.splice(i--, 1);␊ - }␊ - }␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] !== '..') continue;␊ - if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ - parts.splice(--i, 2);␊ - i--;␊ - }␊ - }␊ - path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ - return path;␊ - }␊ + t.is(requireEntry(), 'custom-module');␊ ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ - }␊ - if (joined === undefined)␊ - return '.';␊ + module.exports = entry$1;␊ + `, + } + +## dynamic-require-relative-paths + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ ␊ - return joined;␊ - }␊ + var submodule;␊ + var hasRequiredSubmodule;␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ + function requireSubmodule () {␊ + if (hasRequiredSubmodule) return submodule;␊ + hasRequiredSubmodule = 1;␊ + submodule = 'submodule';␊ + return submodule;␊ }␊ ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ + var subsubmodule;␊ + var hasRequiredSubsubmodule;␊ ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ + function requireSubsubmodule () {␊ + if (hasRequiredSubsubmodule) return subsubmodule;␊ + hasRequiredSubsubmodule = 1;␊ + subsubmodule = 'subsubmodule';␊ + return subsubmodule;␊ + }␊ ␊ - if (i > 0)␊ - return path.substr(0, i);␊ + var dynamicModules;␊ ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/fixtures/function/dynamic-require-relative-paths/sub/submodule.js": requireSubmodule,␊ + "/fixtures/function/dynamic-require-relative-paths/sub/subsub/subsubmodule.js": requireSubsubmodule␊ + });␊ + }␊ ␊ - return '.';␊ + function createCommonjsRequire(originalModuleDir) {␊ + function handleRequire(path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ + }␊ + throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ + }␊ + handleRequire.resolve = function (path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ + };␊ + return handleRequire;␊ }␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ + function commonjsResolve (path, originalModuleDir) {␊ var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ path = normalize(path);␊ var relPath;␊ if (path[0] === '/') {␊ - originalModuleDir = '/';␊ + originalModuleDir = '';␊ }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ while (true) {␊ if (!shouldTryNodeModules) {␊ - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ - } else if (originalModuleDir) {␊ - relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ + relPath = normalize(originalModuleDir + '/' + path);␊ } else {␊ - relPath = normalize(join('node_modules', path));␊ + relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ }␊ ␊ if (relPath.endsWith('/..')) {␊ break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -3233,104 +2373,16 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ - }␊ - ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ - ␊ - var entry = {};␊ - ␊ - const commonjsRegister$1 = commonjsRegister$2;␊ - commonjsRegister$1("/$$rollup_base$$/fixtures/function/dynamic-require-package-sub/node_modules/custom-module/entry.js", function (module, exports) {␊ - module.exports = 'custom-module';␊ - ␊ - });␊ - ␊ - var main = "./entry.js";␊ - var require$$1 = {␊ - main: main␊ - };␊ - ␊ - const commonjsRegister = commonjsRegister$2;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-package-sub/node_modules/custom-module/package.json", function (module, exports) {␊ - module.exports = require$$1;␊ - });␊ - ␊ - const commonjsRegisterOrShort = commonjsRegisterOrShort$1;␊ - commonjsRegisterOrShort("/$$rollup_base$$/fixtures/function/dynamic-require-package-sub/node_modules/custom-module", "/$$rollup_base$$/fixtures/function/dynamic-require-package-sub/node_modules/custom-module/entry.js");␊ - ␊ - t.is(commonjsRequire("custom-module", "/$$rollup_base$$/fixtures/function/dynamic-require-package-sub/sub"), 'custom-module');␊ - ␊ - module.exports = entry;␊ - `, - } - -## dynamic-require-relative-paths - -> Snapshot 1 - - { - 'main.js': `'use strict';␊ - ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ - ␊ - function commonjsRegister$2 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ - ␊ function normalize (path) {␊ path = path.replace(/\\\\/g, '/');␊ var parts = path.split('/');␊ @@ -3348,93 +2400,119 @@ Generated by [AVA](https://avajs.dev). }␊ }␊ path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ return path;␊ }␊ ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ - }␊ - if (joined === undefined)␊ - return '.';␊ + var main = {};␊ + ␊ + /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ - return joined;␊ + function takeModuleWithDelimiter(name, delimiter) {␊ + return createCommonjsRequire("/fixtures/function/dynamic-require-relative-paths")(`.${delimiter}${name.replace(/=/g, delimiter)}`);␊ }␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ + t.is(takeModuleWithDelimiter('sub=submodule.js', '/'), 'submodule');␊ + t.is(takeModuleWithDelimiter('sub=subsub=subsubmodule.js', '/'), 'subsubmodule');␊ + t.is(takeModuleWithDelimiter('sub=submodule.js', '\\\\'), 'submodule');␊ + t.is(takeModuleWithDelimiter('sub=subsub=subsubmodule.js', '\\\\'), 'subsubmodule');␊ + ␊ + module.exports = main;␊ + `, + } + +## dynamic-require-resolve-index + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var dynamicRequireResolveIndex;␊ + var hasRequiredDynamicRequireResolveIndex;␊ + ␊ + function requireDynamicRequireResolveIndex () {␊ + if (hasRequiredDynamicRequireResolveIndex) return dynamicRequireResolveIndex;␊ + hasRequiredDynamicRequireResolveIndex = 1;␊ + dynamicRequireResolveIndex = 'same-directory';␊ + return dynamicRequireResolveIndex;␊ }␊ ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ + var sub$1;␊ + var hasRequiredSub;␊ ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ + function requireSub () {␊ + if (hasRequiredSub) return sub$1;␊ + hasRequiredSub = 1;␊ + sub$1 = 'sub';␊ + return sub$1;␊ + }␊ + ␊ + var customModule;␊ + var hasRequiredCustomModule;␊ + ␊ + function requireCustomModule () {␊ + if (hasRequiredCustomModule) return customModule;␊ + hasRequiredCustomModule = 1;␊ + customModule = 'custom-module';␊ + return customModule;␊ + }␊ ␊ - if (i > 0)␊ - return path.substr(0, i);␊ + var dynamicModules;␊ ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/fixtures/function/dynamic-require-resolve-index": requireDynamicRequireResolveIndex,␊ + "/fixtures/function/dynamic-require-resolve-index/index.js": requireDynamicRequireResolveIndex,␊ + "/fixtures/function/dynamic-require-resolve-index/sub": requireSub,␊ + "/fixtures/function/dynamic-require-resolve-index/sub/index.js": requireSub,␊ + "/fixtures/function/dynamic-require-resolve-index/node_modules/custom-module": requireCustomModule,␊ + "/fixtures/function/dynamic-require-resolve-index/node_modules/custom-module/index.js": requireCustomModule␊ + });␊ + }␊ ␊ - return '.';␊ + function createCommonjsRequire(originalModuleDir) {␊ + function handleRequire(path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ + }␊ + throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ + }␊ + handleRequire.resolve = function (path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ + };␊ + return handleRequire;␊ }␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ + function commonjsResolve (path, originalModuleDir) {␊ var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ path = normalize(path);␊ var relPath;␊ if (path[0] === '/') {␊ - originalModuleDir = '/';␊ + originalModuleDir = '';␊ }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ while (true) {␊ if (!shouldTryNodeModules) {␊ - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ - } else if (originalModuleDir) {␊ - relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ + relPath = normalize(originalModuleDir + '/' + path);␊ } else {␊ - relPath = normalize(join('node_modules', path));␊ + relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ }␊ ␊ if (relPath.endsWith('/..')) {␊ break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -3446,114 +2524,161 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ }␊ ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ + function normalize (path) {␊ + path = path.replace(/\\\\/g, '/');␊ + var parts = path.split('/');␊ + var slashed = parts[0] === '';␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] === '.' || parts[i] === '') {␊ + parts.splice(i--, 1);␊ + }␊ + }␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] !== '..') continue;␊ + if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ + parts.splice(--i, 2);␊ + i--;␊ + }␊ + }␊ + path = parts.join('/');␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ + return path;␊ + }␊ ␊ var main = {};␊ ␊ - const commonjsRegister$1 = commonjsRegister$2;␊ - commonjsRegister$1("/$$rollup_base$$/fixtures/function/dynamic-require-relative-paths/sub/submodule.js", function (module, exports) {␊ - module.exports = 'submodule';␊ - ␊ - });␊ + /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ - const commonjsRegister = commonjsRegister$2;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-relative-paths/sub/subsub/subsubmodule.js", function (module, exports) {␊ - module.exports = 'subsubmodule';␊ + function takeModule$1(name) {␊ + return createCommonjsRequire("/fixtures/function/dynamic-require-resolve-index/sub")(name);␊ + }␊ ␊ - });␊ + var sub = {␊ + parent: takeModule$1('..'),␊ + customModule: takeModule$1('custom-module')␊ + };␊ ␊ /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ - function takeModuleWithDelimiter(name, delimiter) {␊ - return commonjsRequire(`.${delimiter}${name.replace(/=/g, delimiter)}`,"/$$rollup_base$$/fixtures/function/dynamic-require-relative-paths");␊ + function takeModule(name) {␊ + return createCommonjsRequire("/fixtures/function/dynamic-require-resolve-index")(name);␊ }␊ ␊ - t.is(takeModuleWithDelimiter('sub=submodule.js', '/'), 'submodule');␊ - t.is(takeModuleWithDelimiter('sub=subsub=subsubmodule.js', '/'), 'subsubmodule');␊ - t.is(takeModuleWithDelimiter('sub=submodule.js', '\\\\'), 'submodule');␊ - t.is(takeModuleWithDelimiter('sub=subsub=subsubmodule.js', '\\\\'), 'subsubmodule');␊ + t.is(takeModule('.'), 'same-directory');␊ + t.is(takeModule('./'), 'same-directory');␊ + t.is(takeModule('.//'), 'same-directory');␊ + ␊ + t.is(takeModule('./sub'), 'sub');␊ + ␊ + t.is(takeModule('custom-module'), 'custom-module');␊ + t.deepEqual(sub, { parent: 'same-directory', customModule: 'custom-module' });␊ ␊ module.exports = main;␊ `, } -## dynamic-require-resolve-index +## dynamic-require-resolve-reference > Snapshot 1 { 'main.js': `'use strict';␊ ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + var main = {};␊ + ␊ + var customModule2;␊ + var hasRequiredCustomModule2;␊ ␊ - function commonjsRegister$3 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ + function requireCustomModule2 () {␊ + if (hasRequiredCustomModule2) return customModule2;␊ + hasRequiredCustomModule2 = 1;␊ + customModule2 = () => createCommonjsRequire("/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module2").resolve('custom-module');␊ + return customModule2;␊ }␊ ␊ - function commonjsRegisterOrShort$1 (path, to) {␊ - var resolvedPath = commonjsResolveImpl(path, null);␊ - if (resolvedPath !== null && DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - DYNAMIC_REQUIRE_CACHE[path] = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - } else {␊ - DYNAMIC_REQUIRE_SHORTS[path] = to;␊ + var dynamicModules;␊ + ␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module": requireCustomModule,␊ + "/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module/index.js": requireCustomModule,␊ + "/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module2": requireCustomModule2,␊ + "/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module2/index.js": requireCustomModule2␊ + });␊ + }␊ + ␊ + function createCommonjsRequire(originalModuleDir) {␊ + function handleRequire(path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ + }␊ + throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ }␊ + handleRequire.resolve = function (path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ + };␊ + return handleRequire;␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ + function commonjsResolve (path, originalModuleDir) {␊ + var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ + path = normalize(path);␊ + var relPath;␊ + if (path[0] === '/') {␊ + originalModuleDir = '';␊ + }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ + while (true) {␊ + if (!shouldTryNodeModules) {␊ + relPath = normalize(originalModuleDir + '/' + path);␊ + } else {␊ + relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ + }␊ + ␊ + if (relPath.endsWith('/..')) {␊ + break; // Travelled too far up, avoid infinite loop␊ + }␊ + ␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ + return resolvedPath;␊ + }␊ + }␊ + if (!shouldTryNodeModules) break;␊ + var nextDir = normalize(originalModuleDir + '/..');␊ + if (nextDir === originalModuleDir) break;␊ + originalModuleDir = nextDir;␊ + }␊ + return null;␊ + }␊ + ␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ + }␊ ␊ function normalize (path) {␊ path = path.replace(/\\\\/g, '/');␊ @@ -3572,93 +2697,105 @@ Generated by [AVA](https://avajs.dev). }␊ }␊ path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ return path;␊ }␊ ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ - }␊ - if (joined === undefined)␊ - return '.';␊ + var customModule = {exports: {}};␊ ␊ - return joined;␊ - }␊ + var hasRequiredCustomModule;␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ + function requireCustomModule () {␊ + if (hasRequiredCustomModule) return customModule.exports;␊ + hasRequiredCustomModule = 1;␊ + (function (module) {␊ + module.exports = () => createCommonjsRequire("/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module").resolve('custom-module2');␊ + } (customModule));␊ + return customModule.exports;␊ }␊ ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ + t.is(␊ + requireCustomModule()(),␊ + '/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module2'␊ + );␊ + t.is(␊ + requireCustomModule2()(),␊ + '/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module'␊ + );␊ ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ + module.exports = main;␊ + `, + } + +## dynamic-require-root + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ ␊ - if (i > 0)␊ - return path.substr(0, i);␊ + var submodule;␊ + var hasRequiredSubmodule;␊ ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ + function requireSubmodule () {␊ + if (hasRequiredSubmodule) return submodule;␊ + hasRequiredSubmodule = 1;␊ + submodule = function () {␊ + return 'Hello there';␊ + };␊ + return submodule;␊ + }␊ + ␊ + var dynamicModules;␊ + ␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/submodule.js": requireSubmodule␊ + });␊ + }␊ ␊ - return '.';␊ + function createCommonjsRequire(originalModuleDir) {␊ + function handleRequire(path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ + }␊ + throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ + }␊ + handleRequire.resolve = function (path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ + };␊ + return handleRequire;␊ }␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ + function commonjsResolve (path, originalModuleDir) {␊ var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ path = normalize(path);␊ var relPath;␊ if (path[0] === '/') {␊ - originalModuleDir = '/';␊ + originalModuleDir = '';␊ }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ while (true) {␊ if (!shouldTryNodeModules) {␊ - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ - } else if (originalModuleDir) {␊ - relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ + relPath = normalize(originalModuleDir + '/' + path);␊ } else {␊ - relPath = normalize(join('node_modules', path));␊ + relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ }␊ ␊ if (relPath.endsWith('/..')) {␊ break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -3670,245 +2807,226 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ }␊ ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ + function normalize (path) {␊ + path = path.replace(/\\\\/g, '/');␊ + var parts = path.split('/');␊ + var slashed = parts[0] === '';␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] === '.' || parts[i] === '') {␊ + parts.splice(i--, 1);␊ + }␊ + }␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] !== '..') continue;␊ + if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ + parts.splice(--i, 2);␊ + i--;␊ + }␊ + }␊ + path = parts.join('/');␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ + return path;␊ + }␊ ␊ var main = {};␊ ␊ - const commonjsRegister$2 = commonjsRegister$3;␊ - commonjsRegister$2("/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index/index.js", function (module, exports) {␊ - module.exports = 'same-directory';␊ + /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ - });␊ + let message;␊ ␊ - const commonjsRegister$1 = commonjsRegister$3;␊ - commonjsRegister$1("/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index/sub/index.js", function (module, exports) {␊ - module.exports = 'sub';␊ + function takeModule(withName) {␊ + return createCommonjsRequire("/")(`./${withName}`);␊ + }␊ ␊ - });␊ + try {␊ + const submodule = takeModule('submodule');␊ + message = submodule();␊ + } catch (err) {␊ + ({ message } = err);␊ + }␊ ␊ - const commonjsRegister = commonjsRegister$3;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index/node_modules/custom-module/index.js", function (module, exports) {␊ - module.exports = 'custom-module';␊ + t.is(message, 'Hello there');␊ ␊ - });␊ + module.exports = main;␊ + `, + } + +## dynamic-require-root-circular + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ ␊ - const commonjsRegisterOrShort = commonjsRegisterOrShort$1;␊ - commonjsRegisterOrShort("/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index", "/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index/index.js");␊ - commonjsRegisterOrShort("/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index/sub", "/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index/sub/index.js");␊ - commonjsRegisterOrShort("/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index/node_modules/custom-module", "/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index/node_modules/custom-module/index.js");␊ + var main = {};␊ ␊ - /* eslint-disable import/no-dynamic-require, global-require */␊ + var customModule = {exports: {}};␊ ␊ - function takeModule$1(name) {␊ - return commonjsRequire(name,"/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index/sub");␊ + var circular = {};␊ + ␊ + var hasRequiredCircular;␊ + ␊ + function requireCircular () {␊ + if (hasRequiredCircular) return circular;␊ + hasRequiredCircular = 1;␊ + const lib = requireCustomModule();␊ + ␊ + circular.extend1 = function (exports) {␊ + exports.get2 = function () {␊ + return 'indirect ref';␊ + };␊ + };␊ + ␊ + circular.extend2 = function (exports) {␊ + exports.get3 = lib.get1;␊ + };␊ + return circular;␊ }␊ ␊ - var sub = {␊ - parent: takeModule$1('..'),␊ - customModule: takeModule$1('custom-module')␊ - };␊ + var hasRequiredCustomModule;␊ ␊ - /* eslint-disable import/no-dynamic-require, global-require */␊ + function requireCustomModule () {␊ + if (hasRequiredCustomModule) return customModule.exports;␊ + hasRequiredCustomModule = 1;␊ + (function (module) {␊ + const circular = requireCircular();␊ ␊ - function takeModule(name) {␊ - return commonjsRequire(name,"/$$rollup_base$$/fixtures/function/dynamic-require-resolve-index");␊ + circular.extend1(module.exports);␊ + ␊ + module.exports.get1 = function () {␊ + return 'all good';␊ + };␊ + ␊ + circular.extend2(module.exports);␊ + } (customModule));␊ + return customModule.exports;␊ }␊ ␊ - t.is(takeModule('.'), 'same-directory');␊ - t.is(takeModule('./'), 'same-directory');␊ - t.is(takeModule('.//'), 'same-directory');␊ + /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ - t.is(takeModule('./sub'), 'sub');␊ + const custom = requireCustomModule();␊ ␊ - t.is(takeModule('custom-module'), 'custom-module');␊ - t.deepEqual(sub, { parent: 'same-directory', customModule: 'custom-module' });␊ + t.is(custom.get1(), 'all good');␊ + t.is(custom.get2(), 'indirect ref');␊ + t.is(custom.get3(), custom.get1());␊ ␊ module.exports = main;␊ `, } -## dynamic-require-resolve-reference +## dynamic-require-slash-access > Snapshot 1 { 'main.js': `'use strict';␊ ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ - ␊ - function commonjsRegister$2 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ - }␊ + var dynamicRequireSlashAccess;␊ + var hasRequiredDynamicRequireSlashAccess;␊ ␊ - function commonjsRegisterOrShort$1 (path, to) {␊ - var resolvedPath = commonjsResolveImpl(path, null);␊ - if (resolvedPath !== null && DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - DYNAMIC_REQUIRE_CACHE[path] = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - } else {␊ - DYNAMIC_REQUIRE_SHORTS[path] = to;␊ - }␊ + function requireDynamicRequireSlashAccess () {␊ + if (hasRequiredDynamicRequireSlashAccess) return dynamicRequireSlashAccess;␊ + hasRequiredDynamicRequireSlashAccess = 1;␊ + dynamicRequireSlashAccess = 'same-directory';␊ + return dynamicRequireSlashAccess;␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ + var sub$2;␊ + var hasRequiredSub$1;␊ ␊ - function normalize (path) {␊ - path = path.replace(/\\\\/g, '/');␊ - var parts = path.split('/');␊ - var slashed = parts[0] === '';␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] === '.' || parts[i] === '') {␊ - parts.splice(i--, 1);␊ - }␊ - }␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] !== '..') continue;␊ - if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ - parts.splice(--i, 2);␊ - i--;␊ - }␊ - }␊ - path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ - return path;␊ + function requireSub$1 () {␊ + if (hasRequiredSub$1) return sub$2;␊ + hasRequiredSub$1 = 1;␊ + sub$2 = 'sub';␊ + return sub$2;␊ }␊ ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ - }␊ - if (joined === undefined)␊ - return '.';␊ - ␊ - return joined;␊ - }␊ + var sub$1;␊ + var hasRequiredSub;␊ ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ + function requireSub () {␊ + if (hasRequiredSub) return sub$1;␊ + hasRequiredSub = 1;␊ + sub$1 = 'sub';␊ + return sub$1;␊ }␊ ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ + var customModule;␊ + var hasRequiredCustomModule;␊ ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ + function requireCustomModule () {␊ + if (hasRequiredCustomModule) return customModule;␊ + hasRequiredCustomModule = 1;␊ + customModule = 'custom-module' + ' + ' + requireSub();␊ + return customModule;␊ + }␊ ␊ - if (i > 0)␊ - return path.substr(0, i);␊ + var dynamicModules;␊ ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/fixtures/function/dynamic-require-slash-access": requireDynamicRequireSlashAccess,␊ + "/fixtures/function/dynamic-require-slash-access/index.js": requireDynamicRequireSlashAccess,␊ + "/fixtures/function/dynamic-require-slash-access/sub": requireSub$1,␊ + "/fixtures/function/dynamic-require-slash-access/sub/index.js": requireSub$1,␊ + "/fixtures/function/dynamic-require-slash-access/node_modules/custom-module": requireCustomModule,␊ + "/fixtures/function/dynamic-require-slash-access/node_modules/custom-module/index.js": requireCustomModule,␊ + "/fixtures/function/dynamic-require-slash-access/node_modules/custom-module2/sub.js": requireSub␊ + });␊ + }␊ ␊ - return '.';␊ + function createCommonjsRequire(originalModuleDir) {␊ + function handleRequire(path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ + }␊ + throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ + }␊ + handleRequire.resolve = function (path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ + };␊ + return handleRequire;␊ }␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ + function commonjsResolve (path, originalModuleDir) {␊ var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ path = normalize(path);␊ var relPath;␊ if (path[0] === '/') {␊ - originalModuleDir = '/';␊ + originalModuleDir = '';␊ }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ while (true) {␊ if (!shouldTryNodeModules) {␊ - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ - } else if (originalModuleDir) {␊ - relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ + relPath = normalize(originalModuleDir + '/' + path);␊ } else {␊ - relPath = normalize(join('node_modules', path));␊ + relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ }␊ ␊ if (relPath.endsWith('/..')) {␊ break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -3920,221 +3038,139 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ }␊ ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ + function normalize (path) {␊ + path = path.replace(/\\\\/g, '/');␊ + var parts = path.split('/');␊ + var slashed = parts[0] === '';␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] === '.' || parts[i] === '') {␊ + parts.splice(i--, 1);␊ + }␊ + }␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] !== '..') continue;␊ + if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ + parts.splice(--i, 2);␊ + i--;␊ + }␊ + }␊ + path = parts.join('/');␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ + return path;␊ + }␊ ␊ var main = {};␊ ␊ - const commonjsRegister$1 = commonjsRegister$2;␊ - commonjsRegister$1("/$$rollup_base$$/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module/index.js", function (module, exports) {␊ - module.exports = {␊ - foo: 'bar',␊ - };␊ + /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ - });␊ + function takeModule$1(name) {␊ + return createCommonjsRequire("/fixtures/function/dynamic-require-slash-access/sub")(name);␊ + }␊ ␊ - const commonjsRegister = commonjsRegister$2;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module2/index.js", function (module, exports) {␊ - module.exports = () => {␊ - return commonjsRequire.resolve('custom-module',"/$$rollup_base$$/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module2");␊ + var sub = {␊ + parent: takeModule$1('..'),␊ + customModule: takeModule$1('custom-module')␊ };␊ ␊ - });␊ + /* eslint-disable import/no-dynamic-require, global-require */␊ + ␊ + function takeModule(name) {␊ + return createCommonjsRequire("/fixtures/function/dynamic-require-slash-access")(name);␊ + }␊ ␊ - const commonjsRegisterOrShort = commonjsRegisterOrShort$1;␊ - commonjsRegisterOrShort("/$$rollup_base$$/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module", "/$$rollup_base$$/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module/index.js");␊ - commonjsRegisterOrShort("/$$rollup_base$$/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module2", "/$$rollup_base$$/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module2/index.js");␊ + t.is(takeModule('.'), 'same-directory', '.');␊ + t.is(takeModule('./'), 'same-directory', './');␊ + t.is(takeModule('.//'), 'same-directory', './/');␊ ␊ - t.is(␊ - commonjsRequire("custom-module2", "/$$rollup_base$$/fixtures/function/dynamic-require-resolve-reference")(),␊ - '/$$rollup_base$$/fixtures/function/dynamic-require-resolve-reference/node_modules/custom-module'␊ - );␊ + t.is(takeModule('./sub'), 'sub', './sub');␊ + ␊ + t.is(takeModule('custom-module'), 'custom-module + sub', 'custom-module');␊ + t.deepEqual(sub, {␊ + parent: 'same-directory',␊ + customModule: 'custom-module + sub'␊ + });␊ ␊ module.exports = main;␊ `, } -## dynamic-require-root-circular +## dynamic-require-targets-fallback > Snapshot 1 { 'main.js': `'use strict';␊ ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + var dep1;␊ + var hasRequiredDep1;␊ ␊ - function commonjsRegister$2 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ + function requireDep1 () {␊ + if (hasRequiredDep1) return dep1;␊ + hasRequiredDep1 = 1;␊ + dep1 = 'dep';␊ + return dep1;␊ }␊ ␊ - function commonjsRegisterOrShort$1 (path, to) {␊ - var resolvedPath = commonjsResolveImpl(path, null);␊ - if (resolvedPath !== null && DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - DYNAMIC_REQUIRE_CACHE[path] = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - } else {␊ - DYNAMIC_REQUIRE_SHORTS[path] = to;␊ - }␊ - }␊ + var dynamicModules;␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/fixtures/function/dynamic-require-targets-fallback/dep1.js": requireDep1␊ + });␊ + }␊ ␊ - function normalize (path) {␊ - path = path.replace(/\\\\/g, '/');␊ - var parts = path.split('/');␊ - var slashed = parts[0] === '';␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] === '.' || parts[i] === '') {␊ - parts.splice(i--, 1);␊ + function createCommonjsRequire(originalModuleDir) {␊ + function handleRequire(path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ }␊ + return require(path);␊ }␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] !== '..') continue;␊ - if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ - parts.splice(--i, 2);␊ - i--;␊ + handleRequire.resolve = function (path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ }␊ - }␊ - path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ - return path;␊ + return require.resolve(path);␊ + };␊ + return handleRequire;␊ }␊ ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ + function commonjsResolve (path, originalModuleDir) {␊ + var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ + path = normalize(path);␊ + var relPath;␊ + if (path[0] === '/') {␊ + originalModuleDir = '';␊ }␊ - if (joined === undefined)␊ - return '.';␊ - ␊ - return joined;␊ - }␊ - ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ - }␊ - ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ - ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ - ␊ - if (i > 0)␊ - return path.substr(0, i);␊ - ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ - ␊ - return '.';␊ - }␊ - ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ - var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ - path = normalize(path);␊ - var relPath;␊ - if (path[0] === '/') {␊ - originalModuleDir = '/';␊ - }␊ - while (true) {␊ - if (!shouldTryNodeModules) {␊ - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ - } else if (originalModuleDir) {␊ - relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ - } else {␊ - relPath = normalize(join('node_modules', path));␊ - }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ + while (true) {␊ + if (!shouldTryNodeModules) {␊ + relPath = normalize(originalModuleDir + '/' + path);␊ + } else {␊ + relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ + }␊ ␊ if (relPath.endsWith('/..')) {␊ break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -4146,124 +3182,16 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ - }␊ - ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ - ␊ - var main = {};␊ - ␊ - const commonjsRegister$1 = commonjsRegister$2;␊ - commonjsRegister$1("/$$rollup_base$$/fixtures/function/dynamic-require-root-circular/node_modules/custom-module/index.js", function (module, exports) {␊ - const circular = commonjsRequire("./lib/circular", "/$$rollup_base$$/fixtures/function/dynamic-require-root-circular/node_modules/custom-module");␊ - ␊ - circular.extend1(module.exports);␊ - ␊ - module.exports.get1 = function () {␊ - return 'all good';␊ - };␊ - ␊ - circular.extend2(module.exports);␊ - ␊ - });␊ - ␊ - const commonjsRegister = commonjsRegister$2;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-root-circular/node_modules/custom-module/lib/circular.js", function (module, exports) {␊ - const lib = commonjsRequire("../", "/$$rollup_base$$/fixtures/function/dynamic-require-root-circular/node_modules/custom-module/lib");␊ - ␊ - module.exports.extend1 = function (exports) {␊ - exports.get2 = function () {␊ - return 'indirect ref';␊ - };␊ - };␊ - ␊ - module.exports.extend2 = function (exports) {␊ - exports.get3 = lib.get1;␊ - };␊ - ␊ - });␊ - ␊ - const commonjsRegisterOrShort = commonjsRegisterOrShort$1;␊ - commonjsRegisterOrShort("/$$rollup_base$$/fixtures/function/dynamic-require-root-circular/node_modules/custom-module", "/$$rollup_base$$/fixtures/function/dynamic-require-root-circular/node_modules/custom-module/index.js");␊ - ␊ - /* eslint-disable import/no-dynamic-require, global-require */␊ - ␊ - const custom = commonjsRequire("custom-module", "/$$rollup_base$$/fixtures/function/dynamic-require-root-circular");␊ - ␊ - t.is(custom.get1(), 'all good');␊ - t.is(custom.get2(), 'indirect ref');␊ - t.is(custom.get3(), custom.get1());␊ - ␊ - module.exports = main;␊ - `, - } - -## dynamic-require-targets-fallback - -> Snapshot 1 - - { - 'main.js': `'use strict';␊ - ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ - ␊ - function commonjsRegister$1 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ - ␊ function normalize (path) {␊ path = path.replace(/\\\\/g, '/');␊ var parts = path.split('/');␊ @@ -4281,166 +3209,17 @@ Generated by [AVA](https://avajs.dev). }␊ }␊ path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ return path;␊ }␊ ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ - }␊ - if (joined === undefined)␊ - return '.';␊ - ␊ - return joined;␊ - }␊ - ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ - }␊ - ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ - ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ - ␊ - if (i > 0)␊ - return path.substr(0, i);␊ - ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ - ␊ - return '.';␊ - }␊ - ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ - var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ - path = normalize(path);␊ - var relPath;␊ - if (path[0] === '/') {␊ - originalModuleDir = '/';␊ - }␊ - while (true) {␊ - if (!shouldTryNodeModules) {␊ - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ - } else if (originalModuleDir) {␊ - relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ - } else {␊ - relPath = normalize(join('node_modules', path));␊ - }␊ - ␊ - if (relPath.endsWith('/..')) {␊ - break; // Travelled too far up, avoid infinite loop␊ - }␊ - ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - }␊ - if (!shouldTryNodeModules) break;␊ - var nextDir = normalize(originalModuleDir + '/..');␊ - if (nextDir === originalModuleDir) break;␊ - originalModuleDir = nextDir;␊ - }␊ - return null;␊ - }␊ - ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - return require(path);␊ - }␊ - ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ - ␊ var main = {};␊ ␊ - const commonjsRegister = commonjsRegister$1;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-targets-fallback/dep1.js", function (module, exports) {␊ - module.exports = 'dep';␊ - ␊ - });␊ - ␊ /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ function takeModule(withName) {␊ - return commonjsRequire(withName,"/$$rollup_base$$/fixtures/function/dynamic-require-targets-fallback");␊ + return createCommonjsRequire("/fixtures/function/dynamic-require-targets-fallback")(withName);␊ }␊ ␊ t.is(takeModule('./dep1.js'), 'dep');␊ @@ -4458,124 +3237,65 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + var dep1;␊ + var hasRequiredDep1;␊ ␊ - function commonjsRegister$1 (path, loader) {␊ - DYNAMIC_REQUIRE_LOADERS[path] = loader;␊ + function requireDep1 () {␊ + if (hasRequiredDep1) return dep1;␊ + hasRequiredDep1 = 1;␊ + dep1 = 'dep';␊ + return dep1;␊ }␊ ␊ - var DYNAMIC_REQUIRE_LOADERS = Object.create(null);␊ - var DYNAMIC_REQUIRE_CACHE = Object.create(null);␊ - var DYNAMIC_REQUIRE_SHORTS = Object.create(null);␊ - var DEFAULT_PARENT_MODULE = {␊ - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []␊ - };␊ - var CHECKED_EXTENSIONS = ['', '.js', '.json'];␊ + var dynamicModules;␊ ␊ - function normalize (path) {␊ - path = path.replace(/\\\\/g, '/');␊ - var parts = path.split('/');␊ - var slashed = parts[0] === '';␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] === '.' || parts[i] === '') {␊ - parts.splice(i--, 1);␊ - }␊ - }␊ - for (var i = 1; i < parts.length; i++) {␊ - if (parts[i] !== '..') continue;␊ - if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ - parts.splice(--i, 2);␊ - i--;␊ - }␊ - }␊ - path = parts.join('/');␊ - if (slashed && path[0] !== '/')␊ - path = '/' + path;␊ - else if (path.length === 0)␊ - path = '.';␊ - return path;␊ + function getDynamicModules() {␊ + return dynamicModules || (dynamicModules = {␊ + "/fixtures/function/dynamic-require-targets-no-fallback/dep1.js": requireDep1␊ + });␊ }␊ ␊ - function join () {␊ - if (arguments.length === 0)␊ - return '.';␊ - var joined;␊ - for (var i = 0; i < arguments.length; ++i) {␊ - var arg = arguments[i];␊ - if (arg.length > 0) {␊ - if (joined === undefined)␊ - joined = arg;␊ - else␊ - joined += '/' + arg;␊ - }␊ + function createCommonjsRequire(originalModuleDir) {␊ + function handleRequire(path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return getDynamicModules()[resolvedPath]();␊ + }␊ + throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ }␊ - if (joined === undefined)␊ - return '.';␊ - ␊ - return joined;␊ - }␊ - ␊ - function isPossibleNodeModulesPath (modulePath) {␊ - var c0 = modulePath[0];␊ - if (c0 === '/' || c0 === '\\\\') return false;␊ - var c1 = modulePath[1], c2 = modulePath[2];␊ - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ - if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))␊ - return false;␊ - return true;␊ - }␊ - ␊ - function dirname (path) {␊ - if (path.length === 0)␊ - return '.';␊ - ␊ - var i = path.length - 1;␊ - while (i > 0) {␊ - var c = path.charCodeAt(i);␊ - if ((c === 47 || c === 92) && i !== path.length - 1)␊ - break;␊ - i--;␊ - }␊ - ␊ - if (i > 0)␊ - return path.substr(0, i);␊ - ␊ - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)␊ - return path.charAt(0);␊ - ␊ - return '.';␊ + handleRequire.resolve = function (path) {␊ + var resolvedPath = commonjsResolve(path, originalModuleDir);␊ + if (resolvedPath !== null) {␊ + return resolvedPath;␊ + }␊ + return require.resolve(path);␊ + };␊ + return handleRequire;␊ }␊ ␊ - function commonjsResolveImpl (path, originalModuleDir, testCache) {␊ + function commonjsResolve (path, originalModuleDir) {␊ var shouldTryNodeModules = isPossibleNodeModulesPath(path);␊ path = normalize(path);␊ var relPath;␊ if (path[0] === '/') {␊ - originalModuleDir = '/';␊ + originalModuleDir = '';␊ }␊ + var modules = getDynamicModules();␊ + var checkedExtensions = ['', '.js', '.json'];␊ while (true) {␊ if (!shouldTryNodeModules) {␊ - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;␊ - } else if (originalModuleDir) {␊ - relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ + relPath = normalize(originalModuleDir + '/' + path);␊ } else {␊ - relPath = normalize(join('node_modules', path));␊ + relPath = normalize(originalModuleDir + '/node_modules/' + path);␊ }␊ ␊ if (relPath.endsWith('/..')) {␊ break; // Travelled too far up, avoid infinite loop␊ }␊ ␊ - for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {␊ - var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];␊ - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {␊ - return resolvedPath;␊ - }␊ - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {␊ + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {␊ + var resolvedPath = relPath + checkedExtensions[extensionIndex];␊ + if (modules[resolvedPath]) {␊ return resolvedPath;␊ }␊ }␊ @@ -4587,68 +3307,44 @@ Generated by [AVA](https://avajs.dev). return null;␊ }␊ ␊ - function commonjsResolve (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - return resolvedPath;␊ - }␊ - return require.resolve(path);␊ - }␊ - ␊ - function commonjsRequire (path, originalModuleDir) {␊ - var resolvedPath = commonjsResolveImpl(path, originalModuleDir);␊ - if (resolvedPath !== null) {␊ - var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - if (cachedModule) return cachedModule.exports;␊ - var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];␊ - if (shortTo) {␊ - cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];␊ - if (cachedModule)␊ - return cachedModule.exports;␊ - resolvedPath = commonjsResolveImpl(shortTo, null);␊ - }␊ - var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];␊ - if (loader) {␊ - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {␊ - id: resolvedPath,␊ - filename: resolvedPath,␊ - path: dirname(resolvedPath),␊ - exports: {},␊ - parent: DEFAULT_PARENT_MODULE,␊ - loaded: false,␊ - children: [],␊ - paths: [],␊ - require: function (path, base) {␊ - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);␊ - }␊ - };␊ - try {␊ - loader.call(commonjsGlobal, cachedModule, cachedModule.exports);␊ - } catch (error) {␊ - delete DYNAMIC_REQUIRE_CACHE[resolvedPath];␊ - throw error;␊ - }␊ - cachedModule.loaded = true;␊ - return cachedModule.exports;␊ - } }␊ - throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ + function isPossibleNodeModulesPath (modulePath) {␊ + var c0 = modulePath[0];␊ + if (c0 === '/' || c0 === '\\\\') return false;␊ + var c1 = modulePath[1], c2 = modulePath[2];␊ + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||␊ + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;␊ + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;␊ + return true;␊ }␊ ␊ - commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;␊ - commonjsRequire.resolve = commonjsResolve;␊ + function normalize (path) {␊ + path = path.replace(/\\\\/g, '/');␊ + var parts = path.split('/');␊ + var slashed = parts[0] === '';␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] === '.' || parts[i] === '') {␊ + parts.splice(i--, 1);␊ + }␊ + }␊ + for (var i = 1; i < parts.length; i++) {␊ + if (parts[i] !== '..') continue;␊ + if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {␊ + parts.splice(--i, 2);␊ + i--;␊ + }␊ + }␊ + path = parts.join('/');␊ + if (slashed && path[0] !== '/') path = '/' + path;␊ + else if (path.length === 0) path = '.';␊ + return path;␊ + }␊ ␊ var main = {};␊ ␊ - const commonjsRegister = commonjsRegister$1;␊ - commonjsRegister("/$$rollup_base$$/fixtures/function/dynamic-require-targets-no-fallback/dep1.js", function (module, exports) {␊ - module.exports = 'dep';␊ - ␊ - });␊ - ␊ /* eslint-disable import/no-dynamic-require, global-require */␊ ␊ function takeModule(withName) {␊ - return commonjsRequire(withName,"/$$rollup_base$$/fixtures/function/dynamic-require-targets-no-fallback");␊ + return createCommonjsRequire("/fixtures/function/dynamic-require-targets-no-fallback")(withName);␊ }␊ ␊ t.is(takeModule('./dep1.js'), 'dep');␊ @@ -4676,8 +3372,10 @@ Generated by [AVA](https://avajs.dev). root = window;␊ } else if (typeof global !== 'undefined') {␊ root = global;␊ - } else {␊ + } else if (typeof module !== 'undefined') {␊ root = module;␊ + } else {␊ + root = Function('return this')(); // eslint-disable-line no-new-func␊ }␊ ␊ root.pollution = 'foo';␊ @@ -4769,8 +3467,14 @@ Generated by [AVA](https://avajs.dev). var externalEsmDefault__namespace = /*#__PURE__*/_interopNamespace(externalEsmDefault);␊ ␊ function getAugmentedNamespace(n) {␊ - if (n.__esModule) return n;␊ - var a = Object.defineProperty({}, '__esModule', {value: true});␊ + var f = n.default;␊ + if (typeof f == "function") {␊ + var a = function () {␊ + return f.apply(this, arguments);␊ + };␊ + a.prototype = f.prototype;␊ + } else a = {};␊ + Object.defineProperty(a, '__esModule', {value: true});␊ Object.keys(n).forEach(function (k) {␊ var d = Object.getOwnPropertyDescriptor(n, k);␊ Object.defineProperty(a, k, d.get ? d : {␊ @@ -4843,8 +3547,14 @@ Generated by [AVA](https://avajs.dev). var externalEsmDefault__namespace = /*#__PURE__*/_interopNamespace(externalEsmDefault);␊ ␊ function getAugmentedNamespace(n) {␊ - if (n.__esModule) return n;␊ - var a = Object.defineProperty({}, '__esModule', {value: true});␊ + var f = n.default;␊ + if (typeof f == "function") {␊ + var a = function () {␊ + return f.apply(this, arguments);␊ + };␊ + a.prototype = f.prototype;␊ + } else a = {};␊ + Object.defineProperty(a, '__esModule', {value: true});␊ Object.keys(n).forEach(function (k) {␊ var d = Object.getOwnPropertyDescriptor(n, k);␊ Object.defineProperty(a, k, d.get ? d : {␊ @@ -4911,8 +3621,14 @@ Generated by [AVA](https://avajs.dev). var externalEsmDefault__namespace = /*#__PURE__*/_interopNamespace(externalEsmDefault);␊ ␊ function getAugmentedNamespace(n) {␊ - if (n.__esModule) return n;␊ - var a = Object.defineProperty({}, '__esModule', {value: true});␊ + var f = n.default;␊ + if (typeof f == "function") {␊ + var a = function () {␊ + return f.apply(this, arguments);␊ + };␊ + a.prototype = f.prototype;␊ + } else a = {};␊ + Object.defineProperty(a, '__esModule', {value: true});␊ Object.keys(n).forEach(function (k) {␊ var d = Object.getOwnPropertyDescriptor(n, k);␊ Object.defineProperty(a, k, d.get ? d : {␊ @@ -4984,33 +3700,119 @@ Generated by [AVA](https://avajs.dev). `, } -## export-default-from +## esm-mixed-exports-function-default > Snapshot 1 { 'main.js': `'use strict';␊ ␊ + function getAugmentedNamespace(n) {␊ + var f = n.default;␊ + if (typeof f == "function") {␊ + var a = function () {␊ + return f.apply(this, arguments);␊ + };␊ + a.prototype = f.prototype;␊ + } else a = {};␊ + Object.defineProperty(a, '__esModule', {value: true});␊ + Object.keys(n).forEach(function (k) {␊ + var d = Object.getOwnPropertyDescriptor(n, k);␊ + Object.defineProperty(a, k, d.get ? d : {␊ + enumerable: true,␊ + get: function () {␊ + return n[k];␊ + }␊ + });␊ + });␊ + return a;␊ + }␊ + ␊ var main = {};␊ ␊ - var require$$0 = 'default export';␊ + function foo$1(...args) {␊ + return args;␊ + }␊ ␊ - t.is(require$$0, 'default export');␊ + const bar$1 = 'bar';␊ ␊ - module.exports = main;␊ - `, - } - -## exports - -> Snapshot 1 - - { - 'main.js': `'use strict';␊ + var esmFunction = /*#__PURE__*/Object.freeze({␊ + __proto__: null,␊ + 'default': foo$1,␊ + bar: bar$1␊ + });␊ ␊ - var foo = {};␊ + var require$$0 = /*@__PURE__*/getAugmentedNamespace(esmFunction);␊ ␊ - foo.bar = 'BAR';␊ + function Foo$1(...args) {␊ + this.foo = args;␊ + }␊ + ␊ + Foo$1.prototype.update = function () {␊ + this.foo = 'updated';␊ + };␊ + ␊ + const bar = 'bar';␊ + ␊ + var esmConstructor = /*#__PURE__*/Object.freeze({␊ + __proto__: null,␊ + 'default': Foo$1,␊ + bar: bar␊ + });␊ + ␊ + var require$$1 = /*@__PURE__*/getAugmentedNamespace(esmConstructor);␊ + ␊ + const foo = require$$0;␊ + const Foo = require$$1;␊ + ␊ + t.is(foo.bar, 'bar');␊ + t.deepEqual(foo.default('first'), ['first']);␊ + t.deepEqual(foo('second'), ['second']);␊ + ␊ + t.is(Foo.bar, 'bar');␊ + ␊ + // eslint-disable-next-line new-cap␊ + const newDefault = new Foo.default('third');␊ + t.deepEqual(newDefault.foo, ['third']);␊ + newDefault.update();␊ + t.is(newDefault.foo, 'updated');␊ + ␊ + const newFoo = new Foo('fourth');␊ + t.deepEqual(newFoo.foo, ['fourth']);␊ + newFoo.update();␊ + t.is(newFoo.foo, 'updated');␊ + ␊ + module.exports = main;␊ + `, + } + +## export-default-from + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var main = {};␊ + ␊ + var require$$0 = 'default export';␊ + ␊ + t.is(require$$0, 'default export');␊ + ␊ + module.exports = main;␊ + `, + } + +## exports + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var foo = {};␊ + ␊ + foo.bar = 'BAR';␊ foo.baz = 'BAZ';␊ ␊ const { bar } = foo;␊ @@ -5034,10 +3836,10 @@ Generated by [AVA](https://avajs.dev). var dep$1 = {exports: {}};␊ ␊ (function (module, exports) {␊ - exports.foo = 'foo';␊ - module.exports = { replaced: true };␊ - exports.bar = 'bar';␊ - }(dep$1, dep$1.exports));␊ + exports.foo = 'foo';␊ + module.exports = { replaced: true };␊ + exports.bar = 'bar';␊ + } (dep$1, dep$1.exports));␊ ␊ const dep = dep$1.exports;␊ ␊ @@ -5054,15 +3856,23 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ - var other = require('./other.js');␊ + var other = require('./other-aeb2ae1d.js');␊ ␊ - t.is(other, 'foo');␊ + t.is(other.other, 'foo');␊ `, - 'other.js': `'use strict';␊ + 'other-aeb2ae1d.js': `'use strict';␊ ␊ var other = 'foo';␊ ␊ - module.exports = other;␊ + exports.other = other;␊ + `, + 'other.js': `'use strict';␊ + ␊ + var other = require('./other-aeb2ae1d.js');␊ + ␊ + ␊ + ␊ + module.exports = other.other;␊ `, } @@ -5095,8 +3905,14 @@ Generated by [AVA](https://avajs.dev). 'main.js': `'use strict';␊ ␊ function getAugmentedNamespace(n) {␊ - if (n.__esModule) return n;␊ - var a = Object.defineProperty({}, '__esModule', {value: true});␊ + var f = n.default;␊ + if (typeof f == "function") {␊ + var a = function () {␊ + return f.apply(this, arguments);␊ + };␊ + a.prototype = f.prototype;␊ + } else a = {};␊ + Object.defineProperty(a, '__esModule', {value: true});␊ Object.keys(n).forEach(function (k) {␊ var d = Object.getOwnPropertyDescriptor(n, k);␊ Object.defineProperty(a, k, d.get ? d : {␊ @@ -5147,13 +3963,13 @@ Generated by [AVA](https://avajs.dev). var encode = {};␊ ␊ (function (exports) {␊ - exports.encodeURIComponent = function () {␊ - return encodeURIComponent(this.str);␊ - };␊ + exports.encodeURIComponent = function () {␊ + return encodeURIComponent(this.str);␊ + };␊ ␊ - // to ensure module is wrapped␊ - commonjsGlobal.foo = exports;␊ - }(encode));␊ + // to ensure module is wrapped␊ + commonjsGlobal.foo = exports;␊ + } (encode));␊ ␊ /* eslint-disable */␊ ␊ @@ -5258,9 +4074,7 @@ Generated by [AVA](https://avajs.dev). ␊ var require$$5 = 'bar';␊ ␊ - var none = /*#__PURE__*/Object.freeze({␊ - __proto__: null␊ - });␊ + var none = {};␊ ␊ const externalNamed = require$$0;␊ const externalMixed = require$$1;␊ @@ -5317,8 +4131,14 @@ Generated by [AVA](https://avajs.dev). var externalEsmDefault__namespace = /*#__PURE__*/_interopNamespace(externalEsmDefault);␊ ␊ function getAugmentedNamespace(n) {␊ - if (n.__esModule) return n;␊ - var a = Object.defineProperty({}, '__esModule', {value: true});␊ + var f = n.default;␊ + if (typeof f == "function") {␊ + var a = function () {␊ + return f.apply(this, arguments);␊ + };␊ + a.prototype = f.prototype;␊ + } else a = {};␊ + Object.defineProperty(a, '__esModule', {value: true});␊ Object.keys(n).forEach(function (k) {␊ var d = Object.getOwnPropertyDescriptor(n, k);␊ Object.defineProperty(a, k, d.get ? d : {␊ @@ -5368,11 +4188,7 @@ Generated by [AVA](https://avajs.dev). ␊ var require$$5 = /*@__PURE__*/getAugmentedNamespace(_default$1);␊ ␊ - var none = /*#__PURE__*/Object.freeze({␊ - __proto__: null␊ - });␊ - ␊ - var require$$6 = /*@__PURE__*/getAugmentedNamespace(none);␊ + var none = {};␊ ␊ const externalNamed = require$$0;␊ const externalMixed = require$$1;␊ @@ -5381,7 +4197,7 @@ Generated by [AVA](https://avajs.dev). const namedExports = require$$3;␊ const mixedExports = require$$4;␊ const defaultExport = require$$5;␊ - const noExports = require$$6;␊ + const noExports = none;␊ ␊ t.deepEqual(namedExports, { foo: 'foo' }, 'named exports');␊ t.deepEqual(mixedExports, { foo: 'foo', default: 'bar' }, 'mixed exports');␊ @@ -5391,6 +4207,14 @@ Generated by [AVA](https://avajs.dev). t.deepEqual(externalMixed, { foo: 'foo', default: 'bar' }, 'external mixed');␊ t.deepEqual(externalDefault, { default: 'bar' }, 'external default');␊ ␊ + /* eslint-disable no-prototype-builtins */␊ + t.is(namedExports.hasOwnProperty('foo'), true);␊ + t.is(mixedExports.hasOwnProperty('foo'), true);␊ + t.is(defaultExport.hasOwnProperty('foo'), false);␊ + t.is(externalNamed.hasOwnProperty('foo'), true);␊ + t.is(externalMixed.hasOwnProperty('foo'), true);␊ + t.is(externalDefault.hasOwnProperty('foo'), false);␊ + ␊ module.exports = main;␊ `, } @@ -5403,8 +4227,14 @@ Generated by [AVA](https://avajs.dev). 'main.js': `'use strict';␊ ␊ function getAugmentedNamespace(n) {␊ - if (n.__esModule) return n;␊ - var a = Object.defineProperty({}, '__esModule', {value: true});␊ + var f = n.default;␊ + if (typeof f == "function") {␊ + var a = function () {␊ + return f.apply(this, arguments);␊ + };␊ + a.prototype = f.prototype;␊ + } else a = {};␊ + Object.defineProperty(a, '__esModule', {value: true});␊ Object.keys(n).forEach(function (k) {␊ var d = Object.getOwnPropertyDescriptor(n, k);␊ Object.defineProperty(a, k, d.get ? d : {␊ @@ -5522,20 +4352,20 @@ Generated by [AVA](https://avajs.dev). ␊ var main$1 = {};␊ ␊ - var require$$0$1 = 'other.js';␊ + var require$$0 = 'other.js';␊ ␊ - var require$$1 = 'both.js';␊ + var require$$2 = 'both.js';␊ ␊ - const other = require$$0$1;␊ - const both$1 = require$$1;␊ + const other = require$$0;␊ + const both$1 = require$$2;␊ ␊ t.deepEqual(other, 'other.js', 'other other');␊ t.deepEqual(both$1, 'both.js', 'other both');␊ ␊ - var require$$0 = 'main.js';␊ + var require$$1 = 'main.js';␊ ␊ - const main = require$$0;␊ - const both = require$$1;␊ + const main = require$$1;␊ + const both = require$$2;␊ ␊ t.deepEqual(main, 'main.js', 'main main');␊ t.deepEqual(both, 'both.js', 'main both');␊ @@ -5584,8 +4414,14 @@ Generated by [AVA](https://avajs.dev). }␊ ␊ function getAugmentedNamespace(n) {␊ - if (n.__esModule) return n;␊ - var a = Object.defineProperty({}, '__esModule', {value: true});␊ + var f = n.default;␊ + if (typeof f == "function") {␊ + var a = function () {␊ + return f.apply(this, arguments);␊ + };␊ + a.prototype = f.prototype;␊ + } else a = {};␊ + Object.defineProperty(a, '__esModule', {value: true});␊ Object.keys(n).forEach(function (k) {␊ var d = Object.getOwnPropertyDescriptor(n, k);␊ Object.defineProperty(a, k, d.get ? d : {␊ @@ -5674,9 +4510,7 @@ Generated by [AVA](https://avajs.dev). 'default': _default␊ });␊ ␊ - var none = /*#__PURE__*/Object.freeze({␊ - __proto__: null␊ - });␊ + var none = {};␊ ␊ const externalNamed = externalEsmNamed__namespace;␊ const externalMixed = externalEsmMixed__namespace;␊ @@ -5755,9 +4589,7 @@ Generated by [AVA](https://avajs.dev). ␊ var require$$5 = 'bar';␊ ␊ - var none = /*#__PURE__*/Object.freeze({␊ - __proto__: null␊ - });␊ + var none = {};␊ ␊ const externalNamed = require$$0;␊ const externalMixed = require$$1;␊ @@ -5854,8 +4686,14 @@ Generated by [AVA](https://avajs.dev). var externalEsmDefault__namespace = /*#__PURE__*/_interopNamespace(externalEsmDefault);␊ ␊ function getAugmentedNamespace(n) {␊ - if (n.__esModule) return n;␊ - var a = Object.defineProperty({}, '__esModule', {value: true});␊ + var f = n.default;␊ + if (typeof f == "function") {␊ + var a = function () {␊ + return f.apply(this, arguments);␊ + };␊ + a.prototype = f.prototype;␊ + } else a = {};␊ + Object.defineProperty(a, '__esModule', {value: true});␊ Object.keys(n).forEach(function (k) {␊ var d = Object.getOwnPropertyDescriptor(n, k);␊ Object.defineProperty(a, k, d.get ? d : {␊ @@ -5905,11 +4743,7 @@ Generated by [AVA](https://avajs.dev). ␊ var require$$5 = /*@__PURE__*/getAugmentedNamespace(_default$1);␊ ␊ - var none = /*#__PURE__*/Object.freeze({␊ - __proto__: null␊ - });␊ - ␊ - var require$$6 = /*@__PURE__*/getAugmentedNamespace(none);␊ + var none = {};␊ ␊ const externalNamed = require$$0;␊ const externalMixed = require$$1;␊ @@ -5918,7 +4752,7 @@ Generated by [AVA](https://avajs.dev). const namedExports = require$$3;␊ const mixedExports = require$$4;␊ const defaultExport = require$$5;␊ - const noExports = require$$6;␊ + const noExports = none;␊ ␊ t.deepEqual(namedExports, { foo: 'foo' }, 'named exports');␊ t.deepEqual(mixedExports, { foo: 'foo', default: 'bar' }, 'mixed exports');␊ @@ -5940,8 +4774,14 @@ Generated by [AVA](https://avajs.dev). 'main.js': `'use strict';␊ ␊ function getAugmentedNamespace(n) {␊ - if (n.__esModule) return n;␊ - var a = Object.defineProperty({}, '__esModule', {value: true});␊ + var f = n.default;␊ + if (typeof f == "function") {␊ + var a = function () {␊ + return f.apply(this, arguments);␊ + };␊ + a.prototype = f.prototype;␊ + } else a = {};␊ + Object.defineProperty(a, '__esModule', {value: true});␊ Object.keys(n).forEach(function (k) {␊ var d = Object.getOwnPropertyDescriptor(n, k);␊ Object.defineProperty(a, k, d.get ? d : {␊ @@ -6020,16 +4860,32 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ - var multiply = function (a, b) {␊ - return a * b;␊ - };␊ + var multiply;␊ + var hasRequiredMultiply;␊ + ␊ + function requireMultiply () {␊ + if (hasRequiredMultiply) return multiply;␊ + hasRequiredMultiply = 1;␊ + multiply = function (a, b) {␊ + return a * b;␊ + };␊ + return multiply;␊ + }␊ ␊ - var foo = 1;␊ + var foo;␊ + var hasRequiredFoo;␊ + ␊ + function requireFoo () {␊ + if (hasRequiredFoo) return foo;␊ + hasRequiredFoo = 1;␊ + foo = 1;␊ + return foo;␊ + }␊ ␊ /* eslint-disable global-require */␊ ␊ var main = function () {␊ - return multiply(2, foo);␊ + return requireMultiply()(2, requireFoo());␊ };␊ ␊ module.exports = main;␊ @@ -6050,15 +4906,15 @@ Generated by [AVA](https://avajs.dev). var other = {exports: {}};␊ ␊ (function (module, exports) {␊ - exports.default = 42;␊ + exports.default = 42;␊ ␊ - addCompiledMarker(module.exports);␊ + addCompiledMarker(module.exports);␊ ␊ - function addCompiledMarker(exports) {␊ - // eslint-disable-next-line no-param-reassign␊ - exports.__esModule = true;␊ - }␊ - }(other, other.exports));␊ + function addCompiledMarker(exports) {␊ + // eslint-disable-next-line no-param-reassign␊ + exports.__esModule = true;␊ + }␊ + } (other, other.exports));␊ ␊ var foo = /*@__PURE__*/getDefaultExportFromCjs(other.exports);␊ ␊ @@ -6076,13 +4932,13 @@ Generated by [AVA](https://avajs.dev). var other = {exports: {}};␊ ␊ (function (module) {␊ - addDefaultExport(module.exports);␊ + addDefaultExport(module.exports);␊ ␊ - function addDefaultExport(exports) {␊ - // eslint-disable-next-line no-param-reassign␊ - exports.default = 42;␊ - }␊ - }(other));␊ + function addDefaultExport(exports) {␊ + // eslint-disable-next-line no-param-reassign␊ + exports.default = 42;␊ + }␊ + } (other));␊ ␊ var foo = other.exports;␊ ␊ @@ -6112,11 +4968,11 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ - var other = require('./other.js');␊ + var other = require('./other2.js');␊ ␊ var main = {};␊ ␊ - const foo = other;␊ + const foo = other.other;␊ ␊ t.is(foo, 'foo');␊ ␊ @@ -6124,9 +4980,17 @@ Generated by [AVA](https://avajs.dev). `, 'other.js': `'use strict';␊ ␊ + var other = require('./other2.js');␊ + ␊ + ␊ + ␊ + module.exports = other.other;␊ + `, + 'other2.js': `'use strict';␊ + ␊ var other = 'foo';␊ ␊ - module.exports = other;␊ + exports.other = other;␊ `, } @@ -6189,13 +5053,77 @@ Generated by [AVA](https://avajs.dev). ␊ (function (exports) {␊ ␊ - modifyExports(exports);␊ + modifyExports(exports);␊ ␊ - function modifyExports(exported) {␊ - // eslint-disable-next-line no-param-reassign␊ - exported.foo = 'bar';␊ - }␊ - }(main));␊ + function modifyExports(exported) {␊ + // eslint-disable-next-line no-param-reassign␊ + exported.foo = 'bar';␊ + }␊ + } (main));␊ + ␊ + module.exports = main;␊ + `, + } + +## load-cycle-parallel + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var main = {};␊ + ␊ + module.exports = main;␊ + `, + } + +## module-meta-properties + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var main = {};␊ + ␊ + var dep$1 = {};␊ + ␊ + dep$1.foo = 'foo';␊ + ␊ + const dep = dep$1;␊ + ␊ + t.is(dep.foo, 'foo');␊ + ␊ + module.exports = main;␊ + `, + } + +## module-side-effects-late-entry + +> Snapshot 1 + + { + 'generated-foo.js': `'use strict';␊ + ␊ + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + ␊ + // This side-effect will only be respected if this is an entry point␊ + commonjsGlobal.foo = 'foo';␊ + `, + 'generated-foo2.js': `'use strict';␊ + ␊ + require('./generated-foo.js');␊ + ␊ + var foo = {};␊ + ␊ + module.exports = foo;␊ + `, + 'main.js': `'use strict';␊ + ␊ + require('./generated-foo.js');␊ + ␊ + var main = 'main';␊ ␊ module.exports = main;␊ `, @@ -6281,10 +5209,10 @@ Generated by [AVA](https://avajs.dev). var x = {exports: {}};␊ ␊ (function (module) {␊ - window.addExport = (key, value) => {␊ - module.exports[key] = value;␊ - };␊ - }(x));␊ + window.addExport = (key, value) => {␊ + module.exports[key] = value;␊ + };␊ + } (x));␊ ␊ t.is(x.exports.named, undefined);␊ ␊ @@ -6304,13 +5232,13 @@ Generated by [AVA](https://avajs.dev). var x = {exports: {}};␊ ␊ (function (module) {␊ - Object.defineProperty(module.exports, 'named', {␊ - enumerable: true,␊ - get: function get() {␊ - return 'foo';␊ - }␊ - });␊ - }(x));␊ + Object.defineProperty(module.exports, 'named', {␊ + enumerable: true,␊ + get: function get() {␊ + return 'foo';␊ + }␊ + });␊ + } (x));␊ ␊ t.is(x.exports.named, 'foo');␊ `, @@ -6323,13 +5251,17 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ + var reexport = {exports: {}};␊ + ␊ var _export = {};␊ ␊ _export.named = 2;␊ ␊ - var reexport = _export;␊ + (function (module) {␊ + module.exports = _export;␊ + } (reexport));␊ ␊ - t.is(reexport.named, 2);␊ + t.is(reexport.exports.named, 2);␊ `, } @@ -6382,8 +5314,8 @@ Generated by [AVA](https://avajs.dev). ␊ (function (exports) {␊ ␊ - exports.default = 'foo';␊ - }(foo$1));␊ + exports.default = 'foo';␊ + } (foo$1));␊ ␊ var foo = /*@__PURE__*/getDefaultExportFromCjs(foo$1);␊ ␊ @@ -6405,14 +5337,14 @@ Generated by [AVA](https://avajs.dev). var foo$1 = {};␊ ␊ (function (exports) {␊ - Object.defineProperty(exports, '__esModule', { value: true });␊ + Object.defineProperty(exports, '__esModule', { value: true });␊ ␊ - {␊ - Object.defineProperty(exports, '__esModule', { value: true });␊ - }␊ + {␊ + Object.defineProperty(exports, '__esModule', { value: true });␊ + }␊ ␊ - exports.default = 'foo';␊ - }(foo$1));␊ + exports.default = 'foo';␊ + } (foo$1));␊ ␊ var foo = /*@__PURE__*/getDefaultExportFromCjs(foo$1);␊ ␊ @@ -6458,58 +5390,555 @@ Generated by [AVA](https://avajs.dev). bar = 'second';␊ }␊ ␊ - t.is(dep1.foo, 'second');␊ - t.is(dep1.bar, 'second');␊ - t.is(foo, 'second');␊ - t.is(bar, 'second');␊ + t.is(dep1.foo, 'second');␊ + t.is(dep1.bar, 'second');␊ + t.is(foo, 'second');␊ + t.is(bar, 'second');␊ + `, + } + +## no-exports-entry + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var main = {};␊ + ␊ + var dep$1 = 42;␊ + ␊ + const dep = dep$1;␊ + ␊ + t.is(dep, 42);␊ + ␊ + module.exports = main;␊ + `, + } + +## no-side-effects + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var main = {};␊ + ␊ + var dep$1 = {};␊ + ␊ + dep$1.foo = 'bar';␊ + ␊ + const dep = dep$1;␊ + ␊ + t.is(dep.foo, 'bar');␊ + ␊ + module.exports = main;␊ + `, + } + +## only-nested-module-exports-reassignment + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var main = {};␊ + ␊ + var dep1$1 = {exports: {}};␊ + ␊ + if (reassignFirstModuleExports) {␊ + dep1$1.exports = 'reassigned';␊ + }␊ + ␊ + var dep2$1 = {exports: {}};␊ + ␊ + if (reassignSecondModuleExports) {␊ + dep2$1.exports = 'reassigned';␊ + }␊ + ␊ + const dep1 = dep1$1.exports;␊ + const dep2 = dep2$1.exports;␊ + ␊ + t.is(dep1, 'reassigned');␊ + t.deepEqual(dep2, {});␊ + ␊ + module.exports = main;␊ + `, + } + +## ordering + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var main = {};␊ + ␊ + var shared$2 = {␊ + fooLoaded: false␊ + };␊ + ␊ + const shared$1 = shared$2;␊ + ␊ + // Mutate the shared module␊ + shared$1.fooLoaded = true;␊ + ␊ + const shared = shared$2;␊ + ␊ + var bar = shared.fooLoaded;␊ + ␊ + const fooLoaded = bar;␊ + ␊ + t.truthy(fooLoaded);␊ + ␊ + module.exports = main;␊ + `, + } + +## pass-require-to-node-resolve + +> Snapshot 1 + + { + 'bar-imported-49e0dbcf.js': `'use strict';␊ + ␊ + var barImported = 'imported';␊ + ␊ + exports["default"] = barImported;␊ + `, + 'main.js': `'use strict';␊ + ␊ + var foo = 'imported';␊ + ␊ + var requiring = {};␊ + ␊ + var fooRequired = 'required';␊ + ␊ + requiring.foo = fooRequired;␊ + ␊ + requiring.barPromise = Promise.resolve().then(function () { return require('./bar-imported-49e0dbcf.js'); });␊ + ␊ + t.is(foo, 'imported');␊ + t.is(requiring.foo, 'required');␊ + ␊ + var main = Promise.all([Promise.resolve().then(function () { return require('./bar-imported-49e0dbcf.js'); }), requiring.barPromise]);␊ + ␊ + module.exports = main;␊ + `, + } + +## plugin-isentry + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + require('./polyfill.js');␊ + ␊ + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + ␊ + function getDefaultExportFromCjs (x) {␊ + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;␊ + }␊ + ␊ + var main$1 = {exports: {}};␊ + ␊ + t.is(commonjsGlobal.entryDetected, true);␊ + var dep = 'dep';␊ + ␊ + (function (module) {␊ + t.is(commonjsGlobal.entryDetected, true);␊ + module.exports = dep;␊ + } (main$1));␊ + ␊ + var main = /*@__PURE__*/getDefaultExportFromCjs(main$1.exports);␊ + ␊ + module.exports = main;␊ + `, + 'other.js': `'use strict';␊ + ␊ + Object.defineProperty(exports, '__esModule', { value: true });␊ + ␊ + require('./polyfill.js');␊ + ␊ + const other = true;␊ + ␊ + exports.other = other;␊ + `, + 'polyfill.js': `'use strict';␊ + ␊ + global.entryDetected = true;␊ + `, + } + +## preserve-modules + +> Snapshot 1 + + { + '_virtual/_commonjsHelpers.js': `'use strict';␊ + ␊ + Object.defineProperty(exports, '__esModule', { value: true });␊ + ␊ + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + ␊ + exports.commonjsGlobal = commonjsGlobal;␊ + `, + 'main.js': `'use strict';␊ + ␊ + var main = require('./main2.js');␊ + ␊ + var mainExports = main.__require();␊ + ␊ + module.exports = mainExports;␊ + `, + 'main2.js': `'use strict';␊ + ␊ + Object.defineProperty(exports, '__esModule', { value: true });␊ + ␊ + var _commonjsHelpers = require('./_virtual/_commonjsHelpers.js');␊ + ␊ + var main;␊ + var hasRequiredMain;␊ + ␊ + function requireMain () {␊ + if (hasRequiredMain) return main;␊ + hasRequiredMain = 1;␊ + _commonjsHelpers.commonjsGlobal.main = 'main';␊ + console.log('main');␊ + ␊ + main = 'main';␊ + return main;␊ + }␊ + ␊ + exports.__require = requireMain;␊ + `, + } + +## react-apollo + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var commonjsBar = {};␊ + ␊ + /* eslint-disable no-underscore-dangle */␊ + ␊ + function Bar$1() {␊ + this.x = 42;␊ + }␊ + ␊ + commonjsBar.__esModule = true;␊ + commonjsBar.default = Bar$1;␊ + ␊ + /* eslint-disable no-underscore-dangle */␊ + ␊ + const Bar = commonjsBar;␊ + var Bar_1 = Bar.default;␊ + ␊ + t.is(new Bar_1().x, 42);␊ + `, + } + +## reassign-exports + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var main = {};␊ + ␊ + var identifier$1 = {};␊ + ␊ + (function (exports) {␊ + exports = 'foo';␊ + t.is(exports, 'foo');␊ + } (identifier$1));␊ + ␊ + var property$1 = {};␊ + ␊ + (function (exports) {␊ + ({ foo: exports } = { foo: 'foo' });␊ + t.is(exports, 'foo');␊ + } (property$1));␊ + ␊ + var arrayPattern$1 = {};␊ + ␊ + (function (exports) {␊ + [exports] = ['foo'];␊ + t.is(exports, 'foo');␊ + } (arrayPattern$1));␊ + ␊ + var assignmentPattern$1 = {};␊ + ␊ + (function (exports) {␊ + ({ exports = 'foo' } = {});␊ + t.is(exports, 'foo');␊ + } (assignmentPattern$1));␊ + ␊ + const identifier = identifier$1;␊ + const property = property$1;␊ + const arrayPattern = arrayPattern$1;␊ + const assignmentPattern = assignmentPattern$1;␊ + ␊ + t.deepEqual(identifier, {});␊ + t.deepEqual(property, {});␊ + t.deepEqual(arrayPattern, {});␊ + t.deepEqual(assignmentPattern, {});␊ + ␊ + module.exports = main;␊ + `, + } + +## reassign-module + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var main = {};␊ + ␊ + var identifier$1 = {exports: {}};␊ + ␊ + (function (module) {␊ + // eslint-disable-next-line no-global-assign␊ + module = 'foo';␊ + t.is(module, 'foo');␊ + } (identifier$1));␊ + ␊ + var property$1 = {exports: {}};␊ + ␊ + (function (module) {␊ + // eslint-disable-next-line no-global-assign␊ + ({ foo: module } = { foo: 'foo' });␊ + t.is(module, 'foo');␊ + } (property$1));␊ + ␊ + var arrayPattern$1 = {exports: {}};␊ + ␊ + (function (module) {␊ + // eslint-disable-next-line no-global-assign␊ + [module] = ['foo'];␊ + t.is(module, 'foo');␊ + } (arrayPattern$1));␊ + ␊ + var assignmentPattern$1 = {exports: {}};␊ + ␊ + (function (module) {␊ + // eslint-disable-next-line no-global-assign␊ + ({ module = 'foo' } = {});␊ + t.is(module, 'foo');␊ + } (assignmentPattern$1));␊ + ␊ + const identifier = identifier$1.exports;␊ + const property = property$1.exports;␊ + const arrayPattern = arrayPattern$1.exports;␊ + const assignmentPattern = assignmentPattern$1.exports;␊ + ␊ + t.deepEqual(identifier, {}, 'identifier');␊ + t.deepEqual(property, {}, 'property');␊ + t.deepEqual(arrayPattern, {}, 'arrayPattern');␊ + t.deepEqual(assignmentPattern, {}, 'assignmentPattern');␊ + ␊ + module.exports = main;␊ + `, + } + +## reassigned-module-exports-object + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var main = {};␊ + ␊ + var dep$1 = {exports: {}};␊ + ␊ + const exported = {};␊ + dep$1.exports = exported;␊ + dep$1.exports.foo = 'foo';␊ + ␊ + t.deepEqual(exported, { foo: 'foo' });␊ + ␊ + const dep = dep$1.exports;␊ + ␊ + t.deepEqual(dep, { foo: 'foo' });␊ + ␊ + module.exports = main;␊ + `, + } + +## reassignment + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var main = {};␊ + ␊ + function foo$1() {}␊ + foo$1.something = false;␊ + ␊ + var foo_1 = foo$1;␊ + ␊ + let foo = foo_1;␊ + ␊ + if (!foo.something) {␊ + foo = function somethingElse() {};␊ + foo.something = true;␊ + }␊ + ␊ + t.truthy(foo.something);␊ + ␊ + module.exports = main;␊ + `, + } + +## relative-external + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var require$$0 = require('../fixtures/function/relative-external/external.js');␊ + ␊ + function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }␊ + ␊ + var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);␊ + ␊ + var main = {};␊ + ␊ + const { foo } = require$$0__default["default"];␊ + ␊ + t.is(foo, 'foo');␊ + ␊ + module.exports = main;␊ + `, + } + +## require-esm-with-named-namespace + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var main = {};␊ + ␊ + const foo = 'foo';␊ + var other = 'bar';␊ + ␊ + var other$1 = /*#__PURE__*/Object.freeze({␊ + __proto__: null,␊ + foo: foo,␊ + 'default': other␊ + });␊ + ␊ + var dep$1 = 'default';␊ + ␊ + var dep$2 = /*#__PURE__*/Object.freeze({␊ + __proto__: null,␊ + 'default': dep$1,␊ + ns: other$1␊ + });␊ + ␊ + const dep = dep$2;␊ + ␊ + t.deepEqual(dep, { default: 'default', ns: { default: 'bar', foo: 'foo' } });␊ + ␊ + module.exports = main;␊ + `, + } + +## require-esm-with-namespace-and-default + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var main = {};␊ + ␊ + const foo = 'foo';␊ + ␊ + var dep$1 = 'default';␊ + ␊ + var dep$2 = /*#__PURE__*/Object.freeze({␊ + __proto__: null,␊ + 'default': dep$1,␊ + foo: foo␊ + });␊ + ␊ + const dep = dep$2;␊ + ␊ + t.deepEqual(dep, { default: 'default', foo: 'foo' });␊ + ␊ + module.exports = main;␊ `, } -## no-default-export-live-binding +## require-esm-with-namespace-named-default > Snapshot 1 { 'main.js': `'use strict';␊ ␊ - var dep1 = {␊ - foo: 'foo',␊ - update: () => (dep1 = { foo: 'bar' })␊ - };␊ + var main = {};␊ ␊ - var dep1$1 = dep1;␊ + const foo = 'foo';␊ + var other = 'bar';␊ ␊ - var dep2$1 = {exports: {}};␊ + var other$1 = /*#__PURE__*/Object.freeze({␊ + __proto__: null,␊ + foo: foo,␊ + 'default': other␊ + });␊ + ␊ + const dep = other$1;␊ ␊ - dep2$1.exports.foo = 'foo';␊ - dep2$1.exports.update = () => (dep2$1.exports = { foo: 'bar' });␊ + t.deepEqual(dep, { default: 'bar', foo: 'foo' });␊ ␊ - var dep2 = dep2$1.exports;␊ + module.exports = main;␊ + `, + } + +## require-esm-with-namespace-prefer-default + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ ␊ - var dep3$1 = {exports: {}};␊ + var main = {};␊ ␊ - (function (module, exports) {␊ - exports.foo = 'foo';␊ - module.exports.update = () => (module.exports = { foo: 'bar' });␊ - }(dep3$1, dep3$1.exports));␊ + const foo = 'foo';␊ ␊ - var dep3 = dep3$1.exports;␊ + var dep$1 = /*#__PURE__*/Object.freeze({␊ + __proto__: null,␊ + foo: foo␊ + });␊ ␊ - t.is(dep1$1.foo, 'foo', 'dep1');␊ - dep1$1.update();␊ - t.is(dep1$1.foo, 'foo', 'dep1 updated');␊ + const dep = dep$1;␊ ␊ - t.is(dep2.foo, 'foo', 'dep2');␊ - dep2.update();␊ - t.is(dep2.foo, 'foo', 'dep2 updated');␊ + t.deepEqual(dep, { foo: 'foo' });␊ ␊ - t.is(dep3.foo, 'foo', 'dep3');␊ - dep3.update();␊ - t.is(dep3.foo, 'foo', 'dep3 updated');␊ + module.exports = main;␊ `, } -## no-exports-entry +## require-snapshotting > Snapshot 1 @@ -6518,71 +5947,115 @@ Generated by [AVA](https://avajs.dev). ␊ var main = {};␊ ␊ - var dep$1 = 42;␊ + var dep$1 = {␊ + foo: 'foo',␊ + update: () => (dep$1 = { foo: 'bar' })␊ + };␊ ␊ const dep = dep$1;␊ ␊ - t.is(dep, 42);␊ + t.is(dep.foo, 'foo');␊ + ␊ + dep.update();␊ + ␊ + t.is(dep.foo, 'foo');␊ + t.is(dep$1.foo, 'bar');␊ ␊ module.exports = main;␊ `, } -## no-side-effects +## resolve-is-cjs-extension > Snapshot 1 { 'main.js': `'use strict';␊ ␊ - var main$1 = {};␊ + function getAugmentedNamespace(n) {␊ + var f = n.default;␊ + if (typeof f == "function") {␊ + var a = function () {␊ + return f.apply(this, arguments);␊ + };␊ + a.prototype = f.prototype;␊ + } else a = {};␊ + Object.defineProperty(a, '__esModule', {value: true});␊ + Object.keys(n).forEach(function (k) {␊ + var d = Object.getOwnPropertyDescriptor(n, k);␊ + Object.defineProperty(a, k, d.get ? d : {␊ + enumerable: true,␊ + get: function () {␊ + return n[k];␊ + }␊ + });␊ + });␊ + return a;␊ + }␊ ␊ - var dep$1 = {};␊ + var main = {};␊ ␊ - dep$1.foo = 'bar';␊ + const result = 'second';␊ ␊ - const dep = dep$1;␊ + var second = /*#__PURE__*/Object.freeze({␊ + __proto__: null,␊ + result: result␊ + });␊ ␊ - t.is(dep.foo, 'bar');␊ + var require$$0 = /*@__PURE__*/getAugmentedNamespace(second);␊ ␊ - var main = main$1;␊ + t.is(require$$0.result, 'second');␊ ␊ module.exports = main;␊ `, } -## only-nested-module-exports-reassignment +## resolve-is-cjs-filtered > Snapshot 1 { 'main.js': `'use strict';␊ ␊ - var main = {};␊ - ␊ - var dep1$1 = {exports: {}};␊ - ␊ - if (reassignFirstModuleExports) {␊ - dep1$1.exports = 'reassigned';␊ + function getAugmentedNamespace(n) {␊ + var f = n.default;␊ + if (typeof f == "function") {␊ + var a = function () {␊ + return f.apply(this, arguments);␊ + };␊ + a.prototype = f.prototype;␊ + } else a = {};␊ + Object.defineProperty(a, '__esModule', {value: true});␊ + Object.keys(n).forEach(function (k) {␊ + var d = Object.getOwnPropertyDescriptor(n, k);␊ + Object.defineProperty(a, k, d.get ? d : {␊ + enumerable: true,␊ + get: function () {␊ + return n[k];␊ + }␊ + });␊ + });␊ + return a;␊ }␊ ␊ - var dep2$1 = {exports: {}};␊ + var main = {};␊ ␊ - if (reassignSecondModuleExports) {␊ - dep2$1.exports = 'reassigned';␊ - }␊ + const result = 'second';␊ ␊ - const dep1 = dep1$1.exports;␊ - const dep2 = dep2$1.exports;␊ + var second = /*#__PURE__*/Object.freeze({␊ + __proto__: null,␊ + result: result␊ + });␊ ␊ - t.is(dep1, 'reassigned');␊ - t.deepEqual(dep2, {});␊ + var require$$0 = /*@__PURE__*/getAugmentedNamespace(second);␊ + ␊ + t.is(require$$0.result, 'second');␊ ␊ module.exports = main;␊ `, } -## ordering +## shadowed-import > Snapshot 1 @@ -6591,87 +6064,105 @@ Generated by [AVA](https://avajs.dev). ␊ var main = {};␊ ␊ - var shared$2 = {␊ - fooLoaded: false␊ - };␊ - ␊ - const shared$1 = shared$2;␊ - ␊ - // Mutate the shared module␊ - shared$1.fooLoaded = true;␊ - ␊ - const shared = shared$2;␊ + var foo$1 = 'foo';␊ ␊ - var bar = shared.fooLoaded;␊ + const foo = foo$1;␊ ␊ - const fooLoaded = bar;␊ + t.is(foo, 'foo');␊ ␊ - t.truthy(fooLoaded);␊ + {␊ + // eslint-disable-next-line no-shadow␊ + const foo = 'wrong';␊ + // eslint-disable-next-line global-require␊ + const bar = foo$1;␊ + t.is(foo, 'wrong');␊ + t.is(bar, 'foo');␊ + }␊ ␊ module.exports = main;␊ `, } -## pass-require-to-node-resolve +## shadowing > Snapshot 1 { - 'bar-imported-49e0dbcf.js': `'use strict';␊ - ␊ - var barImported = 'imported';␊ - ␊ - exports["default"] = barImported;␊ - `, 'main.js': `'use strict';␊ ␊ - var foo = 'imported';␊ + function foo(require) {␊ + require('not-an-actual-require-statement');␊ + }␊ ␊ - var requiring = {};␊ + let result;␊ ␊ - var fooRequired = 'required';␊ + foo((msg) => {␊ + result = msg;␊ + });␊ ␊ - requiring.foo = fooRequired;␊ + t.is(result, 'not-an-actual-require-statement');␊ + `, + } + +## shorthand-require + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ ␊ - requiring.barPromise = Promise.resolve().then(function () { return require('./bar-imported-49e0dbcf.js'); });␊ + function commonjsRequire(path) {␊ + throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ + }␊ ␊ - t.is(foo, 'imported');␊ - t.is(requiring.foo, 'required');␊ + const HOST = {␊ + require: commonjsRequire␊ + };␊ ␊ - var main = Promise.all([Promise.resolve().then(function () { return require('./bar-imported-49e0dbcf.js'); }), requiring.barPromise]);␊ + var main = {␊ + HOST␊ + };␊ ␊ module.exports = main;␊ `, } -## react-apollo +## skips-dead-branches > Snapshot 1 { 'main.js': `'use strict';␊ ␊ - var commonjsBar = {};␊ + Object.defineProperty(exports, '__esModule', { value: true });␊ ␊ - /* eslint-disable no-underscore-dangle */␊ + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ ␊ - function Bar$1() {␊ - this.x = 42;␊ - }␊ + var main = {};␊ ␊ - commonjsBar.__esModule = true;␊ - commonjsBar.default = Bar$1;␊ + commonjsGlobal.b = 2;␊ + var b = 'b';␊ ␊ - /* eslint-disable no-underscore-dangle */␊ + /* eslint-disable */␊ ␊ - const Bar = commonjsBar;␊ - var Bar_1 = Bar.default;␊ + var conditionalTrue = main.conditionalTrue = b ;␊ + var conditionalFalse = main.conditionalFalse = b;␊ + var logicalAnd1 = main.logicalAnd1 = b;␊ + var logicalAnd2 = main.logicalAnd2 = false ;␊ + var logicalOr1 = main.logicalOr1 = true ;␊ + var logicalOr2 = main.logicalOr2 = b;␊ ␊ - t.is(new Bar_1().x, 42);␊ + exports.conditionalFalse = conditionalFalse;␊ + exports.conditionalTrue = conditionalTrue;␊ + exports["default"] = main;␊ + exports.logicalAnd1 = logicalAnd1;␊ + exports.logicalAnd2 = logicalAnd2;␊ + exports.logicalOr1 = logicalOr1;␊ + exports.logicalOr2 = logicalOr2;␊ `, } -## reassign-exports +## strict-requires-auto > Snapshot 1 @@ -6680,49 +6171,47 @@ Generated by [AVA](https://avajs.dev). ␊ var main = {};␊ ␊ - var identifier$1 = {};␊ + var aImportsB = {};␊ ␊ - (function (exports) {␊ - exports = 'foo';␊ - t.is(exports, 'foo');␊ - }(identifier$1));␊ + var bImportsC = {};␊ ␊ - var property$1 = {};␊ + var cImportsA = {};␊ ␊ - (function (exports) {␊ - ({ foo: exports } = { foo: 'foo' });␊ - t.is(exports, 'foo');␊ - }(property$1));␊ + var hasRequiredCImportsA;␊ ␊ - var arrayPattern$1 = {};␊ + function requireCImportsA () {␊ + if (hasRequiredCImportsA) return cImportsA;␊ + hasRequiredCImportsA = 1;␊ + cImportsA.a = requireAImportsB().a;␊ + return cImportsA;␊ + }␊ ␊ - (function (exports) {␊ - [exports] = ['foo'];␊ - t.is(exports, 'foo');␊ - }(arrayPattern$1));␊ + var hasRequiredBImportsC;␊ ␊ - var assignmentPattern$1 = {};␊ + function requireBImportsC () {␊ + if (hasRequiredBImportsC) return bImportsC;␊ + hasRequiredBImportsC = 1;␊ + bImportsC.a = requireCImportsA().a;␊ + return bImportsC;␊ + }␊ ␊ - (function (exports) {␊ - ({ exports = 'foo' } = {});␊ - t.is(exports, 'foo');␊ - }(assignmentPattern$1));␊ + var hasRequiredAImportsB;␊ ␊ - const identifier = identifier$1;␊ - const property = property$1;␊ - const arrayPattern = arrayPattern$1;␊ - const assignmentPattern = assignmentPattern$1;␊ + function requireAImportsB () {␊ + if (hasRequiredAImportsB) return aImportsB;␊ + hasRequiredAImportsB = 1;␊ + aImportsB.a = 'a';␊ + t.is(requireBImportsC().a, 'a');␊ + return aImportsB;␊ + }␊ ␊ - t.deepEqual(identifier, {});␊ - t.deepEqual(property, {});␊ - t.deepEqual(arrayPattern, {});␊ - t.deepEqual(assignmentPattern, {});␊ + requireAImportsB();␊ ␊ module.exports = main;␊ `, } -## reassign-module +## strict-requires-circular > Snapshot 1 @@ -6731,53 +6220,83 @@ Generated by [AVA](https://avajs.dev). ␊ var main = {};␊ ␊ - var identifier$1 = {exports: {}};␊ + var other = {};␊ ␊ - (function (module) {␊ - // eslint-disable-next-line no-global-assign␊ - module = 'foo';␊ - t.is(module, 'foo');␊ - }(identifier$1));␊ + var hasRequiredOther;␊ ␊ - var property$1 = {exports: {}};␊ + function requireOther () {␊ + if (hasRequiredOther) return other;␊ + hasRequiredOther = 1;␊ + other.foo = requireMain().foo;␊ + return other;␊ + }␊ ␊ - (function (module) {␊ - // eslint-disable-next-line no-global-assign␊ - ({ foo: module } = { foo: 'foo' });␊ - t.is(module, 'foo');␊ - }(property$1));␊ + var hasRequiredMain;␊ ␊ - var arrayPattern$1 = {exports: {}};␊ + function requireMain () {␊ + if (hasRequiredMain) return main;␊ + hasRequiredMain = 1;␊ + main.foo = 'foo';␊ + t.is(requireOther().foo, 'foo');␊ + return main;␊ + }␊ ␊ - (function (module) {␊ - // eslint-disable-next-line no-global-assign␊ - [module] = ['foo'];␊ - t.is(module, 'foo');␊ - }(arrayPattern$1));␊ + var mainExports = requireMain();␊ ␊ - var assignmentPattern$1 = {exports: {}};␊ + module.exports = mainExports;␊ + `, + } + +## strict-requires-cycle-detection + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ ␊ - (function (module) {␊ - // eslint-disable-next-line no-global-assign␊ - ({ module = 'foo' } = {});␊ - t.is(module, 'foo');␊ - }(assignmentPattern$1));␊ + var main = {};␊ ␊ - const identifier = identifier$1.exports;␊ - const property = property$1.exports;␊ - const arrayPattern = arrayPattern$1.exports;␊ - const assignmentPattern = assignmentPattern$1.exports;␊ + var aImportsB = {};␊ ␊ - t.deepEqual(identifier, {});␊ - t.deepEqual(property, {});␊ - t.deepEqual(arrayPattern, {});␊ - t.deepEqual(assignmentPattern, {});␊ + var bImportsC = {};␊ + ␊ + var cImportsA = {};␊ + ␊ + var hasRequiredCImportsA;␊ + ␊ + function requireCImportsA () {␊ + if (hasRequiredCImportsA) return cImportsA;␊ + hasRequiredCImportsA = 1;␊ + cImportsA.a = requireAImportsB().a;␊ + return cImportsA;␊ + }␊ + ␊ + var hasRequiredBImportsC;␊ + ␊ + function requireBImportsC () {␊ + if (hasRequiredBImportsC) return bImportsC;␊ + hasRequiredBImportsC = 1;␊ + bImportsC.a = requireCImportsA().a;␊ + return bImportsC;␊ + }␊ + ␊ + var hasRequiredAImportsB;␊ + ␊ + function requireAImportsB () {␊ + if (hasRequiredAImportsB) return aImportsB;␊ + hasRequiredAImportsB = 1;␊ + aImportsB.a = 'a';␊ + t.is(requireBImportsC().a, 'a');␊ + return aImportsB;␊ + }␊ + ␊ + requireAImportsB();␊ ␊ module.exports = main;␊ `, } -## reassigned-module-exports-object +## strict-requires-debug > Snapshot 1 @@ -6786,84 +6305,131 @@ Generated by [AVA](https://avajs.dev). ␊ var main = {};␊ ␊ - var dep$1 = {exports: {}};␊ + var aImportsB = {};␊ ␊ - const exported = {};␊ - dep$1.exports = exported;␊ - dep$1.exports.foo = 'foo';␊ + var bImportsC = {};␊ ␊ - t.deepEqual(exported, { foo: 'foo' });␊ + var cImportsA = {};␊ ␊ - const dep = dep$1.exports;␊ + var hasRequiredCImportsA;␊ ␊ - t.deepEqual(dep, { foo: 'foo' });␊ + function requireCImportsA () {␊ + if (hasRequiredCImportsA) return cImportsA;␊ + hasRequiredCImportsA = 1;␊ + cImportsA.a = requireAImportsB().a;␊ + return cImportsA;␊ + }␊ + ␊ + var hasRequiredBImportsC;␊ + ␊ + function requireBImportsC () {␊ + if (hasRequiredBImportsC) return bImportsC;␊ + hasRequiredBImportsC = 1;␊ + bImportsC.a = requireCImportsA().a;␊ + return bImportsC;␊ + }␊ + ␊ + var hasRequiredAImportsB;␊ + ␊ + function requireAImportsB () {␊ + if (hasRequiredAImportsB) return aImportsB;␊ + hasRequiredAImportsB = 1;␊ + aImportsB.a = 'a';␊ + t.is(requireBImportsC().a, 'a');␊ + return aImportsB;␊ + }␊ + ␊ + requireAImportsB();␊ ␊ module.exports = main;␊ `, } -## reassignment +## strict-requires-debug-none > Snapshot 1 { 'main.js': `'use strict';␊ ␊ - var main = {};␊ - ␊ - function foo$1() {}␊ - foo$1.something = false;␊ - ␊ - var foo_1 = foo$1;␊ - ␊ - let foo = foo_1;␊ - ␊ - if (!foo.something) {␊ - foo = function somethingElse() {};␊ - foo.something = true;␊ - }␊ - ␊ - t.truthy(foo.something);␊ + var main = 'bar';␊ ␊ module.exports = main;␊ `, } -## require-esm-with-named-namespace +## strict-requires-detect-conditionals > Snapshot 1 { 'main.js': `'use strict';␊ ␊ + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + ␊ var main = {};␊ ␊ - const foo = 'foo';␊ - var other = 'bar';␊ + var throws = {};␊ ␊ - var other$1 = /*#__PURE__*/Object.freeze({␊ - __proto__: null,␊ - foo: foo,␊ - 'default': other␊ - });␊ + var hasRequiredThrows;␊ ␊ - var dep$1 = 'default';␊ + function requireThrows () {␊ + if (hasRequiredThrows) return throws;␊ + hasRequiredThrows = 1;␊ + throw new Error('This should never be executed or imported');␊ + }␊ ␊ - var dep$2 = /*#__PURE__*/Object.freeze({␊ - __proto__: null,␊ - 'default': dep$1,␊ - ns: other$1␊ - });␊ + var hoisted = 'this should be top-level';␊ ␊ - const dep = dep$2;␊ + /* eslint-disable global-require */␊ ␊ - t.deepEqual(dep, { default: 'default', ns: { default: 'bar', foo: 'foo' } });␊ + commonjsGlobal.false = false;␊ + commonjsGlobal.true = true;␊ + ␊ + if (commonjsGlobal.false) {␊ + requireThrows();␊ + }␊ + ␊ + if (commonjsGlobal.true) ; else {␊ + requireThrows();␊ + }␊ + ␊ + commonjsGlobal.false ? requireThrows() : null;␊ + commonjsGlobal.true ? null : requireThrows();␊ + ␊ + commonjsGlobal.false && requireThrows();␊ + commonjsGlobal.true || requireThrows();␊ + ␊ + function requireFunctionDeclaration() {␊ + requireThrows();␊ + }␊ + ␊ + const requireFunctionExpression = function () {␊ + requireThrows();␊ + };␊ + ␊ + const requireArrowFunction = () => requireThrows();␊ + ␊ + if (commonjsGlobal.false) {␊ + requireFunctionDeclaration();␊ + requireFunctionExpression();␊ + requireArrowFunction();␊ + }␊ + ␊ + // These should not cause wrapping␊ + t.is(␊ + (function () {␊ + return hoisted;␊ + })(),␊ + 'this should be top-level'␊ + );␊ + t.is((() => hoisted)(), 'this should be top-level');␊ ␊ module.exports = main;␊ `, } -## require-esm-with-namespace-and-default +## strict-requires-entry-node-resolve > Snapshot 1 @@ -6872,245 +6438,375 @@ Generated by [AVA](https://avajs.dev). ␊ var main = {};␊ ␊ - const foo = 'foo';␊ - ␊ - var dep$1 = 'default';␊ - ␊ - var dep$2 = /*#__PURE__*/Object.freeze({␊ - __proto__: null,␊ - 'default': dep$1,␊ - foo: foo␊ - });␊ + var hasRequiredMain;␊ ␊ - const dep = dep$2;␊ + function requireMain () {␊ + if (hasRequiredMain) return main;␊ + hasRequiredMain = 1;␊ + main.foo = 'foo';␊ + return main;␊ + }␊ ␊ - t.deepEqual(dep, { default: 'default', foo: 'foo' });␊ + var mainExports = requireMain();␊ ␊ - module.exports = main;␊ + module.exports = mainExports;␊ `, } -## require-esm-with-namespace-named-default +## strict-requires-exportmode-exports > Snapshot 1 { 'main.js': `'use strict';␊ ␊ + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + ␊ var main = {};␊ ␊ - const foo = 'foo';␊ - var other = 'bar';␊ + var assignExports = {};␊ ␊ - var other$1 = /*#__PURE__*/Object.freeze({␊ - __proto__: null,␊ - foo: foo,␊ - 'default': other␊ - });␊ + var hasRequiredAssignExports;␊ ␊ - const dep = other$1;␊ + function requireAssignExports () {␊ + if (hasRequiredAssignExports) return assignExports;␊ + hasRequiredAssignExports = 1;␊ + assignExports.foo = 'foo';␊ + assignExports.bar = 'bar';␊ + commonjsGlobal.hasAssignExportsRun = true;␊ + return assignExports;␊ + }␊ ␊ - t.deepEqual(dep, { default: 'bar', foo: 'foo' });␊ + var compiledEsm = {};␊ + ␊ + var hasRequiredCompiledEsm;␊ + ␊ + function requireCompiledEsm () {␊ + if (hasRequiredCompiledEsm) return compiledEsm;␊ + hasRequiredCompiledEsm = 1;␊ + compiledEsm.__esModule = true;␊ + Object.defineProperty(compiledEsm, '__esModule', { value: true });␊ + compiledEsm.foo = 'foo';␊ + commonjsGlobal.hasCompiledEsmRun = true;␊ + return compiledEsm;␊ + }␊ + ␊ + var wrappedExports = {};␊ + ␊ + var hasRequiredWrappedExports;␊ + ␊ + function requireWrappedExports () {␊ + if (hasRequiredWrappedExports) return wrappedExports;␊ + hasRequiredWrappedExports = 1;␊ + (function (exports) {␊ + exports.foo = 'foo';␊ + exports = {};␊ + exports.bar = 'bar';␊ + commonjsGlobal.hasWrappedExportsRun = true;␊ + } (wrappedExports));␊ + return wrappedExports;␊ + }␊ + ␊ + t.is(commonjsGlobal.hasAssignExportsRun, undefined, 'before require');␊ + t.deepEqual(requireAssignExports(), { foo: 'foo', bar: 'bar' });␊ + ␊ + t.is(commonjsGlobal.hasAssignExportsRun, true, 'after require');␊ + delete commonjsGlobal.hasAssignExportsRun;␊ + ␊ + t.is(commonjsGlobal.hasCompiledEsmRun, undefined, 'before require');␊ + t.deepEqual(requireCompiledEsm(), { foo: 'foo', __esModule: true });␊ + ␊ + t.is(commonjsGlobal.hasCompiledEsmRun, true, 'after require');␊ + delete commonjsGlobal.hasCompiledEsmRun;␊ + ␊ + t.is(commonjsGlobal.hasWrappedExportsRun, undefined, 'before require');␊ + t.deepEqual(requireWrappedExports(), { foo: 'foo' });␊ + ␊ + t.is(commonjsGlobal.hasWrappedExportsRun, true, 'after require');␊ + delete commonjsGlobal.hasWrappedExportsRun;␊ ␊ module.exports = main;␊ `, } -## require-esm-with-namespace-prefer-default +## strict-requires-exportmode-module > Snapshot 1 { 'main.js': `'use strict';␊ ␊ + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + ␊ var main = {};␊ ␊ - const foo = 'foo';␊ + var assignModuleExports = {exports: {}};␊ ␊ - var dep$1 = /*#__PURE__*/Object.freeze({␊ - __proto__: null,␊ - foo: foo␊ - });␊ + var hasRequiredAssignModuleExports;␊ ␊ - const dep = dep$1;␊ + function requireAssignModuleExports () {␊ + if (hasRequiredAssignModuleExports) return assignModuleExports.exports;␊ + hasRequiredAssignModuleExports = 1;␊ + if (Math.random() > 0.5) {␊ + assignModuleExports.exports = { foo: 'foo' };␊ + } else {␊ + assignModuleExports.exports = { foo: 'foo' };␊ + }␊ + commonjsGlobal.hasAssignModuleExportsRun = true;␊ + return assignModuleExports.exports;␊ + }␊ ␊ - t.deepEqual(dep, { foo: 'foo' });␊ + var assignModuleAndExports = {exports: {}};␊ + ␊ + var hasRequiredAssignModuleAndExports;␊ + ␊ + function requireAssignModuleAndExports () {␊ + if (hasRequiredAssignModuleAndExports) return assignModuleAndExports.exports;␊ + hasRequiredAssignModuleAndExports = 1;␊ + assignModuleAndExports.exports = { foo: 'foo' };␊ + assignModuleAndExports.exports.bar = 'bar';␊ + commonjsGlobal.hasAssignModuleAndExportsRun = true;␊ + return assignModuleAndExports.exports;␊ + }␊ + ␊ + var wrappedModuleExports = {exports: {}};␊ + ␊ + var hasRequiredWrappedModuleExports;␊ + ␊ + function requireWrappedModuleExports () {␊ + if (hasRequiredWrappedModuleExports) return wrappedModuleExports.exports;␊ + hasRequiredWrappedModuleExports = 1;␊ + (function (module, exports) {␊ + module.exports = { foo: 'foo' };␊ + commonjsGlobal.hasWrappedModuleExportsRun = true;␊ + } (wrappedModuleExports));␊ + return wrappedModuleExports.exports;␊ + }␊ + ␊ + t.is(commonjsGlobal.hasAssignModuleExportsRun, undefined, 'before require');␊ + t.is(requireAssignModuleExports().foo, 'foo');␊ + ␊ + t.is(commonjsGlobal.hasAssignModuleExportsRun, true, 'after require');␊ + delete commonjsGlobal.hasAssignModuleExportsRun;␊ + ␊ + t.is(commonjsGlobal.hasAssignModuleAndExportsRun, undefined, 'before require');␊ + t.is(requireAssignModuleAndExports().foo, 'foo');␊ + ␊ + t.is(commonjsGlobal.hasAssignModuleAndExportsRun, true, 'after require');␊ + delete commonjsGlobal.hasAssignModuleAndExportsRun;␊ + ␊ + t.is(commonjsGlobal.hasWrappedModuleExportsRun, undefined, 'before require');␊ + t.is(requireWrappedModuleExports().foo, 'foo');␊ + ␊ + t.is(commonjsGlobal.hasWrappedModuleExportsRun, true, 'after require');␊ + delete commonjsGlobal.hasWrappedModuleExportsRun;␊ ␊ module.exports = main;␊ `, } -## require-snapshotting +## strict-requires-exportmode-replace > Snapshot 1 { 'main.js': `'use strict';␊ ␊ - var main = {};␊ + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ ␊ - var dep$1 = {␊ - foo: 'foo',␊ - update: () => (dep$1 = { foo: 'bar' })␊ - };␊ + var main = {};␊ ␊ - const dep = dep$1;␊ + var replaceModuleExports;␊ + var hasRequiredReplaceModuleExports;␊ ␊ - t.is(dep.foo, 'foo');␊ + function requireReplaceModuleExports () {␊ + if (hasRequiredReplaceModuleExports) return replaceModuleExports;␊ + hasRequiredReplaceModuleExports = 1;␊ + replaceModuleExports = { foo: 'foo' };␊ + commonjsGlobal.hasReplaceModuleExportsRun = true;␊ + return replaceModuleExports;␊ + }␊ ␊ - dep.update();␊ + t.is(commonjsGlobal.hasReplaceModuleExportsRun, undefined, 'before require');␊ + t.is(requireReplaceModuleExports().foo, 'foo');␊ ␊ - t.is(dep.foo, 'foo');␊ - t.is(dep$1.foo, 'bar');␊ + t.is(commonjsGlobal.hasReplaceModuleExportsRun, true, 'after require');␊ + delete commonjsGlobal.hasReplaceModuleExportsRun;␊ ␊ module.exports = main;␊ `, } -## resolve-is-cjs-extension +## strict-requires-external > Snapshot 1 { 'main.js': `'use strict';␊ ␊ - function getAugmentedNamespace(n) {␊ - if (n.__esModule) return n;␊ - var a = Object.defineProperty({}, '__esModule', {value: true});␊ - Object.keys(n).forEach(function (k) {␊ - var d = Object.getOwnPropertyDescriptor(n, k);␊ - Object.defineProperty(a, k, d.get ? d : {␊ - enumerable: true,␊ - get: function () {␊ - return n[k];␊ - }␊ - });␊ - });␊ - return a;␊ - }␊ + var require$$0 = require('external');␊ ␊ - var main = {};␊ + function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }␊ ␊ - const result = 'second';␊ + var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);␊ ␊ - var second = /*#__PURE__*/Object.freeze({␊ - __proto__: null,␊ - result: result␊ - });␊ + var main = {};␊ ␊ - var require$$0 = /*@__PURE__*/getAugmentedNamespace(second);␊ + var hasRequiredMain;␊ ␊ - t.is(require$$0.result, 'second');␊ + function requireMain () {␊ + if (hasRequiredMain) return main;␊ + hasRequiredMain = 1;␊ + t.is(require$$0__default["default"].message, 'it works');␊ + return main;␊ + }␊ ␊ - module.exports = main;␊ + var mainExports = requireMain();␊ + ␊ + module.exports = mainExports;␊ `, } -## resolve-is-cjs-filtered +## strict-requires-file-without-module-type > Snapshot 1 { 'main.js': `'use strict';␊ ␊ - function getAugmentedNamespace(n) {␊ - if (n.__esModule) return n;␊ - var a = Object.defineProperty({}, '__esModule', {value: true});␊ - Object.keys(n).forEach(function (k) {␊ - var d = Object.getOwnPropertyDescriptor(n, k);␊ - Object.defineProperty(a, k, d.get ? d : {␊ - enumerable: true,␊ - get: function () {␊ - return n[k];␊ - }␊ - });␊ - });␊ - return a;␊ - }␊ + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ ␊ var main = {};␊ ␊ - const result = 'second';␊ + var error = {};␊ ␊ - var second = /*#__PURE__*/Object.freeze({␊ - __proto__: null,␊ - result: result␊ - });␊ + var hasRequiredError;␊ ␊ - var require$$0 = /*@__PURE__*/getAugmentedNamespace(second);␊ + function requireError () {␊ + if (hasRequiredError) return error;␊ + hasRequiredError = 1;␊ + throw new Error('FAIL');␊ + }␊ ␊ - t.is(require$$0.result, 'second');␊ + var hasRequiredMain;␊ ␊ - module.exports = main;␊ + function requireMain () {␊ + if (hasRequiredMain) return main;␊ + hasRequiredMain = 1;␊ + commonjsGlobal.null = 0;␊ + ␊ + // eslint-disable-next-line global-require␊ + t.is(commonjsGlobal.null && requireError(), 0);␊ + return main;␊ + }␊ + ␊ + var mainExports = requireMain();␊ + ␊ + module.exports = mainExports;␊ `, } -## shadowed-import +## strict-requires-from-esm > Snapshot 1 { 'main.js': `'use strict';␊ ␊ - var main = {};␊ + var strict = {};␊ ␊ - var foo$1 = 'foo';␊ + var hasRequiredStrict;␊ ␊ - const foo = foo$1;␊ + function requireStrict () {␊ + if (hasRequiredStrict) return strict;␊ + hasRequiredStrict = 1;␊ + strict.foo = 'foo';␊ + return strict;␊ + }␊ ␊ - t.is(foo, 'foo');␊ + var strictExports = requireStrict();␊ ␊ - {␊ - // eslint-disable-next-line no-shadow␊ - const foo = 'wrong';␊ - // eslint-disable-next-line global-require␊ - const bar = foo$1;␊ - t.is(foo, 'wrong');␊ - t.is(bar, 'foo');␊ - }␊ + t.is(requireStrict().foo, 'foo');␊ ␊ - module.exports = main;␊ + t.is(strictExports.foo, 'foo');␊ `, } -## shadowing +## strict-requires-mixed-esm > Snapshot 1 { 'main.js': `'use strict';␊ ␊ - function foo(require) {␊ - require('not-an-actual-require-statement');␊ + var require$1 = {};␊ + ␊ + var hasRequiredRequire;␊ + ␊ + function requireRequire () {␊ + if (hasRequiredRequire) return require$1;␊ + hasRequiredRequire = 1;␊ + require$1.foo = 'foo';␊ + return require$1;␊ }␊ ␊ - let result;␊ + var _import = {};␊ ␊ - foo((msg) => {␊ - result = msg;␊ - });␊ + var hasRequired_import;␊ ␊ - t.is(result, 'not-an-actual-require-statement');␊ + function require_import () {␊ + if (hasRequired_import) return _import;␊ + hasRequired_import = 1;␊ + _import.foo = 'foo';␊ + return _import;␊ + }␊ + ␊ + var _importExports = require_import();␊ + ␊ + const cjs = requireRequire();␊ + ␊ + t.is(_importExports.foo, 'foo');␊ + t.is(cjs.foo, 'foo');␊ `, } -## skips-dead-branches +## strict-requires-multiple-entry > Snapshot 1 { + 'generated-main.js': `'use strict';␊ + ␊ + var main = {};␊ + ␊ + var hasRequiredMain;␊ + ␊ + function requireMain () {␊ + if (hasRequiredMain) return main;␊ + hasRequiredMain = 1;␊ + main.foo = 'foo';␊ + return main;␊ + }␊ + ␊ + exports.requireMain = requireMain;␊ + `, 'main.js': `'use strict';␊ ␊ - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};␊ + var main = require('./generated-main.js');␊ ␊ - commonjsGlobal.b = 2;␊ - var b = 'b';␊ + var mainExports = main.requireMain();␊ ␊ - /* eslint-disable */␊ + module.exports = mainExports;␊ + `, + 'other.js': `'use strict';␊ ␊ - var main = b ;␊ + var main = require('./generated-main.js');␊ ␊ - module.exports = main;␊ + var other = {};␊ + ␊ + t.is(main.requireMain().foo, 'foo');␊ + ␊ + module.exports = other;␊ `, } @@ -7212,11 +6908,11 @@ Generated by [AVA](https://avajs.dev). ␊ (function (module) {␊ ␊ - module.exports = 'bar';␊ - {␊ - return;␊ - }␊ - }(foo$1));␊ + module.exports = 'bar';␊ + {␊ + return;␊ + }␊ + } (foo$1));␊ ␊ const foo = foo$1.exports;␊ ␊ @@ -7253,8 +6949,14 @@ Generated by [AVA](https://avajs.dev). 'main.js': `'use strict';␊ ␊ function getAugmentedNamespace(n) {␊ - if (n.__esModule) return n;␊ - var a = Object.defineProperty({}, '__esModule', {value: true});␊ + var f = n.default;␊ + if (typeof f == "function") {␊ + var a = function () {␊ + return f.apply(this, arguments);␊ + };␊ + a.prototype = f.prototype;␊ + } else a = {};␊ + Object.defineProperty(a, '__esModule', {value: true});␊ Object.keys(n).forEach(function (k) {␊ var d = Object.getOwnPropertyDescriptor(n, k);␊ Object.defineProperty(a, k, d.get ? d : {␊ @@ -7576,153 +7278,385 @@ Generated by [AVA](https://avajs.dev). 'default': _default␊ }, [dep$1]));␊ ␊ - t.deepEqual(dep, {␊ - default: 'default'␊ - });␊ + t.deepEqual(dep, {␊ + default: 'default'␊ + });␊ + ␊ + t.deepEqual(external__namespace, {␊ + default: 'bar'␊ + });␊ + `, + } + +## transpiled-esm-namespace-mixed + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var external = require('external-esm-mixed');␊ + ␊ + 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);␊ + }␊ + ␊ + function _mergeNamespaces(n, m) {␊ + m.forEach(function (e) {␊ + e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) {␊ + if (k !== 'default' && !(k in n)) {␊ + var d = Object.getOwnPropertyDescriptor(e, k);␊ + Object.defineProperty(n, k, d.get ? d : {␊ + enumerable: true,␊ + get: function () { return e[k]; }␊ + });␊ + }␊ + });␊ + });␊ + return Object.freeze(n);␊ + }␊ + ␊ + var external__namespace = /*#__PURE__*/_interopNamespace(external);␊ + ␊ + var dep$1 = {};␊ + ␊ + Object.defineProperty(dep$1, '__esModule', { value: true });␊ + var named = dep$1.named = 'named';␊ + var _default = dep$1.default = 'default';␊ + ␊ + var dep = /*#__PURE__*/Object.freeze(/*#__PURE__*/_mergeNamespaces({␊ + __proto__: null,␊ + named: named,␊ + 'default': _default␊ + }, [dep$1]));␊ + ␊ + t.deepEqual(dep, {␊ + default: 'default',␊ + named: 'named'␊ + });␊ + ␊ + t.deepEqual(external__namespace, {␊ + default: 'bar',␊ + foo: 'foo'␊ + });␊ + `, + } + +## transpiled-esm-namespace-named + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var external = require('external-esm-named');␊ + ␊ + 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);␊ + }␊ + ␊ + function _mergeNamespaces(n, m) {␊ + m.forEach(function (e) {␊ + e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) {␊ + if (k !== 'default' && !(k in n)) {␊ + var d = Object.getOwnPropertyDescriptor(e, k);␊ + Object.defineProperty(n, k, d.get ? d : {␊ + enumerable: true,␊ + get: function () { return e[k]; }␊ + });␊ + }␊ + });␊ + });␊ + return Object.freeze(n);␊ + }␊ + ␊ + var external__namespace = /*#__PURE__*/_interopNamespace(external);␊ + ␊ + var dep$1 = {};␊ + ␊ + Object.defineProperty(dep$1, '__esModule', { value: true });␊ + var named = dep$1.named = 'named';␊ + ␊ + var dep = /*#__PURE__*/Object.freeze(/*#__PURE__*/_mergeNamespaces({␊ + __proto__: null,␊ + named: named,␊ + 'default': dep$1␊ + }, [dep$1]));␊ + ␊ + t.deepEqual(dep, {␊ + default: {␊ + named: 'named'␊ + },␊ + named: 'named'␊ + });␊ + ␊ + t.deepEqual(external__namespace, {␊ + foo: 'foo'␊ + });␊ + `, + } + +## transpiled-esm-nested-module-exports + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + function getDefaultExportFromCjs (x) {␊ + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;␊ + }␊ + ␊ + var dep$1 = {exports: {}};␊ + ␊ + Object.defineProperty(dep$1.exports, '__esModule', { value: true });␊ + ␊ + if (globalValue) {␊ + dep$1.exports = 'first';␊ + } else {␊ + dep$1.exports = 'second';␊ + }␊ + ␊ + var dep = /*@__PURE__*/getDefaultExportFromCjs(dep$1.exports);␊ + ␊ + t.is(dep, 'first');␊ + `, + } + +## transpiled-esm-nested-module-exports2 + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + function getDefaultExportFromCjs (x) {␊ + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;␊ + }␊ + ␊ + var dep$1 = {exports: {}};␊ + ␊ + if (globalValue) {␊ + dep$1.exports = { default: 'first' };␊ + } else {␊ + dep$1.exports = { default: 'second' };␊ + }␊ + ␊ + Object.defineProperty(dep$1.exports, '__esModule', { value: true });␊ + ␊ + var dep = /*@__PURE__*/getDefaultExportFromCjs(dep$1.exports);␊ + ␊ + t.is(dep, 'first');␊ + `, + } + +## transpiled-esm-reexported-default + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + function getDefaultExportFromCjs (x) {␊ + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;␊ + }␊ + ␊ + var proxy = {exports: {}};␊ + ␊ + var dep$1 = {};␊ + ␊ + Object.defineProperty(dep$1, '__esModule', { value: true });␊ + dep$1.default = 'default';␊ + ␊ + (function (module) {␊ + module.exports = dep$1;␊ + } (proxy));␊ + ␊ + var dep = /*@__PURE__*/getDefaultExportFromCjs(proxy.exports);␊ + ␊ + t.is(dep, 'default');␊ + `, + } + +## transpiled-esm-reexported-entry-default + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + function _mergeNamespaces(n, m) {␊ + m.forEach(function (e) {␊ + e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) {␊ + if (k !== 'default' && !(k in n)) {␊ + var d = Object.getOwnPropertyDescriptor(e, k);␊ + Object.defineProperty(n, k, d.get ? d : {␊ + enumerable: true,␊ + get: function () { return e[k]; }␊ + });␊ + }␊ + });␊ + });␊ + return Object.freeze(n);␊ + }␊ + ␊ + function getDefaultExportFromCjs (x) {␊ + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;␊ + }␊ + ␊ + var proxy$1 = {exports: {}};␊ + ␊ + var entry$1 = {};␊ + ␊ + Object.defineProperty(entry$1, '__esModule', { value: true });␊ + entry$1.default = 'default';␊ + ␊ + (function (module) {␊ + module.exports = entry$1;␊ + } (proxy$1));␊ + ␊ + var proxy = /*@__PURE__*/getDefaultExportFromCjs(proxy$1.exports);␊ + ␊ + var entry = /*#__PURE__*/Object.freeze(/*#__PURE__*/_mergeNamespaces({␊ + __proto__: null,␊ + 'default': proxy␊ + }, [proxy$1.exports]));␊ ␊ - t.deepEqual(external__namespace, {␊ - default: 'bar'␊ - });␊ + t.deepEqual(entry, { default: 'default' });␊ `, } -## transpiled-esm-namespace-mixed +## transpiled-esm-reexported-entry-mixed > Snapshot 1 { 'main.js': `'use strict';␊ ␊ - var external = require('external-esm-mixed');␊ - ␊ - 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);␊ + function _mergeNamespaces(n, m) {␊ + m.forEach(function (e) {␊ + e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) {␊ + if (k !== 'default' && !(k in n)) {␊ + var d = Object.getOwnPropertyDescriptor(e, k);␊ + Object.defineProperty(n, k, d.get ? d : {␊ + enumerable: true,␊ + get: function () { return e[k]; }␊ + });␊ + }␊ + });␊ + });␊ + return Object.freeze(n);␊ }␊ ␊ - function _mergeNamespaces(n, m) {␊ - m.forEach(function (e) {␊ - e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) {␊ - if (k !== 'default' && !(k in n)) {␊ - var d = Object.getOwnPropertyDescriptor(e, k);␊ - Object.defineProperty(n, k, d.get ? d : {␊ - enumerable: true,␊ - get: function () { return e[k]; }␊ - });␊ - }␊ - });␊ - });␊ - return Object.freeze(n);␊ + function getDefaultExportFromCjs (x) {␊ + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;␊ }␊ ␊ - var external__namespace = /*#__PURE__*/_interopNamespace(external);␊ + var proxy$1 = {exports: {}};␊ ␊ - var dep$1 = {};␊ + var entry$1 = {};␊ ␊ - Object.defineProperty(dep$1, '__esModule', { value: true });␊ - var named = dep$1.named = 'named';␊ - var _default = dep$1.default = 'default';␊ + Object.defineProperty(entry$1, '__esModule', { value: true });␊ + entry$1.default = 'default';␊ + entry$1.named = 'named';␊ ␊ - var dep = /*#__PURE__*/Object.freeze(/*#__PURE__*/_mergeNamespaces({␊ - __proto__: null,␊ - named: named,␊ - 'default': _default␊ - }, [dep$1]));␊ + (function (module) {␊ + module.exports = entry$1;␊ + } (proxy$1));␊ ␊ - t.deepEqual(dep, {␊ - default: 'default',␊ - named: 'named'␊ - });␊ + var proxy = /*@__PURE__*/getDefaultExportFromCjs(proxy$1.exports);␊ ␊ - t.deepEqual(external__namespace, {␊ - default: 'bar',␊ - foo: 'foo'␊ - });␊ + var entry = /*#__PURE__*/Object.freeze(/*#__PURE__*/_mergeNamespaces({␊ + __proto__: null,␊ + 'default': proxy␊ + }, [proxy$1.exports]));␊ + ␊ + t.deepEqual(entry, { default: 'default', named: 'named' });␊ `, } -## transpiled-esm-namespace-named +## transpiled-esm-reexported-entry-named > Snapshot 1 { 'main.js': `'use strict';␊ ␊ - var external = require('external-esm-named');␊ - ␊ - 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);␊ + function _mergeNamespaces(n, m) {␊ + m.forEach(function (e) {␊ + e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) {␊ + if (k !== 'default' && !(k in n)) {␊ + var d = Object.getOwnPropertyDescriptor(e, k);␊ + Object.defineProperty(n, k, d.get ? d : {␊ + enumerable: true,␊ + get: function () { return e[k]; }␊ + });␊ + }␊ + });␊ + });␊ + return Object.freeze(n);␊ }␊ ␊ - function _mergeNamespaces(n, m) {␊ - m.forEach(function (e) {␊ - e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) {␊ - if (k !== 'default' && !(k in n)) {␊ - var d = Object.getOwnPropertyDescriptor(e, k);␊ - Object.defineProperty(n, k, d.get ? d : {␊ - enumerable: true,␊ - get: function () { return e[k]; }␊ - });␊ - }␊ - });␊ - });␊ - return Object.freeze(n);␊ + function getDefaultExportFromCjs (x) {␊ + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;␊ }␊ ␊ - var external__namespace = /*#__PURE__*/_interopNamespace(external);␊ + var proxy$1 = {exports: {}};␊ ␊ - var dep$1 = {};␊ + var entry$1 = {};␊ ␊ - Object.defineProperty(dep$1, '__esModule', { value: true });␊ - var named = dep$1.named = 'named';␊ + Object.defineProperty(entry$1, '__esModule', { value: true });␊ + entry$1.named = 'named';␊ ␊ - var dep = /*#__PURE__*/Object.freeze(/*#__PURE__*/_mergeNamespaces({␊ - __proto__: null,␊ - named: named,␊ - 'default': dep$1␊ - }, [dep$1]));␊ + (function (module) {␊ + module.exports = entry$1;␊ + } (proxy$1));␊ ␊ - t.deepEqual(dep, {␊ + var proxy = /*@__PURE__*/getDefaultExportFromCjs(proxy$1.exports);␊ + ␊ + var entry = /*#__PURE__*/Object.freeze(/*#__PURE__*/_mergeNamespaces({␊ + __proto__: null,␊ + 'default': proxy␊ + }, [proxy$1.exports]));␊ + ␊ + t.deepEqual(entry, {␊ default: {␊ - named: 'named'␊ + named: 'named',␊ },␊ named: 'named'␊ });␊ - ␊ - t.deepEqual(external__namespace, {␊ - foo: 'foo'␊ - });␊ `, } -## transpiled-esm-nested-module-exports +## transpiled-esm-reexported-mixed > Snapshot 1 @@ -7733,46 +7667,44 @@ Generated by [AVA](https://avajs.dev). return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;␊ }␊ ␊ - var dep$1 = {exports: {}};␊ + var proxy = {exports: {}};␊ ␊ - Object.defineProperty(dep$1.exports, '__esModule', { value: true });␊ + var dep$1 = {};␊ ␊ - if (globalValue) {␊ - dep$1.exports = 'first';␊ - } else {␊ - dep$1.exports = 'second';␊ - }␊ + Object.defineProperty(dep$1, '__esModule', { value: true });␊ + dep$1.named = 'named';␊ + dep$1.default = 'default';␊ ␊ - var dep = /*@__PURE__*/getDefaultExportFromCjs(dep$1.exports);␊ + (function (module) {␊ + module.exports = dep$1;␊ + } (proxy));␊ ␊ - t.is(dep, 'first');␊ + var dep = /*@__PURE__*/getDefaultExportFromCjs(proxy.exports);␊ + ␊ + t.is(dep, 'default');␊ + t.is(proxy.exports.named, 'named');␊ `, } -## transpiled-esm-nested-module-exports2 +## transpiled-esm-reexported-named > Snapshot 1 { 'main.js': `'use strict';␊ ␊ - function getDefaultExportFromCjs (x) {␊ - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;␊ - }␊ - ␊ - var dep$1 = {exports: {}};␊ + var proxy = {exports: {}};␊ ␊ - if (globalValue) {␊ - dep$1.exports = { default: 'first' };␊ - } else {␊ - dep$1.exports = { default: 'second' };␊ - }␊ + var dep = {};␊ ␊ - Object.defineProperty(dep$1.exports, '__esModule', { value: true });␊ + Object.defineProperty(dep, '__esModule', { value: true });␊ + dep.named = 'named';␊ ␊ - var dep = /*@__PURE__*/getDefaultExportFromCjs(dep$1.exports);␊ + (function (module) {␊ + module.exports = dep;␊ + } (proxy));␊ ␊ - t.is(dep, 'first');␊ + t.is(proxy.exports.named, 'named');␊ `, } @@ -7840,6 +7772,8 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ + var main = {};␊ + ␊ /* eslint-disable global-require */␊ ␊ try {␊ @@ -7847,6 +7781,8 @@ Generated by [AVA](https://avajs.dev). } catch (ignored) {␊ /* ignore */␊ }␊ + ␊ + module.exports = main;␊ `, } @@ -7857,6 +7793,8 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ + var main = {};␊ + ␊ /* eslint-disable global-require */␊ ␊ try {␊ @@ -7864,6 +7802,8 @@ Generated by [AVA](https://avajs.dev). } catch (ignored) {␊ /* ignore */␊ }␊ + ␊ + module.exports = main;␊ `, } @@ -7874,6 +7814,8 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ + var main = {};␊ + ␊ /* eslint-disable global-require */␊ ␊ try {␊ @@ -7881,6 +7823,69 @@ Generated by [AVA](https://avajs.dev). } catch (ignored) {␊ /* ignore */␊ }␊ + ␊ + module.exports = main;␊ + `, + } + +## try-catch-internal + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var main = {};␊ + ␊ + var dep = {};␊ + ␊ + var hasRequiredDep;␊ + ␊ + function requireDep () {␊ + if (hasRequiredDep) return dep;␊ + hasRequiredDep = 1;␊ + dep.foo = 'foo';␊ + return dep;␊ + }␊ + ␊ + var throws = {};␊ + ␊ + var hasRequiredThrows;␊ + ␊ + function requireThrows () {␊ + if (hasRequiredThrows) return throws;␊ + hasRequiredThrows = 1;␊ + throw new Error('Expected error');␊ + }␊ + ␊ + /* eslint-disable global-require */␊ + ␊ + try {␊ + t.is(requireDep().foo, 'foo');␊ + } catch (err) {␊ + throw new Error(`Could not require: ${err}`);␊ + }␊ + ␊ + try {␊ + requireThrows();␊ + } catch (err) {␊ + t.is(err.message, 'Expected error');␊ + }␊ + ␊ + module.exports = main;␊ + `, + } + +## try-catch-remove + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var main = {};␊ + ␊ + module.exports = main;␊ `, } @@ -7891,21 +7896,19 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ - function commonjsRequire (path) {␊ + function commonjsRequire(path) {␊ throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ }␊ ␊ - var foo$1 = {exports: {}};␊ + var foo = {exports: {}};␊ ␊ if (typeof commonjsRequire === 'function' && commonjsRequire) {␊ - foo$1.exports = 1;␊ + foo.exports = 'require detected';␊ } else {␊ - foo$1.exports = 2;␊ + foo.exports = 'could not detect require';␊ }␊ ␊ - var foo = foo$1.exports;␊ - ␊ - t.is(foo, 1);␊ + t.is(foo.exports, 'require detected');␊ `, } @@ -7916,21 +7919,19 @@ Generated by [AVA](https://avajs.dev). { 'main.js': `'use strict';␊ ␊ - function commonjsRequire (path) {␊ + function commonjsRequire(path) {␊ throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');␊ }␊ ␊ - var foo$1 = {exports: {}};␊ + var foo = {exports: {}};␊ ␊ if (typeof commonjsRequire === 'function' && commonjsRequire) {␊ - foo$1.exports = 1;␊ + foo.exports = 1;␊ } else {␊ - foo$1.exports = 2;␊ + foo.exports = 2;␊ }␊ ␊ - var foo = foo$1.exports;␊ - ␊ - t.is(foo, 1);␊ + t.is(foo.exports, 1);␊ `, } @@ -7956,3 +7957,20 @@ Generated by [AVA](https://avajs.dev). module.exports = main;␊ `, } + +## warn-this-resolve-without-options + +> Snapshot 1 + + { + 'main.js': `'use strict';␊ + ␊ + var foo$1 = 21;␊ + ␊ + const foo = foo$1;␊ + ␊ + var main = foo * 2;␊ + ␊ + module.exports = main;␊ + `, + } diff --git a/packages/commonjs/test/snapshots/function.js.snap b/packages/commonjs/test/snapshots/function.js.snap index c0d62a8ac..4d687e69a 100644 Binary files a/packages/commonjs/test/snapshots/function.js.snap and b/packages/commonjs/test/snapshots/function.js.snap differ diff --git a/packages/commonjs/test/snapshots/test.js.md b/packages/commonjs/test/snapshots/test.js.md index 507b22d70..a3a119159 100644 --- a/packages/commonjs/test/snapshots/test.js.md +++ b/packages/commonjs/test/snapshots/test.js.md @@ -10,9 +10,19 @@ Generated by [AVA](https://avajs.dev). `'use strict';␊ ␊ + function getDefaultExportFromCjs (x) {␊ + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;␊ + }␊ + ␊ + var main$1 = {exports: {}};␊ + ␊ var require$$0 = "default";␊ ␊ - var main = require$$0;␊ + (function (module) {␊ + module.exports = require$$0;␊ + } (main$1));␊ + ␊ + var main = /*@__PURE__*/getDefaultExportFromCjs(main$1.exports);␊ ␊ module.exports = main;␊ ` @@ -23,9 +33,19 @@ Generated by [AVA](https://avajs.dev). `'use strict';␊ ␊ + function getDefaultExportFromCjs (x) {␊ + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;␊ + }␊ + ␊ function getAugmentedNamespace(n) {␊ - if (n.__esModule) return n;␊ - var a = Object.defineProperty({}, '__esModule', {value: true});␊ + var f = n.default;␊ + if (typeof f == "function") {␊ + var a = function () {␊ + return f.apply(this, arguments);␊ + };␊ + a.prototype = f.prototype;␊ + } else a = {};␊ + Object.defineProperty(a, '__esModule', {value: true});␊ Object.keys(n).forEach(function (k) {␊ var d = Object.getOwnPropertyDescriptor(n, k);␊ Object.defineProperty(a, k, d.get ? d : {␊ @@ -38,6 +58,8 @@ Generated by [AVA](https://avajs.dev). return a;␊ }␊ ␊ + var main$1 = {exports: {}};␊ + ␊ const value = "value";␊ ␊ var esm = /*#__PURE__*/Object.freeze({␊ @@ -47,7 +69,11 @@ Generated by [AVA](https://avajs.dev). ␊ var require$$0 = /*@__PURE__*/getAugmentedNamespace(esm);␊ ␊ - var main = require$$0;␊ + (function (module) {␊ + module.exports = require$$0;␊ + } (main$1));␊ + ␊ + var main = /*@__PURE__*/getDefaultExportFromCjs(main$1.exports);␊ ␊ module.exports = main;␊ ` @@ -95,21 +121,237 @@ Generated by [AVA](https://avajs.dev). module.exports = main;␊ ` -## imports .cjs file extension by default +## does not transform typeof exports for mixed modules + +> Snapshot 1 + + `var foo$1 = 21;␊ + ␊ + const foo = foo$1;␊ + ␊ + if (typeof exports !== 'undefined') {␊ + throw new Error('There should be no global exports in an ES module');␊ + }␊ + ␊ + export { foo as default };␊ + ` + +## handles when an imported dependency of an ES module changes type > Snapshot 1 `'use strict';␊ ␊ - var main = {};␊ + const dep = 'esm';␊ ␊ - var _export = {␊ - test: 42␊ - };␊ + module.exports = dep;␊ + ` + +> Snapshot 2 + + `'use strict';␊ + ␊ + var dep_1 = 'cjs';␊ + ␊ + module.exports = dep_1;␊ + ` + +> Snapshot 3 + + `'use strict';␊ + ␊ + var dep$1 = {};␊ + ␊ + var hasRequiredDep;␊ + ␊ + function requireDep () {␊ + if (hasRequiredDep) return dep$1;␊ + hasRequiredDep = 1;␊ + dep$1.dep = 'cjs'; dep$1.dep += requireDep().dep;␊ + return dep$1;␊ + }␊ + ␊ + var depExports = requireDep();␊ + ␊ + var dep = depExports.dep;␊ + ␊ + module.exports = dep;␊ + ` + +## handles when a required dependency of a CJS module changes type + +> Snapshot 1 + + `'use strict';␊ + ␊ + function getAugmentedNamespace(n) {␊ + var f = n.default;␊ + if (typeof f == "function") {␊ + var a = function () {␊ + return f.apply(this, arguments);␊ + };␊ + a.prototype = f.prototype;␊ + } else a = {};␊ + Object.defineProperty(a, '__esModule', {value: true});␊ + Object.keys(n).forEach(function (k) {␊ + var d = Object.getOwnPropertyDescriptor(n, k);␊ + Object.defineProperty(a, k, d.get ? d : {␊ + enumerable: true,␊ + get: function () {␊ + return n[k];␊ + }␊ + });␊ + });␊ + return a;␊ + }␊ + ␊ + const dep = 'esm';␊ + ␊ + var dep$1 = /*#__PURE__*/Object.freeze({␊ + __proto__: null,␊ + dep: dep␊ + });␊ + ␊ + var require$$0 = /*@__PURE__*/getAugmentedNamespace(dep$1);␊ + ␊ + var main = require$$0.dep;␊ + ␊ + module.exports = main;␊ + ` + +> Snapshot 2 + + `'use strict';␊ + ␊ + var dep = {};␊ + ␊ + dep.dep = 'cjs';␊ + ␊ + var main = dep.dep;␊ + ␊ + module.exports = main;␊ + ` + +> Snapshot 3 + + `'use strict';␊ + ␊ + var dep = {};␊ + ␊ + var hasRequiredDep;␊ + ␊ + function requireDep () {␊ + if (hasRequiredDep) return dep;␊ + hasRequiredDep = 1;␊ + dep.dep = 'cjs'; dep.dep += requireDep().dep;␊ + return dep;␊ + }␊ + ␊ + var main = requireDep().dep;␊ + ␊ + module.exports = main;␊ + ` + +## handles when a required dependency of a mixed ES module changes type + +> Snapshot 1 + + `'use strict';␊ + ␊ + function getAugmentedNamespace(n) {␊ + var f = n.default;␊ + if (typeof f == "function") {␊ + var a = function () {␊ + return f.apply(this, arguments);␊ + };␊ + a.prototype = f.prototype;␊ + } else a = {};␊ + Object.defineProperty(a, '__esModule', {value: true});␊ + Object.keys(n).forEach(function (k) {␊ + var d = Object.getOwnPropertyDescriptor(n, k);␊ + Object.defineProperty(a, k, d.get ? d : {␊ + enumerable: true,␊ + get: function () {␊ + return n[k];␊ + }␊ + });␊ + });␊ + return a;␊ + }␊ + ␊ + const dep = 'esm';␊ + ␊ + var dep$1 = /*#__PURE__*/Object.freeze({␊ + __proto__: null,␊ + dep: dep␊ + });␊ + ␊ + var require$$0 = /*@__PURE__*/getAugmentedNamespace(dep$1);␊ + ␊ + var main = require$$0.dep;␊ + ␊ + module.exports = main;␊ + ` + +> Snapshot 2 + + `'use strict';␊ + ␊ + var dep = {};␊ + ␊ + dep.dep = 'cjs';␊ + ␊ + var main = dep.dep;␊ + ␊ + module.exports = main;␊ + ` + +> Snapshot 3 + + `'use strict';␊ + ␊ + var dep = {};␊ + ␊ + var hasRequiredDep;␊ + ␊ + function requireDep () {␊ + if (hasRequiredDep) return dep;␊ + hasRequiredDep = 1;␊ + dep.dep = 'cjs'; dep.dep += requireDep().dep;␊ + return dep;␊ + }␊ + ␊ + var main = requireDep().dep;␊ + ␊ + module.exports = main;␊ + ` + +## handles ESM cycles when using the cache + +> Snapshot 1 + + `'use strict';␊ + ␊ + console.log('dep');␊ + ␊ + console.log('main');␊ + ` + +## handles external dependencies when using the cache + +> Snapshot 1 + + `'use strict';␊ + ␊ + var require$$0 = require('external');␊ + ␊ + function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }␊ + ␊ + var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);␊ ␊ - const { test } = _export;␊ + var second = require$$0__default["default"].second;␊ ␊ - console.log(test);␊ + var main = require$$0.first + second;␊ ␊ module.exports = main;␊ ` diff --git a/packages/commonjs/test/snapshots/test.js.snap b/packages/commonjs/test/snapshots/test.js.snap index 7289e9012..925f06c48 100644 Binary files a/packages/commonjs/test/snapshots/test.js.snap and b/packages/commonjs/test/snapshots/test.js.snap differ diff --git a/packages/commonjs/test/test.js b/packages/commonjs/test/test.js index c2413d3c1..845bd8d48 100644 --- a/packages/commonjs/test/test.js +++ b/packages/commonjs/test/test.js @@ -1,11 +1,13 @@ /* eslint-disable line-comment-position, no-new-func, no-undefined */ -import * as path from 'path'; import os from 'os'; -import resolve from '@rollup/plugin-node-resolve'; +import * as path from 'path'; + +import nodeResolve from '@rollup/plugin-node-resolve'; import test from 'ava'; import { getLocator } from 'locate-character'; + import { rollup } from 'rollup'; import { SourceMapConsumer } from 'source-map'; import { install } from 'source-map-support'; @@ -19,10 +21,32 @@ install(); process.chdir(__dirname); +const loader = (modules) => { + return { + load(id) { + if (Object.hasOwnProperty.call(modules, id)) { + return modules[id]; + } + return null; + }, + resolveId(id) { + if (Object.hasOwnProperty.call(modules, id)) { + return id; + } + return null; + } + }; +}; + test('Rollup peer dependency has correct format', (t) => { t.regex(peerDependencies.rollup, /^\^\d+\.\d+\.\d+(\|\|\^\d+\.\d+\.\d+)*$/); }); +test('exposes plugin version', (t) => { + const plugin = commonjs(); + t.regex(plugin.version, /^\d+\.\d+\.\d+/); +}); + // most of these should be moved over to function... test('generates a sourcemap', async (t) => { const bundle = await rollup({ @@ -86,7 +110,7 @@ test('supports an object of multiple entry points', async (t) => { b: require.resolve('./fixtures/samples/multiple-entry-points/b.js'), c: require.resolve('./fixtures/samples/multiple-entry-points/c.js') }, - plugins: [resolve(), commonjs()] + plugins: [nodeResolve(), commonjs()] }); const { output } = await bundle.generate({ @@ -207,7 +231,7 @@ test.serial('handles symlinked node_modules with preserveSymlinks: false', (t) = throw new Error(`Unexpected warning: ${warning.message}`); }, plugins: [ - resolve({ + nodeResolve({ preserveSymlinks: false, preferBuiltins: false }), @@ -326,8 +350,8 @@ test('typeof transforms: sinon', async (t) => { } = await bundle.generate({ format: 'es' }); t.is(code.indexOf('typeof require'), -1, code); - // t.not( code.indexOf( 'typeof module' ), -1, code ); // #151 breaks this test - // t.not( code.indexOf( 'typeof define' ), -1, code ); // #144 breaks this test + t.is(code.indexOf('typeof module'), -1, code); + t.is(code.indexOf('typeof define'), -1, code); }); test('deconflicts helper name', async (t) => { @@ -395,7 +419,7 @@ test('rewrites top-level defines', async (t) => { test('respects options.external', async (t) => { const bundle = await rollup({ input: 'fixtures/samples/external/main.js', - plugins: [resolve(), commonjs()], + plugins: [nodeResolve(), commonjs()], external: ['baz'] }); @@ -444,20 +468,18 @@ test('does not warn even if the ES module does not export "default"', async (t) }); test('compiles with cache', async (t) => { - // specific commonjs require() to ensure same instance is used - // eslint-disable-next-line global-require - const commonjsInstance = require('../dist/index'); + const plugin = commonjs(); - const bundle = await rollup({ + const { cache } = await rollup({ input: 'fixtures/function/index/main.js', - plugins: [commonjsInstance()] + plugins: [plugin] }); await t.notThrowsAsync( rollup({ input: 'fixtures/function/index/main.js', - plugins: [commonjsInstance()], - cache: bundle + plugins: [plugin], + cache }) ); }); @@ -542,20 +564,10 @@ test('produces optimized code when importing esm with a known default export', a input: 'main.js', plugins: [ commonjs({ requireReturnsDefault: true }), - { - load(id) { - if (id === 'main.js') { - return 'module.exports = require("esm.js")'; - } - if (id === 'esm.js') { - return 'export const ignored = "ignored"; export default "default"'; - } - return null; - }, - resolveId(id) { - return id; - } - } + loader({ + 'main.js': 'module.exports = require("esm.js")', + 'esm.js': 'export const ignored = "ignored"; export default "default"' + }) ] }); t.snapshot(await getCodeFromBundle(bundle)); @@ -566,20 +578,10 @@ test('produces optimized code when importing esm without a default export', asyn input: 'main.js', plugins: [ commonjs(), - { - load(id) { - if (id === 'main.js') { - return 'module.exports = require("esm.js")'; - } - if (id === 'esm.js') { - return 'export const value = "value";'; - } - return null; - }, - resolveId(id) { - return id; - } - } + loader({ + 'main.js': 'module.exports = require("esm.js")', + 'esm.js': 'export const value = "value";' + }) ] }); t.snapshot(await getCodeFromBundle(bundle)); @@ -619,79 +621,6 @@ test('logs a warning when the deprecated namedExports option is used', async (t) ); }); -test('imports .cjs file extension by default', async (t) => { - const bundle = await rollup({ - input: 'fixtures/samples/cjs-extension/main.js', - plugins: [commonjs()] - }); - t.snapshot(await getCodeFromBundle(bundle)); -}); - -test('registers dynamic requires when entry is from a different loader', async (t) => { - const bundle = await rollup({ - input: 'fixtures/samples/dynamic-require-different-loader/main.js', - plugins: [ - { - load(id) { - if (id === path.resolve('fixtures/samples/dynamic-require-different-loader/main.js')) { - return 'import submodule1 from "./submodule1"; export default submodule1();'; - } - return null; - } - }, - commonjs({ - dynamicRequireTargets: ['fixtures/samples/dynamic-require-different-loader/submodule2.js'], - transformMixedEsModules: true - }) - ] - }); - - t.is((await executeBundle(bundle, t)).exports, 'Hello there'); -}); - -test('transforms the es file with a `commonjsRequire` and no `require`s', async (t) => { - const bundle = await rollup({ - input: 'fixtures/samples/dynamic-require-es-mixed-helpers/main.js', - plugins: [ - commonjs({ - dynamicRequireTargets: ['fixtures/samples/dynamic-require-es-mixed-helpers/submodule.js'], - transformMixedEsModules: true - }) - ] - }); - - const code = await getCodeFromBundle(bundle); - - t.is(/commonjsRequire\(["']\.\/submodule\.js/.test(code), true); -}); - -test('does not wrap commonjsRegister calls in createCommonjsModule', async (t) => { - const bundle = await rollup({ - input: 'fixtures/samples/dynamic-require-double-wrap/main.js', - plugins: [ - commonjs({ - sourceMap: true, - dynamicRequireTargets: ['fixtures/samples/dynamic-require-double-wrap/submodule.js'] - }) - ] - }); - - const code = await getCodeFromBundle(bundle, { exports: 'named' }); - - t.not(/createCommonjsModule\(function/.test(code), true); -}); - -test('does not replace shorthand `require` property in object', async (t) => { - const bundle = await rollup({ - input: 'fixtures/samples/shorthand-require/main.js', - plugins: [commonjs()] - }); - - const code = await getCodeFromBundle(bundle, { exports: 'named' }); - - t.is(/require: commonjsRequire/.test(code), true); -}); - // This test uses worker threads to simulate an empty internal cache and needs at least Node 12 if (Number(/^v(\d+)/.exec(process.version)[1]) >= 12) { test('can be cached across instances', async (t) => { @@ -757,3 +686,526 @@ if (os.platform() === 'win32') { t.regex(code, /var foo(\$\d+)? = {}/); }); } + +test('throws when there is a dynamic require from outside dynamicRequireRoot', async (t) => { + let error = null; + try { + await rollup({ + input: 'fixtures/samples/dynamic-require-outside-root/main.js', + plugins: [ + commonjs({ + dynamicRequireRoot: 'fixtures/samples/dynamic-require-outside-root/nested', + dynamicRequireTargets: ['fixtures/samples/dynamic-require-outside-root/nested/target.js'] + }) + ] + }); + } catch (err) { + error = err; + } + + const cwd = process.cwd(); + const id = path.join(cwd, 'fixtures/samples/dynamic-require-outside-root/main.js'); + const dynamicRequireRoot = path.join(cwd, 'fixtures/samples/dynamic-require-outside-root/nested'); + const minimalDynamicRequireRoot = path.join(cwd, 'fixtures/samples/dynamic-require-outside-root'); + t.like(error, { + message: `"${id}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${dynamicRequireRoot}". You should set dynamicRequireRoot to "${minimalDynamicRequireRoot}" or one of its parent directories.`, + pluginCode: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT', + id, + dynamicRequireRoot + }); +}); + +test('does not transform typeof exports for mixed modules', async (t) => { + const bundle = await rollup({ + input: 'fixtures/samples/mixed-module-typeof-exports/main.js', + plugins: [commonjs({ transformMixedEsModules: true })] + }); + + const { + output: [{ code }] + } = await bundle.generate({ format: 'es' }); + + t.is(code.includes('typeof exports'), true, '"typeof exports" not found in the code'); + t.snapshot(code); +}); + +test('throws when using an old node_resolve version', async (t) => { + let error = null; + try { + await rollup({ + input: 'ignored', + plugins: [commonjs(), { name: nodeResolve().name }] + }); + } catch (err) { + error = err; + } + t.like(error, { + message: + 'Insufficient @rollup/plugin-node-resolve version: "@rollup/plugin-commonjs" requires at least @rollup/plugin-node-resolve@13.0.6.' + }); +}); + +test('throws when using an inadequate node_resolve version', async (t) => { + let error = null; + try { + await rollup({ + input: 'ignored', + plugins: [commonjs(), { name: nodeResolve().name, version: '13.0.5' }] + }); + } catch (err) { + error = err; + } + t.like(error, { + message: + 'Insufficient @rollup/plugin-node-resolve version: "@rollup/plugin-commonjs" requires at least @rollup/plugin-node-resolve@13.0.6 but found @rollup/plugin-node-resolve@13.0.5.' + }); +}); + +const onwarn = (warning) => { + if (warning.code !== 'CIRCULAR_DEPENDENCY') { + throw new Error(warning.message); + } +}; + +const getTransformTracker = (trackedId) => { + const trackedTransforms = []; + const meta = {}; + return { + meta, + trackedTransforms, + tracker: { + name: 'transform-tracker', + transform(code, id) { + trackedTransforms.push(id); + }, + moduleParsed({ id, meta: { commonjs: commonjsMeta } }) { + if (id === trackedId) { + Object.assign(meta, commonjsMeta); + } + } + } + }; +}; + +test('handles when an imported dependency of an ES module changes type', async (t) => { + const { meta, tracker, trackedTransforms } = getTransformTracker('dep.js'); + const modules = {}; + const resetModules = () => { + modules['main.js'] = "import {dep} from 'dep.js';export default dep;"; + modules['dep.js'] = "export const dep = 'esm';"; + }; + const options = { + input: 'main.js', + plugins: [commonjs(), loader(modules), tracker], + onwarn + }; + + resetModules(); + let bundle = await rollup(options); + t.is(meta.isCommonJS, false); + t.deepEqual((await executeBundle(bundle, t)).exports, 'esm'); + t.deepEqual(trackedTransforms, ['main.js', 'dep.js', 'main.js?commonjs-entry']); + trackedTransforms.length = 0; + const esCode = await getCodeFromBundle(bundle); + t.snapshot(esCode); + + modules['dep.js'] = "exports.dep = 'cjs';"; + options.cache = bundle.cache; + bundle = await rollup(options); + t.is(meta.isCommonJS, true); + t.deepEqual((await executeBundle(bundle, t)).exports, 'cjs'); + t.deepEqual(trackedTransforms, ['dep.js', '\0commonjsHelpers.js', '\0dep.js?commonjs-exports']); + trackedTransforms.length = 0; + const cjsCode = await getCodeFromBundle(bundle); + t.snapshot(cjsCode); + + modules['dep.js'] = "exports.dep = 'cjs'; exports.dep += require('dep.js').dep;"; + options.cache = bundle.cache; + bundle = await rollup(options); + t.is(meta.isCommonJS, 'withRequireFunction'); + t.deepEqual((await executeBundle(bundle, t)).exports, 'cjscjs'); + t.deepEqual(trackedTransforms, ['dep.js', 'main.js', '\0dep.js?commonjs-es-import']); + trackedTransforms.length = 0; + const wrappedCode = await getCodeFromBundle(bundle); + t.snapshot(wrappedCode); + + resetModules(); + options.cache = bundle.cache; + bundle = await rollup(options); + t.is(meta.isCommonJS, false); + t.deepEqual((await executeBundle(bundle, t)).exports, 'esm'); + t.deepEqual(trackedTransforms, ['dep.js', 'main.js']); + trackedTransforms.length = 0; + t.is(await getCodeFromBundle(bundle), esCode); + + modules['dep.js'] = "exports.dep = 'cjs'; exports.dep += require('dep.js').dep;"; + options.cache = bundle.cache; + bundle = await rollup(options); + t.is(meta.isCommonJS, 'withRequireFunction'); + t.deepEqual((await executeBundle(bundle, t)).exports, 'cjscjs'); + t.deepEqual(trackedTransforms, [ + 'dep.js', + 'main.js', + '\0dep.js?commonjs-es-import', + '\0commonjsHelpers.js', + '\0dep.js?commonjs-exports' + ]); + trackedTransforms.length = 0; + t.is(await getCodeFromBundle(bundle), wrappedCode); + + modules['dep.js'] = "exports.dep = 'cjs';"; + options.cache = bundle.cache; + bundle = await rollup(options); + t.is(meta.isCommonJS, true); + t.deepEqual((await executeBundle(bundle, t)).exports, 'cjs'); + t.deepEqual(trackedTransforms, ['dep.js', 'main.js']); + trackedTransforms.length = 0; + t.is(await getCodeFromBundle(bundle), cjsCode); + + resetModules(); + options.cache = bundle.cache; + bundle = await rollup(options); + t.is(meta.isCommonJS, false); + t.deepEqual((await executeBundle(bundle, t)).exports, 'esm'); + t.deepEqual(trackedTransforms, ['dep.js']); + trackedTransforms.length = 0; + t.is(await getCodeFromBundle(bundle), esCode); +}); + +test('handles when a dynamically imported dependency of an ES module changes type', async (t) => { + const { meta, tracker, trackedTransforms } = getTransformTracker('dep.js'); + const modules = {}; + const resetModules = () => { + modules['main.js'] = "export default import('dep.js').then(({dep}) => dep);"; + modules['dep.js'] = "export const dep = 'esm';"; + }; + const options = { + input: 'main.js', + plugins: [commonjs(), loader(modules), tracker], + onwarn + }; + + resetModules(); + let bundle = await rollup(options); + t.is(meta.isCommonJS, false); + t.deepEqual(await (await executeBundle(bundle, t)).exports, 'esm'); + t.deepEqual(trackedTransforms, ['main.js', 'main.js?commonjs-entry', 'dep.js']); + trackedTransforms.length = 0; + + modules['dep.js'] = "exports.dep = 'cjs';"; + options.cache = bundle.cache; + bundle = await rollup(options); + t.is(meta.isCommonJS, true); + t.deepEqual(await (await executeBundle(bundle, t)).exports, 'cjs'); + t.deepEqual(trackedTransforms, ['dep.js', '\0commonjsHelpers.js', '\0dep.js?commonjs-exports']); + trackedTransforms.length = 0; + + modules['dep.js'] = "exports.dep = 'cjs'; exports.dep += require('dep.js').dep;"; + options.cache = bundle.cache; + bundle = await rollup(options); + t.is(meta.isCommonJS, 'withRequireFunction'); + t.deepEqual(await (await executeBundle(bundle, t)).exports, 'cjscjs'); + t.deepEqual(trackedTransforms, ['dep.js', 'main.js', '\0dep.js?commonjs-es-import']); + trackedTransforms.length = 0; + + resetModules(); + options.cache = bundle.cache; + bundle = await rollup(options); + t.is(meta.isCommonJS, false); + t.deepEqual(await (await executeBundle(bundle, t)).exports, 'esm'); + t.deepEqual(trackedTransforms, ['dep.js', 'main.js']); + trackedTransforms.length = 0; + + modules['dep.js'] = "exports.dep = 'cjs'; exports.dep += require('dep.js').dep;"; + options.cache = bundle.cache; + bundle = await rollup(options); + t.is(meta.isCommonJS, 'withRequireFunction'); + t.deepEqual(await (await executeBundle(bundle, t)).exports, 'cjscjs'); + t.deepEqual(trackedTransforms, [ + 'dep.js', + 'main.js', + '\0dep.js?commonjs-es-import', + '\0commonjsHelpers.js', + '\0dep.js?commonjs-exports' + ]); + trackedTransforms.length = 0; + + modules['dep.js'] = "exports.dep = 'cjs';"; + options.cache = bundle.cache; + bundle = await rollup(options); + t.is(meta.isCommonJS, true); + t.deepEqual(await (await executeBundle(bundle, t)).exports, 'cjs'); + t.deepEqual(trackedTransforms, ['dep.js', 'main.js']); + trackedTransforms.length = 0; + + resetModules(); + options.cache = bundle.cache; + bundle = await rollup(options); + t.is(meta.isCommonJS, false); + t.deepEqual(await (await executeBundle(bundle, t)).exports, 'esm'); + t.deepEqual(trackedTransforms, ['dep.js']); + trackedTransforms.length = 0; +}); + +test('handles when a required dependency of a CJS module changes type', async (t) => { + const { meta, tracker, trackedTransforms } = getTransformTracker('dep.js'); + const modules = {}; + const resetModules = () => { + modules['main.js'] = "module.exports = require('dep.js').dep;"; + modules['dep.js'] = "export const dep = 'esm';"; + }; + const options = { + input: 'main.js', + plugins: [commonjs(), loader(modules), tracker], + onwarn + }; + + resetModules(); + let bundle = await rollup(options); + t.is(meta.isCommonJS, false); + t.deepEqual((await executeBundle(bundle, t)).exports, 'esm'); + t.deepEqual(trackedTransforms, [ + 'dep.js', + 'main.js', + 'main.js?commonjs-entry', + '\0commonjsHelpers.js', + '\0dep.js?commonjs-proxy' + ]); + trackedTransforms.length = 0; + const esCode = await getCodeFromBundle(bundle); + t.snapshot(esCode); + + modules['dep.js'] = "exports.dep = 'cjs';"; + options.cache = bundle.cache; + bundle = await rollup(options); + t.is(meta.isCommonJS, true); + t.deepEqual((await executeBundle(bundle, t)).exports, 'cjs'); + t.deepEqual(trackedTransforms, [ + 'dep.js', + 'main.js', + '\0dep.js?commonjs-proxy', + '\0dep.js?commonjs-exports' + ]); + trackedTransforms.length = 0; + const cjsCode = await getCodeFromBundle(bundle); + t.snapshot(cjsCode); + + modules['dep.js'] = "exports.dep = 'cjs'; exports.dep += require('dep.js').dep;"; + options.cache = bundle.cache; + bundle = await rollup(options); + t.is(meta.isCommonJS, 'withRequireFunction'); + t.deepEqual((await executeBundle(bundle, t)).exports, 'cjscjs'); + t.deepEqual(trackedTransforms, ['dep.js', 'main.js']); + trackedTransforms.length = 0; + const wrappedCode = await getCodeFromBundle(bundle); + t.snapshot(wrappedCode); + + resetModules(); + options.cache = bundle.cache; + bundle = await rollup(options); + t.is(meta.isCommonJS, false); + t.deepEqual((await executeBundle(bundle, t)).exports, 'esm'); + t.deepEqual(trackedTransforms, ['dep.js', 'main.js', '\0dep.js?commonjs-proxy']); + trackedTransforms.length = 0; + t.is(await getCodeFromBundle(bundle), esCode); + + modules['dep.js'] = "exports.dep = 'cjs'; exports.dep += require('dep.js').dep;"; + options.cache = bundle.cache; + bundle = await rollup(options); + t.is(meta.isCommonJS, 'withRequireFunction'); + t.deepEqual((await executeBundle(bundle, t)).exports, 'cjscjs'); + t.deepEqual(trackedTransforms, ['dep.js', 'main.js', '\0dep.js?commonjs-exports']); + trackedTransforms.length = 0; + t.is(await getCodeFromBundle(bundle), wrappedCode); + + modules['dep.js'] = "exports.dep = 'cjs';"; + options.cache = bundle.cache; + bundle = await rollup(options); + t.is(meta.isCommonJS, true); + t.deepEqual((await executeBundle(bundle, t)).exports, 'cjs'); + t.deepEqual(trackedTransforms, ['dep.js', 'main.js', '\0dep.js?commonjs-proxy']); + trackedTransforms.length = 0; + t.is(await getCodeFromBundle(bundle), cjsCode); + + resetModules(); + options.cache = bundle.cache; + bundle = await rollup(options); + t.is(meta.isCommonJS, false); + t.deepEqual((await executeBundle(bundle, t)).exports, 'esm'); + t.deepEqual(trackedTransforms, ['dep.js', 'main.js', '\0dep.js?commonjs-proxy']); + trackedTransforms.length = 0; + t.is(await getCodeFromBundle(bundle), esCode); +}); + +test('handles when a required dependency of a mixed ES module changes type', async (t) => { + const { meta, tracker, trackedTransforms } = getTransformTracker('dep.js'); + const modules = {}; + const resetModules = () => { + modules['main.js'] = "export default require('dep.js').dep;"; + modules['dep.js'] = "export const dep = 'esm';"; + }; + const options = { + input: 'main.js', + plugins: [commonjs({ transformMixedEsModules: true }), loader(modules), tracker], + onwarn + }; + + resetModules(); + let bundle = await rollup(options); + t.is(meta.isCommonJS, false); + t.deepEqual((await executeBundle(bundle, t)).exports, 'esm'); + t.deepEqual(trackedTransforms, [ + 'dep.js', + 'main.js', + 'main.js?commonjs-entry', + '\0commonjsHelpers.js', + '\0dep.js?commonjs-proxy' + ]); + trackedTransforms.length = 0; + const esCode = await getCodeFromBundle(bundle); + t.snapshot(esCode); + + modules['dep.js'] = "exports.dep = 'cjs';"; + options.cache = bundle.cache; + bundle = await rollup(options); + t.is(meta.isCommonJS, true); + t.deepEqual((await executeBundle(bundle, t)).exports, 'cjs'); + t.deepEqual(trackedTransforms, [ + 'dep.js', + 'main.js', + '\0dep.js?commonjs-proxy', + '\0dep.js?commonjs-exports' + ]); + trackedTransforms.length = 0; + const cjsCode = await getCodeFromBundle(bundle); + t.snapshot(cjsCode); + + modules['dep.js'] = "exports.dep = 'cjs'; exports.dep += require('dep.js').dep;"; + options.cache = bundle.cache; + bundle = await rollup(options); + t.is(meta.isCommonJS, 'withRequireFunction'); + t.deepEqual((await executeBundle(bundle, t)).exports, 'cjscjs'); + t.deepEqual(trackedTransforms, ['dep.js', 'main.js']); + trackedTransforms.length = 0; + const wrappedCode = await getCodeFromBundle(bundle); + t.snapshot(wrappedCode); + + resetModules(); + options.cache = bundle.cache; + bundle = await rollup(options); + t.is(meta.isCommonJS, false); + t.deepEqual((await executeBundle(bundle, t)).exports, 'esm'); + t.deepEqual(trackedTransforms, ['dep.js', 'main.js', '\0dep.js?commonjs-proxy']); + trackedTransforms.length = 0; + t.is(await getCodeFromBundle(bundle), esCode); + + modules['dep.js'] = "exports.dep = 'cjs'; exports.dep += require('dep.js').dep;"; + options.cache = bundle.cache; + bundle = await rollup(options); + t.is(meta.isCommonJS, 'withRequireFunction'); + t.deepEqual((await executeBundle(bundle, t)).exports, 'cjscjs'); + t.deepEqual(trackedTransforms, ['dep.js', 'main.js', '\0dep.js?commonjs-exports']); + trackedTransforms.length = 0; + t.is(await getCodeFromBundle(bundle), wrappedCode); + + modules['dep.js'] = "exports.dep = 'cjs';"; + options.cache = bundle.cache; + bundle = await rollup(options); + t.is(meta.isCommonJS, true); + t.deepEqual((await executeBundle(bundle, t)).exports, 'cjs'); + t.deepEqual(trackedTransforms, ['dep.js', 'main.js', '\0dep.js?commonjs-proxy']); + trackedTransforms.length = 0; + t.is(await getCodeFromBundle(bundle), cjsCode); + + resetModules(); + options.cache = bundle.cache; + bundle = await rollup(options); + t.is(meta.isCommonJS, false); + t.deepEqual((await executeBundle(bundle, t)).exports, 'esm'); + t.deepEqual(trackedTransforms, ['dep.js', 'main.js', '\0dep.js?commonjs-proxy']); + trackedTransforms.length = 0; + t.is(await getCodeFromBundle(bundle), esCode); +}); + +test('handles ESM cycles when using the cache', async (t) => { + const modules = {}; + const resetModules = () => { + modules['main.js'] = "import 'dep.js';console.log('main');"; + modules['dep.js'] = "import 'main.js';console.log('dep');"; + }; + const options = { + input: 'main.js', + plugins: [commonjs(), loader(modules)], + onwarn + }; + + resetModules(); + let bundle = await rollup(options); + + options.cache = bundle.cache; + bundle = await rollup(options); + t.snapshot(await getCodeFromBundle(bundle)); +}); + +test('handles external dependencies when using the cache', async (t) => { + const modules = {}; + const resetModules = () => { + modules['main.js'] = + "import first from 'first.js';import second from 'second.js';export default first + second;"; + modules['first.js'] = "export {first as default} from 'external';"; + modules['second.js'] = "module.exports = require('external').second;"; + }; + const options = { + input: 'main.js', + external: ['external'], + plugins: [commonjs(), loader(modules)], + onwarn + }; + + resetModules(); + let bundle = await rollup(options); + t.is( + ( + await executeBundle(bundle, t, { + context: { + require(id) { + if (id === 'external') { + return { first: 'first', second: 'second' }; + } + throw new Error(`Unexpected require "${id}"`); + } + } + }) + ).exports, + 'firstsecond' + ); + const code = await getCodeFromBundle(bundle); + t.snapshot(code); + + options.cache = bundle.cache; + bundle = await rollup(options); + t.is(await getCodeFromBundle(bundle), code); +}); + +test('allows the config to be reused', async (t) => { + const config = { + preserveModules: true, + plugins: [ + commonjs({ requireReturnsDefault: true }), + loader({ + 'foo.js': "console.log('foo')", + 'bar.js': "console.log('bar')" + }) + ] + }; + let bundle = await rollup({ input: 'foo.js', ...config }); + t.deepEqual( + bundle.cache.modules.map(({ id }) => id), + ['foo.js', 'foo.js?commonjs-entry'] + ); + bundle = await rollup({ input: 'bar.js', ...config }); + t.deepEqual( + bundle.cache.modules.map(({ id }) => id), + ['bar.js', 'bar.js?commonjs-entry'] + ); +}); diff --git a/packages/commonjs/test/types.ts b/packages/commonjs/test/types.ts index 8c010a0d2..67439d3cf 100644 --- a/packages/commonjs/test/types.ts +++ b/packages/commonjs/test/types.ts @@ -20,7 +20,9 @@ const config: RollupOptions = { sourceMap: false, transformMixedEsModules: false, ignore: ['conditional-runtime-dependency'], - dynamicRequireTargets: ['node_modules/logform/*.js'] + dynamicRequireTargets: ['node_modules/logform/*.js'], + dynamicRequireRoot: 'node_modules', + strictRequires: ['node_modules/foo/*.js'] }) ] }; diff --git a/packages/commonjs/types/index.d.ts b/packages/commonjs/types/index.d.ts index 350d54328..febae890d 100644 --- a/packages/commonjs/types/index.d.ts +++ b/packages/commonjs/types/index.d.ts @@ -8,10 +8,10 @@ interface RollupCommonJSOptions { /** * A minimatch pattern, or array of patterns, which specifies the files in * the build the plugin should operate on. By default, all files with - * extension `".cjs"` or those in `extensions` are included, but you can narrow - * this list by only including specific files. These files will be analyzed - * and transpiled if either the analysis does not find ES module specific - * statements or `transformMixedEsModules` is `true`. + * extension `".cjs"` or those in `extensions` are included, but you can + * narrow this list by only including specific files. These files will be + * analyzed and transpiled if either the analysis does not find ES module + * specific statements or `transformMixedEsModules` is `true`. * @default undefined */ include?: FilterPattern; @@ -65,6 +65,39 @@ interface RollupCommonJSOptions { * @default false */ transformMixedEsModules?: boolean; + /** + * By default, this plugin will try to hoist `require` statements as imports + * to the top of each file. While this works well for many code bases and + * allows for very efficient ESM output, it does not perfectly capture + * CommonJS semantics as the order of side effects like log statements may + * change. But it is especially problematic when there are circular `require` + * calls between CommonJS modules as those often rely on the lazy execution of + * nested `require` calls. + * + * Setting this option to `true` will wrap all CommonJS files in functions + * which are executed when they are required for the first time, preserving + * NodeJS semantics. Note that this can have an impact on the size and + * performance of the generated code. + * + * The default value of `"auto"` will only wrap CommonJS files when they are + * part of a CommonJS dependency cycle, e.g. an index file that is required by + * many of its dependencies. All other CommonJS files are hoisted. This is the + * recommended setting for most code bases. + * + * `false` will entirely prevent wrapping and hoist all files. This may still + * work depending on the nature of cyclic dependencies but will often cause + * problems. + * + * You can also provide a minimatch pattern, or array of patterns, to only + * specify a subset of files which should be wrapped in functions for proper + * `require` semantics. + * + * `"debug"` works like `"auto"` but after bundling, it will display a warning + * containing a list of ids that have been wrapped which can be used as + * minimatch pattern for fine-tuning. + * @default "auto" + */ + strictRequires?: boolean | FilterPattern; /** * Sometimes you have to leave require statements unconverted. Pass an array * containing the IDs or a `id => boolean` function. @@ -75,14 +108,16 @@ interface RollupCommonJSOptions { * In most cases, where `require` calls are inside a `try-catch` clause, * they should be left unconverted as it requires an optional dependency * that may or may not be installed beside the rolled up package. - * Due to the conversion of `require` to a static `import` - the call is hoisted - * to the top of the file, outside of the `try-catch` clause. + * Due to the conversion of `require` to a static `import` - the call is + * hoisted to the top of the file, outside of the `try-catch` clause. * * - `true`: All `require` calls inside a `try` will be left unconverted. - * - `false`: All `require` calls inside a `try` will be converted as if the `try-catch` clause is not there. + * - `false`: All `require` calls inside a `try` will be converted as if the + * `try-catch` clause is not there. * - `remove`: Remove all `require` calls from inside any `try` block. * - `string[]`: Pass an array containing the IDs to left unconverted. - * - `((id: string) => boolean|'remove')`: Pass a function that control individual IDs. + * - `((id: string) => boolean|'remove')`: Pass a function that control + * individual IDs. * * @default false */ @@ -173,8 +208,8 @@ interface RollupCommonJSOptions { * Some modules contain dynamic `require` calls, or require modules that * contain circular dependencies, which are not handled well by static * imports. Including those modules as `dynamicRequireTargets` will simulate a - * CommonJS (NodeJS-like) environment for them with support for dynamic and - * circular dependencies. + * CommonJS (NodeJS-like) environment for them with support for dynamic + * dependencies. It also enables `strictRequires` for those modules. * * Note: In extreme cases, this feature may result in some paths being * rendered as absolute in the final bundle. The plugin tries to avoid @@ -183,6 +218,13 @@ interface RollupCommonJSOptions { * replacing strings like `"/Users/John/Desktop/foo-project/"` -> `"/"`. */ dynamicRequireTargets?: string | ReadonlyArray; + /** + * To avoid long paths when using the `dynamicRequireTargets` option, you can use this option to specify a directory + * that is a common parent for all files that use dynamic require statements. Using a directory higher up such as `/` + * may lead to unnecessarily long paths in the generated code and may expose directory names on your machine like your + * home directory name. By default it uses the current working directory. + */ + dynamicRequireRoot?: string; } /** diff --git a/packages/json/src/index.js b/packages/json/src/index.js index 9767e83ca..63e37c280 100755 --- a/packages/json/src/index.js +++ b/packages/json/src/index.js @@ -8,11 +8,11 @@ export default function json(options = {}) { name: 'json', // eslint-disable-next-line no-shadow - transform(json, id) { + transform(code, id) { if (id.slice(-5) !== '.json' || !filter(id)) return null; try { - const parsed = JSON.parse(json); + const parsed = JSON.parse(code); return { code: dataToEsm(parsed, { preferConst: options.preferConst, diff --git a/packages/node-resolve/src/index.js b/packages/node-resolve/src/index.js index ddb1ffb78..8daafcffe 100644 --- a/packages/node-resolve/src/index.js +++ b/packages/node-resolve/src/index.js @@ -242,14 +242,14 @@ export function nodeResolve(opts = {}) { version, - buildStart(options) { - rollupOptions = options; + buildStart(buildOptions) { + rollupOptions = buildOptions; for (const warning of warnings) { this.warn(warning); } - ({ preserveSymlinks } = options); + ({ preserveSymlinks } = buildOptions); }, generateBundle() { diff --git a/packages/run/test/test.js b/packages/run/test/test.js index fdbc808ff..ffba8ea18 100644 --- a/packages/run/test/test.js +++ b/packages/run/test/test.js @@ -99,13 +99,13 @@ test('throws an error when bundle is not written to disk', async (t) => { test('detects changes - forks a new child process and kills older process', async (t) => { // eslint-disable-next-line no-shadow - const input = join(cwd, 'change-detect-input.js'); + const testInput = join(cwd, 'change-detect-input.js'); const bundle = await rollup({ - input, + input: testInput, plugins: [run()] }); await bundle.write(outputOptions); - await writeFile(input, "export const Greeting = () => 'Hola'; // eslint-disable-line"); + await writeFile(testInput, "export const Greeting = () => 'Hola'; // eslint-disable-line"); await bundle.write(outputOptions); t.true(mockChildProcess.calledWithExactly(outputOptions.file, [], {})); t.is(mockChildProcess().kill.callCount, 1); diff --git a/packages/typescript/test/fixtures/export-namespace-export-class/test.ts b/packages/typescript/test/fixtures/export-namespace-export-class/test.ts index 43fc12c68..6565f7c69 100644 --- a/packages/typescript/test/fixtures/export-namespace-export-class/test.ts +++ b/packages/typescript/test/fixtures/export-namespace-export-class/test.ts @@ -2,6 +2,6 @@ // test.ts export namespace MODE { - // eslint-disable-next-line no-shadow + // eslint-disable-next-line no-shadow,@typescript-eslint/no-shadow export class MODE {} } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7da67e89e..41304a331 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -99,18 +99,6 @@ importers: rollup: 2.67.3 typescript: 4.1.2 - packages/auto-install/test/fixtures/pnpm: - specifiers: - node-noop: ^1.0.0 - dependencies: - node-noop: 1.0.0 - - packages/auto-install/test/fixtures/pnpm-bare: - specifiers: - node-noop: ^1.0.0 - dependencies: - node-noop: 1.0.0 - packages/babel: specifiers: '@babel/core': ^7.10.5 @@ -174,7 +162,7 @@ importers: packages/commonjs: specifiers: '@rollup/plugin-json': ^4.1.0 - '@rollup/plugin-node-resolve': ^8.4.0 + '@rollup/plugin-node-resolve': ^13.1.0 '@rollup/pluginutils': ^3.1.0 commondir: ^1.0.1 estree-walker: ^2.0.1 @@ -184,13 +172,13 @@ importers: magic-string: ^0.25.7 require-relative: ^0.8.7 resolve: ^1.17.0 - rollup: ^2.67.3 + rollup: ^2.68.0 shx: ^0.3.2 source-map: ^0.7.3 source-map-support: ^0.5.19 typescript: ^3.9.7 dependencies: - '@rollup/pluginutils': 3.1.0_rollup@2.67.3 + '@rollup/pluginutils': 3.1.0_rollup@2.68.0 commondir: 1.0.1 estree-walker: 2.0.1 glob: 7.1.6 @@ -198,11 +186,11 @@ importers: magic-string: 0.25.7 resolve: 1.18.1 devDependencies: - '@rollup/plugin-json': 4.1.0_rollup@2.67.3 - '@rollup/plugin-node-resolve': 8.4.0_rollup@2.67.3 + '@rollup/plugin-json': 4.1.0_rollup@2.68.0 + '@rollup/plugin-node-resolve': 13.1.3_rollup@2.68.0 locate-character: 2.0.5 require-relative: 0.8.7 - rollup: 2.67.3 + rollup: 2.68.0 shx: 0.3.3 source-map: 0.7.3 source-map-support: 0.5.19 @@ -2166,6 +2154,15 @@ packages: rollup: 2.67.3 dev: true + /@rollup/plugin-json/4.1.0_rollup@2.68.0: + resolution: {integrity: sha512-yfLbTdNS6amI/2OpmbiBoW12vngr5NW2jCJVZSBEz+H5KfUJZ2M7sDjk0U6GOOdCWFVScShte29o9NezJ53TPw==} + peerDependencies: + rollup: ^1.20.0 || ^2.0.0 + dependencies: + '@rollup/pluginutils': 3.1.0_rollup@2.68.0 + rollup: 2.68.0 + dev: true + /@rollup/plugin-node-resolve/10.0.0_rollup@2.67.3: resolution: {integrity: sha512-sNijGta8fqzwA1VwUEtTvWCx2E7qC70NMsDh4ZG13byAXYigBNZMxALhKUSycBks5gupJdq0lFrKumFrRZ8H3A==} engines: {node: '>= 10.0.0'} @@ -2181,6 +2178,21 @@ packages: rollup: 2.67.3 dev: true + /@rollup/plugin-node-resolve/13.1.3_rollup@2.68.0: + resolution: {integrity: sha512-BdxNk+LtmElRo5d06MGY4zoepyrXX1tkzX2hrnPEZ53k78GuOMWLqmJDGIIOPwVRIFZrLQOo+Yr6KtCuLIA0AQ==} + engines: {node: '>= 10.0.0'} + peerDependencies: + rollup: ^2.42.0 + dependencies: + '@rollup/pluginutils': 3.1.0_rollup@2.68.0 + '@types/resolve': 1.17.1 + builtin-modules: 3.2.0 + deepmerge: 4.2.2 + is-module: 1.0.0 + resolve: 1.20.0 + rollup: 2.68.0 + dev: true + /@rollup/plugin-node-resolve/8.4.0_rollup@2.67.3: resolution: {integrity: sha512-LFqKdRLn0ShtQyf6SBYO69bGE1upV6wUhBX0vFOUnLAyzx5cwp8svA0eHUnu8+YU57XOkrMtfG63QOpQx25pHQ==} engines: {node: '>= 8.0.0'} @@ -2288,6 +2300,17 @@ packages: picomatch: 2.2.2 rollup: 2.67.3 + /@rollup/pluginutils/3.1.0_rollup@2.68.0: + resolution: {integrity: sha512-GksZ6pr6TpIjHm8h9lSQ8pi8BE9VeubNT0OMJ3B5uZJ8pz73NPiqOtCog/x2/QzM1ENChPKxMDhiQuRHsqc+lg==} + engines: {node: '>= 8.0.0'} + peerDependencies: + rollup: ^1.20.0||^2.0.0 + dependencies: + '@types/estree': 0.0.39 + estree-walker: 1.0.1 + picomatch: 2.2.2 + rollup: 2.68.0 + /@rollup/pluginutils/4.1.2: resolution: {integrity: sha512-ROn4qvkxP9SyPeHaf7uQC/GPFY6L/OWy9+bd9AwcjOAWQwxRscoEyAUD8qCY5o5iL4jqQwoLk2kaTKJPb/HwzQ==} engines: {node: '>= 8.0.0'} @@ -2484,6 +2507,10 @@ packages: /@types/node/14.14.3: resolution: {integrity: sha512-33/L34xS7HVUx23e0wOT2V1qPF1IrHgQccdJVm9uXGTB9vFBrrzBtkQymT8VskeKOxjz55MSqMv0xuLq+u98WQ==} + dev: true + + /@types/node/16.11.12: + resolution: {integrity: sha512-+2Iggwg7PxoO5Kyhvsq9VarmPbIelXP070HMImEpbtGCoyWNINQj4wzjbQCXzdHTRXnqufutJb5KAURZANNBAw==} /@types/node/16.3.2: resolution: {integrity: sha512-jJs9ErFLP403I+hMLGnqDRWT0RYKSvArxuBVh2veudHV7ifEC1WAmjJADacZ7mRbA2nWgHtn8xyECMAot0SkAw==} @@ -2512,7 +2539,7 @@ packages: /@types/resolve/1.17.1: resolution: {integrity: sha512-yy7HuzQhj0dhGpD8RLXSZWEkLsV9ibvxvi6EiJ3bkqLAO1RGo0WbkWQiwpRlSFymTJRz0d3k5LM3kkx8ArDbLw==} dependencies: - '@types/node': 14.14.3 + '@types/node': 16.11.12 /@types/responselike/1.0.0: resolution: {integrity: sha512-85Y2BjiufFzaMIlvJDvTTB8Fxl2xfLo4HgmHzVBz08w4wDePCTjYw66PdrolO0kzli3yam/YCgRufyo1DdQVTA==} @@ -3211,6 +3238,11 @@ packages: resolution: {integrity: sha512-k0KL0aWZuBt2lrxrcASWDfwOLMnodeQjodT/1SxEQAXsHANgo6ZC/VEaSEHCXt7aSTZ4/4H5LKa+tBXmW7Vtvw==} engines: {node: '>=6'} + /builtin-modules/3.2.0: + resolution: {integrity: sha512-lGzLKcioL90C7wMczpkY0n/oART3MbBa8R9OFGE1rJxoVI86u4WAGfEk8Wjv10eKSyTHVGkSo3bvBylCEtk7LA==} + engines: {node: '>=6'} + dev: true + /cacheable-lookup/5.0.4: resolution: {integrity: sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA==} engines: {node: '>=10.6.0'} @@ -6181,6 +6213,7 @@ packages: /node-noop/1.0.0: resolution: {integrity: sha1-R6Pn2Az/qmRYNkvSLthcqzMHvnk=} + dev: true /node-preload/0.2.1: resolution: {integrity: sha512-RM5oyBy45cLEoHqCeh+MNuFAxO0vTFBLskvQbOKnEE7YTTSN4tbN8QWDIPQ6L+WvKsB/qLEGpYe2ZZ9d4W9OIQ==} @@ -7460,6 +7493,14 @@ packages: fsevents: 2.3.2 dev: true + /rollup/2.68.0: + resolution: {integrity: sha512-XrMKOYK7oQcTio4wyTz466mucnd8LzkiZLozZ4Rz0zQD+HeX4nUK4B8GrTX/2EvN2/vBF/i2WnaXboPxo0JylA==} + engines: {node: '>=10.0.0'} + hasBin: true + optionalDependencies: + fsevents: 2.3.2 + dev: true + /run-parallel/1.1.9: resolution: {integrity: sha512-DEqnSRTDw/Tc3FXf49zedI638Z9onwUotBMiUFKmrO2sdFKIbXamXGQ3Axd4qgphxKB4kw/qP1w5kTxnfU1B9Q==} dev: true