ronantakizawa/codereview-bench huggingface dataset:
Repository: webpack/webpack
File: lib/DotenvPlugin.js (JavaScript)

Code before:
		}

		const startTime = Date.now();
		const newSnapshot = await new Promise((resolve, reject) => {
			fileSystemInfo.createSnapshot(
				startTime,
				fileDependencies,
				null,
				missingDependencies,
				// `.env` files is a build dependencies
				compiler.options.snapshot.buildDependencies,
				(err, snapshot) => {
					if (err) return reject(err);
					resolve(snapshot);
				}
			);
		});

		await itemCache.storePromise({
			parsed,
			snapshot: newSnapshot,
			fileDependencies,
			missingDependencies
		});

		const env = this._getEnv(parsed);

		return { env, snapshot: newSnapshot };
	}

	/**
	 * Generate env variables
	 * @private
	 * @param {Record<string, string>} parsed parsed env variables
	 * @returns {Record<string, string>} env variables
	 */
	_getEnv(parsed) {
		const prefixes = this.options.prefix;

		// Always expand environment variables (like Vite does)
		// Make a copy of process.env so that dotenv-expand doesn't modify global process.env
		const processEnv = { ...process.env };
		expand({ parsed, processEnv });

		// Filter by prefixes and prioritize process.env (like Vite)
		const env = /** @type {Record<string, string>} */ ({});

		// First, add filtered vars from parsed .env files
		for (const [key, value] of Object.entries(parsed)) {
			if (prefixes.some((prefix) => key.startsWith(prefix))) {
				env[key] = value;

Review comment (performance):
We can't cache it because we are looking at `process.env`, technically we can do it, but not sure it is a good solution to use all `process.env` as identifier for cache, I will test

Code after:
						reject(error);

						return;
					}

					resolve(isValid);
				});
			});

			if (isSnapshotValid) {
				return { parsed: result.parsed, snapshot: result.snapshot };
			}
		}

		const { parsed, fileDependencies, missingDependencies } =
			await this._getParsed(
				fs,
				dir,
				/** @type {string} */
				(compiler.options.mode)
			);

		const startTime = Date.now();
		const newSnapshot = await new Promise((resolve, reject) => {
			fileSystemInfo.createSnapshot(
				startTime,
				fileDependencies,
				null,
				missingDependencies,
				// `.env` files are build dependencies
				compiler.options.snapshot.buildDependencies,
				(err, snapshot) => {
					if (err) return reject(err);
					resolve(snapshot);
				}
			);
		});

		await itemCache.storePromise({ parsed, snapshot: newSnapshot });

		return { parsed, snapshot: newSnapshot };
	}

	/**
	 * Generate env variables
	 * @private
	 * @param {Prefix} prefixes expose only environment variables that start with these prefixes
	 * @param {Env} parsed parsed env variables
	 * @returns {Env} env variables
	 */
	_getEnv(prefixes, parsed) {
Repository: webpack/webpack
File: test/configCases/source-map/extract-source-map/extract1.js (JavaScript)

Code before:
"use strict";

const fs = require("fs");
const path = require("path");

require("./test1");
require("./no-source-map")

it("should extract source map - 1", () => {
	const fileData = fs.readFileSync(path.resolve(__dirname, "bundle1.js.map")).toString("utf-8");
	const { sources } = JSON.parse(fileData);
	expect(sources).toMatchSnapshot();
	expect(1).toBe(1)
});


Review comment (suggestion):
This should be `bundle0.js.map`. But it would be better to use `__filename + ".map"`.

Code after:
"use strict";

const fs = require("fs");
const path = require("path");

require("./test1");
require("./no-source-map");

it("should extract source map - 1", () => {
	const fileData = fs.readFileSync(__filename + ".map").toString("utf-8");
	const { sources } = JSON.parse(fileData);
	expect(sources).toContain("webpack:///./extract1.js");
	expect(sources).toContain("webpack:///./charset-inline-source-map.txt");
	expect(sources).toContain("webpack:///./no-source-map.js");
});
Repository: webpack/webpack
File: lib/javascript/JavascriptModulesPlugin.js (JavaScript)

Code before:
							"if(threw) delete __webpack_module_cache__[moduleId];"
						]),
						"}"
					])
				: outputOptions.strictModuleErrorHandling
					? Template.asString([
							"// Execute the module function",
							"try {",
							Template.indent(
								needModuleDefer
									? [
											moduleExecution,
											"delete __webpack_module_deferred_exports__[moduleId];"
										]
									: moduleExecution
							),
							"} catch(e) {",
							Template.indent(["module.error = e;", "throw e;"]),
							"}"
						])
					: Template.asString([
							"// Execute the module function",
							moduleExecution,
							...(needModuleDefer
								? [
										"delete __webpack_module_deferred_exports__[module];",
										"// skipped because strictModuleErrorHandling is not enabled."
									]
								: [])
						]),
			needModuleLoaded
				? Template.asString([
						"",
						"// Flag the module as loaded",
						`${RuntimeGlobals.moduleLoaded} = true;`,
						""
					])
				: "",
			"// Return the exports of the module",
			"return module.exports;"
		]);
		return tryRunOrWebpackError(
			() => hooks.renderRequire.call(content, renderContext),
			"JavascriptModulesPlugin.getCompilationHooks().renderRequire"
		);
	}

	/**
	 * @param {Module[]} allModules allModules
	 * @param {MainRenderContext} renderContext renderContext
	 * @param {Set<Module>} inlinedModules inlinedModules

Review comment (suggestion):
I think it should be `__webpack_module_deferred_exports__[moduleId]`. Also feel free to remove the below comment.

Code after:
							"if(threw) delete __webpack_module_cache__[moduleId];"
						]),
						"}"
					])
				: outputOptions.strictModuleErrorHandling
					? Template.asString([
							"// Execute the module function",
							"try {",
							Template.indent(
								needModuleDefer
									? [
											moduleExecution,
											"delete __webpack_module_deferred_exports__[moduleId];"
										]
									: moduleExecution
							),
							"} catch(e) {",
							Template.indent(["module.error = e;", "throw e;"]),
							"}"
						])
					: Template.asString([
							"// Execute the module function",
							moduleExecution,
							...(needModuleDefer
								? ["delete __webpack_module_deferred_exports__[moduleId];"]
								: [])
						]),
			needModuleLoaded
				? Template.asString([
						"",
						"// Flag the module as loaded",
						`${RuntimeGlobals.moduleLoaded} = true;`,
						""
					])
				: "",
			"// Return the exports of the module",
			"return module.exports;"
		]);
		return tryRunOrWebpackError(
			() => hooks.renderRequire.call(content, renderContext),
			"JavascriptModulesPlugin.getCompilationHooks().renderRequire"
		);
	}

	/**
	 * @param {Module[]} allModules allModules
	 * @param {MainRenderContext} renderContext renderContext
	 * @param {Set<Module>} inlinedModules inlinedModules
	 * @param {ChunkRenderContext} chunkRenderContext chunkRenderContext
	 * @param {CompilationHooks} hooks hooks
	 * @param {boolean | undefined} allStrict allStrict
Repository: webpack/webpack
File: declarations/WebpackOptions.d.ts (TypeScript)

Code before:
	/**
	 * Enable recursive directory lookup for partial dynamic dependencies.
	 */
	wrappedContextRecursive?: boolean;
	/**
	 * Set the inner regular expression for partial dynamic dependencies.
	 */
	wrappedContextRegExp?: RegExp;
}
/**
 * Generator options for json modules.
 */
