"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 config_exports = {};
__export(config_exports, {
  chainStaticAssetRule: () => chainStaticAssetRule,
  getDefaultDevConfig: () => getDefaultDevConfig,
  getDefaultHtmlConfig: () => getDefaultHtmlConfig,
  getDefaultOutputConfig: () => getDefaultOutputConfig,
  getDefaultPerformanceConfig: () => getDefaultPerformanceConfig,
  getDefaultSecurityConfig: () => getDefaultSecurityConfig,
  getDefaultServerConfig: () => getDefaultServerConfig,
  getDefaultSourceConfig: () => getDefaultSourceConfig,
  getDefaultStyledComponentsConfig: () => getDefaultStyledComponentsConfig,
  getDefaultToolsConfig: () => getDefaultToolsConfig,
  getMinify: () => getMinify,
  outputInspectConfigFiles: () => outputInspectConfigFiles,
  pickRsbuildConfig: () => pickRsbuildConfig,
  setConfig: () => setConfig,
  stringifyConfig: () => stringifyConfig
});
module.exports = __toCommonJS(config_exports);
var import_constants = require("./constants");
var import_logger = require("./logger");
var import_path = require("path");
var import_fs_extra = __toESM(require("../compiled/fs-extra"));
var import_utils = require("./utils");
var import_lodash = __toESM(require("lodash"));
var import_constants2 = require("./constants");
var import_minimize = require("./minimize");
const getDefaultDevConfig = () => ({
  hmr: true,
  assetPrefix: import_constants.DEFAULT_ASSET_PREFIX,
  startUrl: false
});
const getDefaultServerConfig = () => ({
  port: import_constants.DEFAULT_PORT,
  host: import_constants2.DEFAULT_DEV_HOST,
  htmlFallback: "index",
  compress: true,
  publicDir: {
    name: "public",
    copyOnBuild: true
  }
});
const getDefaultSourceConfig = () => ({
  alias: {},
  define: {},
  aliasStrategy: "prefer-tsconfig",
  preEntry: []
});
const getDefaultHtmlConfig = () => ({
  meta: {
    charset: { charset: "UTF-8" },
    viewport: "width=device-width, initial-scale=1.0"
  },
  title: "Rsbuild App",
  inject: "head",
  mountId: import_constants.DEFAULT_MOUNT_ID,
  crossorigin: false,
  outputStructure: "flat",
  scriptLoading: "defer"
});
const getDefaultSecurityConfig = () => ({
  nonce: ""
});
const getDefaultToolsConfig = () => ({
  cssExtract: {
    loaderOptions: {},
    pluginOptions: {}
  }
});
const getDefaultPerformanceConfig = () => ({
  profile: false,
  buildCache: true,
  printFileSize: true,
  removeConsole: false,
  transformLodash: true,
  removeMomentLocale: false,
  chunkSplit: {
    strategy: "split-by-experience"
  }
});
const getDefaultOutputConfig = () => ({
  targets: ["web"],
  distPath: {
    root: import_constants.ROOT_DIST_DIR,
    js: import_constants.JS_DIST_DIR,
    css: import_constants.CSS_DIST_DIR,
    svg: import_constants.SVG_DIST_DIR,
    font: import_constants.FONT_DIST_DIR,
    html: import_constants.HTML_DIST_DIR,
    wasm: import_constants.WASM_DIST_DIR,
    image: import_constants.IMAGE_DIST_DIR,
    media: import_constants.MEDIA_DIST_DIR,
    server: import_constants.SERVER_DIST_DIR,
    worker: import_constants.SERVER_WORKER_DIST_DIR
  },
  assetPrefix: import_constants.DEFAULT_ASSET_PREFIX,
  filename: {},
  charset: "ascii",
  polyfill: "usage",
  dataUriLimit: {
    svg: import_constants.DEFAULT_DATA_URL_SIZE,
    font: import_constants.DEFAULT_DATA_URL_SIZE,
    image: import_constants.DEFAULT_DATA_URL_SIZE,
    media: import_constants.DEFAULT_DATA_URL_SIZE
  },
  legalComments: "linked",
  cleanDistPath: true,
  injectStyles: false,
  disableMinimize: false,
  sourceMap: {
    js: void 0,
    css: false
  },
  disableFilenameHash: false,
  enableLatestDecorators: false,
  enableCssModuleTSDeclaration: false,
  inlineScripts: false,
  inlineStyles: false,
  cssModules: {
    auto: true,
    exportLocalsConvention: "camelCase"
  }
});
async function outputInspectConfigFiles({
  rsbuildConfig,
  rawRsbuildConfig,
  bundlerConfigs,
  inspectOptions,
  configType
}) {
  const { outputPath } = inspectOptions;
  const files = [
    {
      path: (0, import_path.join)(outputPath, "rsbuild.config.js"),
      label: "Rsbuild Config",
      content: rawRsbuildConfig
    },
    ...bundlerConfigs.map((content, index) => {
      const suffix = rsbuildConfig.output.targets[index];
      const outputFile = `${configType}.config.${suffix}.js`;
      let outputFilePath = (0, import_path.join)(outputPath, outputFile);
      if (import_fs_extra.default.existsSync(outputFilePath)) {
        outputFilePath = outputFilePath.replace(/\.js$/, `.${Date.now()}.js`);
      }
      return {
        path: outputFilePath,
        label: `${(0, import_utils.upperFirst)(configType)} Config (${suffix})`,
        content
      };
    })
  ];
  await Promise.all(
    files.map(
      (item) => import_fs_extra.default.outputFile(item.path, `module.exports = ${item.content}`)
    )
  );
  const fileInfos = files.map(
    (item) => `  - ${import_utils.color.bold(import_utils.color.yellow(item.label))}: ${import_utils.color.underline(
      item.path
    )}`
  ).join("\n");
  import_logger.logger.success(
    `Inspect config succeed, open following files to view the content: 

${fileInfos}
`
  );
}
const setConfig = (config, path, value) => {
  import_lodash.default.set(config, path, value);
};
async function getMinify(isProd, config) {
  if (config.output.disableMinimize || !isProd) {
    return false;
  }
  const minifyJS = (await (0, import_minimize.getTerserMinifyOptions)(config)).terserOptions;
  return {
    removeComments: false,
    useShortDoctype: true,
    keepClosingSlash: true,
    collapseWhitespace: true,
    removeRedundantAttributes: true,
    removeScriptTypeAttributes: true,
    removeStyleLinkTypeAttributes: true,
    removeEmptyAttributes: true,
    minifyJS,
    minifyCSS: true,
    minifyURLs: true
  };
}
async function stringifyConfig(config, verbose) {
  const { default: WebpackChain } = await Promise.resolve().then(() => __toESM(require("../compiled/webpack-chain")));
  const stringify = WebpackChain.toString;
  return stringify(config, { verbose });
}
const chainStaticAssetRule = ({
  rule,
  maxSize,
  filename,
  assetType,
  issuer
}) => {
  rule.oneOf(`${assetType}-asset-url`).type("asset/resource").resourceQuery(/(__inline=false|url)/).set("generator", {
    filename
  }).set("issuer", issuer);
  rule.oneOf(`${assetType}-asset-inline`).type("asset/inline").resourceQuery(/inline/).set("issuer", issuer);
  rule.oneOf(`${assetType}-asset`).type("asset").parser({
    dataUrlCondition: {
      maxSize
    }
  }).set("generator", {
    filename
  }).set("issuer", issuer);
};
const getDefaultStyledComponentsConfig = (isProd, ssr) => {
  return {
    ssr,
    // "pure" is used to improve dead code elimination in production.
    // we don't need to enable it in development because it will slow down the build process.
    pure: isProd,
    displayName: true,
    transpileTemplateLiterals: true
  };
};
const pickRsbuildConfig = (rsbuildConfig) => {
  const keys = [
    "dev",
    "server",
    "html",
    "tools",
    "source",
    "output",
    "security",
    "performance"
  ];
  return (0, import_utils.pick)(rsbuildConfig, keys);
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  chainStaticAssetRule,
  getDefaultDevConfig,
  getDefaultHtmlConfig,
  getDefaultOutputConfig,
  getDefaultPerformanceConfig,
  getDefaultSecurityConfig,
  getDefaultServerConfig,
  getDefaultSourceConfig,
  getDefaultStyledComponentsConfig,
  getDefaultToolsConfig,
  getMinify,
  outputInspectConfigFiles,
  pickRsbuildConfig,
  setConfig,
  stringifyConfig
});
