"use strict";var _WeakMap = require("@babel/runtime-corejs2/core-js/weak-map");var _Object$defineProperty = require("@babel/runtime-corejs2/core-js/object/define-property");var _Object$getOwnPropertyDescriptor = require("@babel/runtime-corejs2/core-js/object/get-own-property-descriptor");var _interopRequireDefault = require("@babel/runtime-corejs2/helpers/interopRequireDefault");_Object$defineProperty(exports, "__esModule", { value: true });exports.default = void 0;var _promise = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/promise"));var _path = _interopRequireDefault(require("path"));
var _index = require("../../cli-shared-utils/index.js");
var paths = _interopRequireWildcard(require("../lib/paths.js"));
var _constanst = require("../lib/constanst.js");
var _readdir = _interopRequireWildcard(require("../lib/readdir.js"));
var _rpk = _interopRequireDefault(require("../lib/rpk.js"));function _getRequireWildcardCache(e) {if ("function" != typeof _WeakMap) return null;var r = new _WeakMap(),t = new _WeakMap();return (_getRequireWildcardCache = function (e) {return e ? t : r;})(e);}function _interopRequireWildcard(e, r) {if (!r && e && e.__esModule) return e;if (null === e || "object" != typeof e && "function" != typeof e) return { default: e };var t = _getRequireWildcardCache(r);if (t && t.has(e)) return t.get(e);var n = { __proto__: null },a = _Object$defineProperty && _Object$getOwnPropertyDescriptor;for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) {var i = a ? _Object$getOwnPropertyDescriptor(e, u) : null;i && (i.get || i.set) ? _Object$defineProperty(n, u, i) : n[u] = e[u];}return n.default = e, t && t.set(e, n), n;}

class ZipWebpackPlugin {
  constructor(options) {
    this.options = options;
  }

  apply(compiler) {
    const pluginName = 'ZipWebpackPlugin';
    /**
     * 获取打原整包的配置
     * @param {Boolean} isRelease 是否是release模式
     * @param {String} packageName 包名
     * @param {Boolean} singlePackage 是否是打原整包
     * @param {Array} subpackages 分包配置
     * @param {String} pluginPath 插件包路径
     * @param {Object} manifest 小游戏配置文件
     * @param {String} buildType 小游戏构建类型
     */
    const { isRelease, packageName, singlePackage, subpackages, manifest, buildType, compileStartTime } = this.options;

    compiler.hooks.afterEmit.tapPromise(pluginName, (compilation) => {
      // 签名文件
      const signFiles = {
        debug: {
          privatekey: paths.DEBUG_PRIVATE_KEY,
          certificate: paths.DEBUG_CERTIFICATE
        },
        release: {
          privatekey: paths.RELEASE_PRIVATE_KEY,
          certificate: paths.RELEASE_CERTIFICATE
        }
      };
      // 编译完成开始打包，打包前先校验签名文件是否存在
      const signFile = signFiles[isRelease ? 'release' : 'debug'];
      // debug包的后缀 .rpk  release包的后缀 .signed.rpk
      // buildType 默认值为release
      let RPK_SIGNED_NEW = _constanst.RPK_SIGNED;
      let RPK_NEW = _constanst.RPK;

      if (buildType && !buildType.includes('release')) {
        RPK_SIGNED_NEW = `.${buildType}${_constanst.RPK_SIGNED}`;
        RPK_NEW = `.${buildType}${_constanst.RPK}`;
      }
      const ext = isRelease ? RPK_SIGNED_NEW : RPK_NEW;

      if (!_index.fs.existsSync(signFile.privatekey)) {
        throw new Error(`${_constanst.LOG_TITLE}缺少私钥文件, 打包失败: ${signFile.privatekey}`);
      }
      if (!_index.fs.existsSync(signFile.certificate)) {
        throw new Error(`${_constanst.LOG_TITLE}缺少证书文件, 打包失败: ${signFile.certificate}`);
      }

      return new _promise.default((resolve) => {
        (0, _index.info)(`${_constanst.LOG_TITLE}${singlePackage ? '原整包编译完成，开始生成原整包' : '分包编译完成，开始生成分包'} 耗时：${new Date().valueOf() - compileStartTime}ms`);

        // 遍历出build目录所有文件
        const files = (0, _readdir.default)(paths.BUILD, isRelease ? _readdir.noDotSymbolsFiles : _readdir.noDotFiles);

        // 如果是打原整包
        if (singlePackage) {
          // 打原整包到temp目录 有插件包的也走这个逻辑，因为需要打个兼容的包
          (0, _rpk.default)(`${packageName}${_constanst.RPK}`, files, paths.BUILD, paths.TEMP, signFile, manifest).then(resolve);
        } else {
          // 如果存在分包，那么就打出各个分包，并和原整包一起再打一个rpk，到dist目录
          const pkgRes = [];
          // 根据分包配置，找到各个包对应的资源。执行如下操作后，files中剩下的即为主包的资源
          subpackages.forEach(({ name, root }) => {
            const matchFiles = [];
            for (let index = files.length - 1; index >= 0; index--) {
              const file = files[index];
              const ext = _path.default.extname(root);

              if (isRelease && !(0, _readdir.noDotSymbolsFiles)(file, 0, _path.default.resolve(paths.BUILD, root))) {
                continue;
              }

              if (ext === '' && file.indexOf(root) === 0) {
                // 如果是目录，校验路径
                matchFiles.push(files.splice(index, 1)[0]);
              } else if (ext !== '' && (file === root || file === `${root}.map`)) {
                // 如果是文件，校验是否为 xxx.js 和 xxx.js.map
                matchFiles.push(files.splice(index, 1)[0]);
              }
            }
            pkgRes.push({
              name,
              matchFiles
            });
          });
          // 打各个分包
          const rpkPromise = pkgRes.map(({ name, matchFiles }) => {
            return (0, _rpk.default)(`${name}${_constanst.RPK}`, matchFiles, paths.BUILD, paths.TEMP, signFile);
          });
          const promiseArr = [(0, _rpk.default)(`${_constanst.MAIN}${_constanst.RPK}`, files, paths.BUILD, paths.TEMP, signFile, manifest)];

          // 分包都打好后，连原整包一起打一个整包
          _promise.default.all([...rpkPromise, ...promiseArr]).then(function () {
            (0, _rpk.default)(`${packageName}${ext}`, (0, _readdir.default)(paths.TEMP), paths.TEMP, paths.DIST, signFile).then(() => {
              resolve();
            });
          });
        }
      });
    });
  }
}var _default = exports.default =

ZipWebpackPlugin;