export interface JsonGeneratorOptions {
	/**
	 * Use `JSON.parse` when the JSON string is longer than 20 characters.
	 */
	JSONParse?: boolean;
}
/**
 * Parser options for JSON modules.
 */
export interface JsonParserOptions {
	/**
	 * Only supports default export.
	 */
	defaultOnly?: boolean;
	/**
	 * The depth of json dependency flagged as `exportInfo`.
	 */
	exportsDepth?: number;
	/**
	 * Function to parser content and return JSON.
	 */
	parse?: import("../lib/json/JsonParser").ParseFn;
}
/**
 * Options for the default backend.
 */
export interface LazyCompilationDefaultBackendOptions {
	/**
	 * A custom client.
	 */
	client?: string;
	/**
	 * Specifies where to listen to from the server.
	 */
	listen?:
		| number
		| import("net").ListenOptions
		| import("../lib/hmr/lazyCompilationBackend").Listen;
	/**

Review comment (suggestion):
Let's use `namedExport`, like we use in webpack for CSS and for other things, by default `true`, but for `{ type: "json" }` is `false`

Code after:
	/**
	 * Disable or configure parsing of WebWorker syntax like new Worker() or navigator.serviceWorker.register().
	 */
	worker?: string[] | boolean;
	/**
	 * Enable warnings for partial dynamic dependencies.
	 */
	wrappedContextCritical?: boolean;
	/**
	 * Enable recursive directory lookup for partial dynamic dependencies.
	 */
	wrappedContextRecursive?: boolean;
	/**
	 * Set the inner regular expression for partial dynamic dependencies.
	 */
	wrappedContextRegExp?: RegExp;
}
/**
 * Generator options for json modules.
 */
