import platform from "../platform/index.mjs";
import utils from "../utils.mjs";
import isURLSameOrigin from "./isURLSameOrigin.mjs";
import cookies from "./cookies.mjs";
import buildFullPath from "../core/buildFullPath.mjs";
import mergeConfig from "../core/mergeConfig.mjs";
import AxiosHeaders from "../core/AxiosHeaders.mjs";
import buildURL from "./buildURL.mjs";
const FORM_DATA_CONTENT_HEADERS = ["content-type", "content-length"];
function setFormDataHeaders(headers, formHeaders, policy) {
  if (policy !== "content-only") {
    headers.set(formHeaders);
    return;
  }
  Object.entries(formHeaders).forEach(([key, val]) => {
    if (FORM_DATA_CONTENT_HEADERS.includes(key.toLowerCase())) {
      headers.set(key, val);
    }
  });
}
const encodeUTF8 = (str) => encodeURIComponent(str).replace(
  /%([0-9A-F]{2})/gi,
  (_, hex) => String.fromCharCode(parseInt(hex, 16))
);
const resolveConfig = (config) => {
  const newConfig = mergeConfig({}, config);
  const own = (key) => utils.hasOwnProp(newConfig, key) ? newConfig[key] : void 0;
  const data = own("data");
  let withXSRFToken = own("withXSRFToken");
  const xsrfHeaderName = own("xsrfHeaderName");
  const xsrfCookieName = own("xsrfCookieName");
  let headers = own("headers");
  const auth = own("auth");
  const baseURL = own("baseURL");
  const allowAbsoluteUrls = own("allowAbsoluteUrls");
  const url = own("url");
  newConfig.headers = headers = AxiosHeaders.from(headers);
  newConfig.url = buildURL(
    buildFullPath(baseURL, url, allowAbsoluteUrls),
    config.params,
    config.paramsSerializer
  );
  if (auth) {
    headers.set(
      "Authorization",
      "Basic " + btoa((auth.username || "") + ":" + (auth.password ? encodeUTF8(auth.password) : ""))
    );
  }
  if (utils.isFormData(data)) {
    if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
      headers.setContentType(void 0);
    } else if (utils.isFunction(data.getHeaders)) {
      setFormDataHeaders(headers, data.getHeaders(), own("formDataHeaderPolicy"));
    }
  }
  if (platform.hasStandardBrowserEnv) {
    if (utils.isFunction(withXSRFToken)) {
      withXSRFToken = withXSRFToken(newConfig);
    }
    const shouldSendXSRF = withXSRFToken === true || withXSRFToken == null && isURLSameOrigin(newConfig.url);
    if (shouldSendXSRF) {
      const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
      if (xsrfValue) {
        headers.set(xsrfHeaderName, xsrfValue);
      }
    }
  }
  return newConfig;
};
export {
  resolveConfig as default
};
