const JavaScriptObfuscator = require("javascript-obfuscator");
const fs = require("fs");

// 配置
const buildDir = "./dist/assets/";

const getJsFileList = (dir) =>
  new Promise((resolve, reject) => {
    fs.readdir(dir, (err, files) => {
      if (err) return reject(`待混淆文件目录不存在!`);
      console.log("files:", files);
      return resolve(
        Promise.all(
          files
            .filter((fileName) => fileName.endsWith(".js"))
            .map(
              (fileName) =>
                new Promise((resolveInner) => {
                  fs.readFile(dir + fileName, (err, data) => {
                    console.log("err:", err);
                    return resolveInner({ fileName, content: data.toString() });
                  });
                })
            )
        )
      );
    });
  });

getJsFileList(buildDir).then((list) => {
  console.log(
    `开始代码混淆...`,
    list.map((item) => item.fileName)
  );
  Promise.all(
    list.map(
      (it) =>
        new Promise((resolve) => {
          const obfuscationResult = JavaScriptObfuscator.obfuscate(it.content, {
            /** 这些都是配置 */
            // optionsPreset: "low-obfuscation",
            // disableConsoleOutput: false,
            // controlFlowFlattening: true,
            selfDefending: true,
          });
          fs.writeFile(
            buildDir + it.fileName,
            obfuscationResult.getObfuscatedCode(),
            (err) => {
              if (err) {
                return console.log(`混淆失败文件=>> ${it.fileName}`, err);
              }
              console.log(`已混淆完成文件=>> ${it.fileName}`);
              resolve(1);
            }
          );
        })
    )
  ).then(() => {
    console.log(`代码混淆完成！`);
  });
});