export interface JsonGeneratorOptions {
	/**
	 * Use `JSON.parse` when the JSON string is longer than 20 characters.
	 */
	JSONParse?: boolean;
}
/**
 * Parser options for JSON modules.
 */
export interface JsonParserOptions {
	/**
	 * The depth of json dependency flagged as `exportInfo`.
	 */
	exportsDepth?: number;
	/**
	 * Allow named exports for json of object type.
	 */
	namedExports?: boolean;
	/**
	 * Function to parser content and return JSON.
	 */
	parse?: import("../lib/json/JsonParser").ParseFn;
}
/**
 * Options for the default backend.
 */
export interface LazyCompilationDefaultBackendOptions {
	/**
	 * A custom client.
	 */
	client?: string;
Repository: webpack/webpack
File: lib/NodeStuffPlugin.js (JavaScript)

Code before:
								}

								const dep = new ExternalModuleDependency(
									"url",
									[
										{
											name: "fileURLToPath",
											value: "__webpack_fileURLToPath__"
										}
									],
									undefined,
									fn("__webpack_fileURLToPath__"),
									/** @type {Range} */ (expr.range),
									identifier
								);
								dep.loc = /** @type {DependencyLocation} */ (expr.loc);
								parser.state.module.addPresentationalDependency(dep);

								return true;
							});
					};

					/**
					 * @param {string} expressionName expression name
					 * @param {string} value value
					 * @param {string} identifier identifier
					 * @param {string=} warning warning
					 * @returns {void}
					 */
					const setConstant = (expressionName, value, identifier, warning) =>
						setModuleConstant(expressionName, () => value, identifier, warning);

					const context = compiler.context;

					if (localOptions.__filename) {
						switch (localOptions.__filename) {
							case "mock":
								setConstant(filename, "/index.js", "__filename");
								break;
							case "warn-mock":
								setConstant(
									filename,
									"/index.js",
									"__filename",
									"__filename is a Node.js feature and isn't available in browsers."
								);
								break;
							case "node-module": {
								const importMetaName = compilation.outputOptions.importMetaName;

								setUrlModuleConstant(

Review comment (suggestion):
Don't replace `import.meta.dirname` and `import.meta.filename` when env supports them

Code after:

								return true;
							});
					};

					/**
					 * @param {string} expressionName expression name
					 * @param {(value: string) => string} fn function
					 * @param {"dirname" | "filename"} property property
					 * @returns {void}
					 */
					const setUrlModuleConstant = (expressionName, fn, property) => {
						parser.hooks.expression
							.for(expressionName)
							.tap(PLUGIN_NAME, (expr) => {
								const { importMetaName, environment, module } =
									compilation.outputOptions;

								if (
									module &&
									importMetaName === "import.meta" &&
									expressionName.startsWith("import.meta") &&
									environment.importMetaDirnameAndFilename
								) {
									return true;
								}

								const dep = environment.importMetaDirnameAndFilename
									? new CachedConstDependency(
											`${compilation.outputOptions.importMetaName}.${property}`,
											/** @type {Range} */
											(expr.range),
											`__webpack_${property}__`
										)
									: new ExternalModuleDependency(
											"url",
											[
												{
													name: "fileURLToPath",
													value: "__webpack_fileURLToPath__"
												}
											],
											undefined,
											fn("__webpack_fileURLToPath__"),
											/** @type {Range} */ (expr.range),
											`__webpack_${property}__`
										);
								dep.loc = /** @type {DependencyLocation} */ (expr.loc);
								parser.state.module.addPresentationalDependency(dep);

								return true;
Repository: webpack/webpack
File: lib/wasm/EnableWasmLoadingPlugin.js (JavaScript)

Code before:
								compiler.options.output.environment.dynamicImport
						}).apply(compiler);
					}

					if (compiler.options.experiments.asyncWebAssembly) {
						const ReadFileCompileAsyncWasmPlugin = require("../node/ReadFileCompileAsyncWasmPlugin");

						new ReadFileCompileAsyncWasmPlugin({
							import:
								compiler.options.output.module &&
								compiler.options.output.environment.dynamicImport
						}).apply(compiler);
					}

					break;
				}
				case "universal": {
					const UniversalCompileAsyncWasmPlugin = require("../wasm-async/UniversalCompileAsyncWasmPlugin");

					new UniversalCompileAsyncWasmPlugin().apply(compiler);
					break;
				}
				default:
					throw new Error(`Unsupported wasm loading type ${type}.
Plugins which provide custom wasm loading types must call EnableWasmLoadingPlugin.setEnabled(compiler, type) to disable this error.`);
			}
		} else {
			// TODO support plugin instances here
			// apply them to the compiler
		}
	}
}

