const AliasPlugin = require("enhanced-resolve/lib/AliasPlugin");
const path = require("path");

const webpack = require("webpack");

let mocks = {
  fs: require.resolve("./mock/fs"),
  net: require.resolve("./mock/net"),
  os: require.resolve("./mock/os"),
  child_process: require.resolve("./mock/child_process"),
}

module.exports = class NodeSourcePlugin {
  constructor(options) {
    this.options = options;
  }
  apply(compiler) {
    new webpack.ProvidePlugin({
      "process": path.resolve(path.join(__dirname, './mock/process')),
    }).apply(compiler);
    new webpack.DefinePlugin({
      "process.env": 'globalThis.__nstd_env__',
    }).apply(compiler),

    compiler.hooks.afterResolvers.tap("NodeSourcePlugin", compiler => {
      for (const lib of Object.keys(mocks)) {
	compiler.resolverFactory.hooks.resolver
	  .for("normal")
	  .tap("NodeSourcePlugin", resolver => {
	    new AliasPlugin(
	      "described-resolve",
	      {
		name: lib,
		onlyModule: true,
		alias: mocks[lib],
	      },
	      "resolve"
	    ).apply(resolver);
	  });
      }
    });
  }
};
