const path = require('path');
const NodeExternals = require('webpack-node-externals');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const WebpackObfuscator = require('webpack-obfuscator');

module.exports = {
  target: 'node',
  entry: path.resolve(__dirname, 'app.js'),
  mode: 'production',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'server.js',
  },
  // 不打包 node_modules，减少体积并避免原生模块问题
  externals: [NodeExternals()],
  resolve: {
    extensions: ['.js'],
  },
  // 保持 Node 的 __dirname/__filename 语义，指向 dist 目录
  node: {
    __dirname: false,
    __filename: false,
  },
  // 这里不使用 source-map，以免暴露过多信息
  plugins: [
    // 将运行期需要的资产复制到 dist 根目录，以适配打包后 __dirname 指向 dist
    new CopyWebpackPlugin({
      patterns: [
        { from: path.resolve(__dirname, 'farmeworkapi/.env'), to: path.resolve(__dirname, 'dist/.env'), toType: 'file', noErrorOnMissing: true },
        { from: path.resolve(__dirname, 'farmeworkapi/pub.pem'), to: path.resolve(__dirname, 'dist/pub.pem'), noErrorOnMissing: true },
      ],
    }),
    // 在打包产物上进行混淆
    new WebpackObfuscator({
      compact: true,
      controlFlowFlattening: false, // 为稳定性，默认关闭；如需更强混淆可开启
      deadCodeInjection: false,
      stringArray: true,
      rotateStringArray: true,
      stringArrayEncoding: ['rc4'],
      stringArrayThreshold: 0.75,
      disableConsoleOutput: false,
    }),
  ],
};