module.exports = EnableWasmLoadingPlugin;


Review comment (suggestion):
Do not use this plugin when `asyncWebAssembly` is not enabled

Code after:
					}

					if (compiler.options.experiments.asyncWebAssembly) {
						const ReadFileCompileAsyncWasmPlugin = require("../node/ReadFileCompileAsyncWasmPlugin");

						new ReadFileCompileAsyncWasmPlugin({
							import:
								compiler.options.output.module &&
								compiler.options.output.environment.dynamicImport
						}).apply(compiler);
					}

					break;
				}
				case "universal": {
					if (compiler.options.experiments.syncWebAssembly) {
						throw new Error(
							"Universal wasm loading type is only supported by asynchronous web assembly."
						);
					}

					if (compiler.options.experiments.asyncWebAssembly) {
						const UniversalCompileAsyncWasmPlugin = require("../wasm-async/UniversalCompileAsyncWasmPlugin");

						new UniversalCompileAsyncWasmPlugin().apply(compiler);
					}
					break;
				}
				default:
					throw new Error(`Unsupported wasm loading type ${type}.
Plugins which provide custom wasm loading types must call EnableWasmLoadingPlugin.setEnabled(compiler, type) to disable this error.`);
			}
		} else {
			// TODO support plugin instances here
			// apply them to the compiler
		}
	}
}

module.exports = EnableWasmLoadingPlugin;
Repository: webpack/webpack
File: test/configCases/source-map/dual-source-map-plugins/webpack.config.js (JavaScript)

Code before:
"use strict";

const webpack = require("../../../../");

/** @type {import("../../../../").Configuration[]} */
module.exports = [
	{
		devtool: false,
		entry: {
			bundle0: "./entry1.js"
		},
		output: {
			filename: "[name].js"
		},
		optimization: {
			runtimeChunk: true
		},
		plugins: [
			new webpack.SourceMapDevToolPlugin({
				filename: "[file].map",
				test: (name) => name === "bundle0.js"
			}),
			new webpack.SourceMapDevToolPlugin({
				filename: "[file].runtime.map",
				test: /runtime~bundle0\.js/
			})
		]
	},
	{
		entry: {
			bundle1: "./entry2.js"
		},
		devtool: false,
		output: {
			filename: "[name].js"
		},
		optimization: {
			runtimeChunk: true
		},
		plugins: [
			new webpack.EvalDevToolModulePlugin({
				filename: "[file].map",
				test: "bundle1.js"
			}),
			new webpack.SourceMapDevToolPlugin({
				filename: "[file].runtime.map",
				test: ["runtime~bundle1.js"]
			})
		]
	}
];


