"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var AutoSetRootFontSizePlugin_exports = {};
__export(AutoSetRootFontSizePlugin_exports, {
  AutoSetRootFontSizePlugin: () => AutoSetRootFontSizePlugin,
  DEFAULT_OPTIONS: () => DEFAULT_OPTIONS,
  genJSTemplate: () => genJSTemplate,
  getRootPixelCode: () => getRootPixelCode
});
module.exports = __toCommonJS(AutoSetRootFontSizePlugin_exports);
var import_path = __toESM(require("path"));
var import_rslog = require("rslog");
var import_url = require("../url");
var import_util = require("./util");
var import_webpack_sources = __toESM(require("../../compiled/webpack-sources"));
async function getRootPixelCode(options, isCompress = false) {
  const code = genJSTemplate(options);
  if (!isCompress) {
    return code;
  }
  const { minify } = await Promise.resolve().then(() => __toESM(require("terser")));
  const { code: minifiedRuntimeCode } = await minify(
    {
      RootPixelCode: code
    },
    {
      ecma: 5
    }
  );
  return minifiedRuntimeCode;
}
const DEFAULT_OPTIONS = {
  screenWidth: 375,
  rootFontSize: 50,
  maxRootFontSize: 64,
  widthQueryKey: "",
  rootFontSizeVariableName: "ROOT_FONT_SIZE",
  excludeEntries: [],
  inlineRuntime: true,
  supportLandscape: false,
  useRootFontSizeBeyondMax: false
};
class AutoSetRootFontSizePlugin {
  constructor(options, entries, HtmlPlugin, distDir) {
    this.name = "AutoSetRootFontSizePlugin";
    this.options = { ...DEFAULT_OPTIONS, ...options || {} };
    this.scriptPath = "";
    this.distDir = distDir;
    this.webpackEntries = entries;
    this.HtmlPlugin = HtmlPlugin;
  }
  async getScriptPath() {
    if (!this.scriptPath) {
      const version = await (0, import_util.getRsbuildVersion)();
      this.scriptPath = import_path.default.join(this.distDir, `convert-rem.${version}.js`);
    }
    return this.scriptPath;
  }
  apply(compiler) {
    let runtimeCode;
    const getRuntimeCode = async () => {
      if (!runtimeCode) {
        const isCompress = process.env.NODE_ENV === "production";
        runtimeCode = await getRootPixelCode(this.options, isCompress);
      }
      return runtimeCode;
    };
    if (!this.options.inlineRuntime) {
      compiler.hooks.thisCompilation.tap(
        this.name,
        (compilation) => {
          compilation.hooks.processAssets.tapPromise(
            {
              name: this.name,
              stage: import_util.COMPILATION_PROCESS_STAGE.PROCESS_ASSETS_STAGE_PRE_PROCESS
            },
            async (assets) => {
              const scriptPath = await this.getScriptPath();
              assets[scriptPath] = new import_webpack_sources.default.RawSource(
                await getRuntimeCode(),
                false
              );
            }
          );
        }
      );
    }
    compiler.hooks.compilation.tap(this.name, (compilation) => {
      this.HtmlPlugin.getHooks(compilation).alterAssetTagGroups.tapPromise(
        this.name,
        async (data) => {
          const isExclude = this.options.excludeEntries.find((item) => {
            if (!this.webpackEntries.includes(item)) {
              import_rslog.logger.error(`convertToRem: can't find the entryName: ${item}`);
              return false;
            }
            const reg = new RegExp(
              `(/${item}/index.html)|(/${item}.html)`,
              "gi"
            );
            return reg.test(data.outputName);
          });
          if (isExclude) {
            return data;
          }
          const scriptTag = (0, import_util.generateScriptTag)();
          if (this.options.inlineRuntime) {
            data.headTags.unshift({
              ...scriptTag,
              innerHTML: await getRuntimeCode()
            });
          } else {
            const publicPath = (0, import_util.getPublicPathFromCompiler)(compiler);
            const url = (0, import_url.withPublicPath)(await this.getScriptPath(), publicPath);
            data.headTags.unshift({
              ...scriptTag,
              attributes: {
                ...scriptTag.attributes,
                src: url
              }
            });
          }
          return data;
        }
      );
    });
  }
}
const genJSTemplate = (opts) => `function setRootPixel() {
  function getQuery(name) {
    return (new RegExp('[?&]' + name + '=([^&#\\b]+)').exec(location.search || '') || [])[1];
  }

  function setRootFontSize() {
    var widthQueryKey = '${opts.widthQueryKey}';
    var rem2px = ${opts.rootFontSize};
    var clientWidth;
    var docEl = document.documentElement;
    if (widthQueryKey && (+getQuery(widthQueryKey))) {
      clientWidth = +getQuery(widthQueryKey);
    } else {
      clientWidth = window.innerWidth && docEl.clientWidth ?
        Math.min(window.innerWidth, docEl.clientWidth) :
        (window.innerWidth || docEl.clientWidth || (document.body && document.body.clientWidth) || ${opts.screenWidth});
        ${opts.supportLandscape ? `
        var isLandscape = ((screen.orientation && screen.orientation.angle) || window.orientation) / 90 % 2;
        if (isLandscape) {
          var clientHeight = window.innerHeight && docEl.clientHeight ?
          Math.min(window.innerHeight, docEl.clientHeight) :
          (window.innerHeight || docEl.clientHeight || (document.body && document.body.clientHeight) || ${opts.screenWidth});

          clientWidth = Math.max(clientHeight, 350);
        }` : ""}
    }

    var htmlFontSizePx = (clientWidth * rem2px) / ${opts.screenWidth};
    var maxRootFontSize = ${opts.maxRootFontSize};

    ${opts.useRootFontSizeBeyondMax ? `htmlFontSizePx = htmlFontSizePx < maxRootFontSize ? htmlFontSizePx : rem2px ;` : `htmlFontSizePx = Math.min(htmlFontSizePx, maxRootFontSize);`}

    window.${opts.rootFontSizeVariableName} = htmlFontSizePx;
    docEl.style.fontSize = htmlFontSizePx + 'px';
  }

  function adjust(immediate) {
    if (immediate) {
      setRootFontSize();
      return;
    }
    setTimeout(setRootFontSize, 30);
  }

  adjust(true);

  window.addEventListener('resize', adjust, false);

  if ('onorientationchange' in window) {
    window.addEventListener('orientationchange', adjust, false);
  }
}

typeof window !== 'undefined' && setRootPixel();`;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  AutoSetRootFontSizePlugin,
  DEFAULT_OPTIONS,
  genJSTemplate,
  getRootPixelCode
});