Review comment (suggestion):
Let's add an extra test when we have two `SourceMapDevToolPlugin` plugins with different configurations 

Code after:
			chunkFilename: "[name].js"
		},
		plugins: [
			new webpack.SourceMapDevToolPlugin({
				filename: "[file].test.map",
				test: "bundle2.js",
				columns: false,
				append: false,
				namespace: "test",
				sourceRoot: "test",
				ignoreList: /entry3\.js/
			}),
			new webpack.SourceMapDevToolPlugin({
				filename: "[file].foo.map",
				test: "chunk-foo.js",
				columns: true,
				publicPath: "sourcemaps/",
				noSources: true,
				append: () => "\n//# sourceMappingURL=http://localhost:8080/foo/[url]",
				namespace: "foo",
				sourceRoot: "foo",
				debugIds: true
			})
		]
	}
];
Repository: webpack/webpack
File: lib/css/CssModulesPlugin.js (JavaScript)

Code before:
		return hooks;
	}

	constructor() {
		/** @type {WeakMap<Source, ModuleFactoryCacheEntry>} */
		this._moduleFactoryCache = new WeakMap();
	}

	/**
	 * Apply the plugin
	 * @param {Compiler} compiler the compiler instance
	 * @returns {void}
	 */
	apply(compiler) {
		compiler.hooks.compilation.tap(
			{
				name: PLUGIN_NAME,
				stage: 100 // ensure we set compilation.dependencyTemplates after JavascriptModulesPlugin
			},
			(compilation, { normalModuleFactory }) => {
				const hooks = CssModulesPlugin.getCompilationHooks(compilation);
				const selfFactory = new SelfModuleFactory(compilation.moduleGraph);
				compilation.dependencyTemplates.set(
					HarmonyImportSideEffectDependency,
					new ProxyHarmonyImportSideEffectDependencyTemplate()
				);
				compilation.dependencyFactories.set(
					CssImportDependency,
					normalModuleFactory
				);
				compilation.dependencyTemplates.set(
					CssImportDependency,
					new CssImportDependency.Template()
				);
				compilation.dependencyFactories.set(
					CssUrlDependency,
					normalModuleFactory
				);
				compilation.dependencyTemplates.set(
					CssUrlDependency,
					new CssUrlDependency.Template()
				);
				compilation.dependencyTemplates.set(
					CssIcssLocalIdentifierDependency,
					new CssIcssLocalIdentifierDependency.Template()
				);
				compilation.dependencyFactories.set(
					CssIcssSelfLocalIdentifierDependency,
					selfFactory
				);
				compilation.dependencyTemplates.set(

Review comment (suggestion):
There is another question, what about `require` or other things, I think we should try to solve it for any cases, not just for side effect imports...

Code after:
	}

	/**
	 * Apply the plugin
	 * @param {Compiler} compiler the compiler instance
	 * @returns {void}
	 */
	apply(compiler) {
		compiler.hooks.compilation.tap(
			PLUGIN_NAME,
			(compilation, { normalModuleFactory }) => {
				const hooks = CssModulesPlugin.getCompilationHooks(compilation);
				compilation.dependencyFactories.set(
					CssImportDependency,
					normalModuleFactory
				);
				compilation.dependencyTemplates.set(
					CssImportDependency,
					new CssImportDependency.Template()
				);
				compilation.dependencyFactories.set(
					CssUrlDependency,
					normalModuleFactory
				);
				compilation.dependencyTemplates.set(
					CssUrlDependency,
					new CssUrlDependency.Template()
				);
				compilation.dependencyFactories.set(
					CssIcssImportDependency,
					normalModuleFactory
				);
				compilation.dependencyTemplates.set(
					CssIcssImportDependency,
					new CssIcssImportDependency.Template()
				);
				compilation.dependencyTemplates.set(
					CssIcssExportDependency,
					new CssIcssExportDependency.Template()
				);
				compilation.dependencyTemplates.set(
					CssIcssSymbolDependency,
					new CssIcssSymbolDependency.Template()
				);
				compilation.dependencyTemplates.set(
					StaticExportsDependency,
					new StaticExportsDependency.Template()
				);
				for (const type of [
					CSS_MODULE_TYPE,
					CSS_MODULE_TYPE_GLOBAL,
Repository: webpack/webpack
File: lib/css/CssGenerator.js (JavaScript)

Code before:
			}
			default:
				return null;
		}
	}

	/**
	 * @param {NormalModule} module fresh module
	 * @returns {SourceTypes} available types (do not mutate)
	 */
	getTypes(module) {
		// if use style-sheet or string exportsType of CSS module, we always need to generate JavaScript output.
		if (this._generatesJsOnly(module)) {
			return JAVASCRIPT_TYPES;
		}
		const sourceTypes = new Set();

		const connections = this._moduleGraph.getIncomingConnections(module);

		// if importer is JavaScript module, we need to generate JavaScript output for it,
		// otherwise we can only generate CSS output.
		for (const connection of connections) {
			// when no hmr required, css module js output contains no sideEffects at all
			// js sideeffect connection doesn't require js type output
			if (
				module.hot !== true &&
				(connection.dependency instanceof HarmonyImportSideEffectDependency ||
					// importer is css module, skip
					connection.dependency instanceof CssImportDependency)
			) {
				continue;
			}

			if (!connection.originModule) {
				continue;
			}

			if (connection.originModule.type.split("/")[0] !== CSS_TYPE) {
				sourceTypes.add(JAVASCRIPT_TYPE);
			}
		}

		if (sourceTypes.has(JAVASCRIPT_TYPE)) {
			return JAVASCRIPT_AND_CSS_TYPES;
		}
		return CSS_TYPES;
	}

	/**
	 * @param {NormalModule} module the module
	 * @param {SourceType=} type source type

Review comment (suggestion):
It seems we can remove the `module.hot !== true` line.
Since we no longer generate JS code for `import "./index.css"`, it doesn’t exist in the output `__webpack_modules__`, Its behavior is closer to being self-accepted. Then will skip generating the side-effect [hmrCode](https://github.com/webpack/webpack/blob/main/lib/css/CssModulesPlugin.js#L403C13-L403C20) for it.

Code after:
			}
			default:
				return null;
		}
	}

	/**
	 * @param {NormalModule} module fresh module
	 * @returns {SourceTypes} available types (do not mutate)
	 */
	getTypes(module) {
		const exportType = /** @type {BuildMeta} */ (module.buildMeta).exportType;
		const sourceTypes = new Set();

		const connections = this._moduleGraph.getIncomingConnections(module);

		for (const connection of connections) {
			if (
				exportType === "link" &&
				connection.dependency instanceof CssImportDependency
			) {
				continue;
			}

			// when no hmr required, css module js output contains no sideEffects at all
			// js sideeffect connection doesn't require js type output
			if (connection.dependency instanceof HarmonyImportSideEffectDependency) {
				continue;
			}

			if (!connection.originModule) {
				continue;
			}

			if (connection.originModule.type.split("/")[0] !== CSS_TYPE) {
				sourceTypes.add(JAVASCRIPT_TYPE);
			} else {
				const originModule = /** @type {CssModule} */ connection.originModule;
				const originExportType = /** @type {BuildMeta} */ (
					originModule.buildMeta
				).exportType;
				if (
					/** @type {boolean} */ (
						originExportType && originExportType !== "link"
					)
				) {
					sourceTypes.add(JAVASCRIPT_TYPE);
				}
			}
		}
		if (this._generatesJsOnly(module)) {