"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 src_exports = {};
__export(src_exports, {
  default: () => fetchCookie
});
module.exports = __toCommonJS(src_exports);
var tough = __toESM(require("tough-cookie"), 1);
var import_set_cookie_parser = require("set-cookie-parser");
function isDomainOrSubdomain(destination, original) {
  const orig = new URL(original).hostname;
  const dest = new URL(destination).hostname;
  return orig === dest || orig.endsWith(`.${dest}`);
}
const referrerPolicy = /* @__PURE__ */ new Set([
  "",
  "no-referrer",
  "no-referrer-when-downgrade",
  "same-origin",
  "origin",
  "strict-origin",
  "origin-when-cross-origin",
  "strict-origin-when-cross-origin",
  "unsafe-url"
]);
function parseReferrerPolicy(policyHeader) {
  const policyTokens = policyHeader.split(/[,\s]+/);
  let policy = "";
  for (const token of policyTokens) {
    if (token !== "" && referrerPolicy.has(token)) {
      policy = token;
    }
  }
  return policy;
}
function doNothing(init, name) {
}
function callDeleteMethod(init, name) {
  init.headers.delete(name);
}
function deleteFromObject(init, name) {
  const headers = init.headers;
  for (const key of Object.keys(headers)) {
    if (key.toLowerCase() === name) {
      delete headers[key];
    }
  }
}
function identifyDeleteHeader(init) {
  if (init.headers == null) {
    return doNothing;
  }
  if (typeof init.headers.delete === "function") {
    return callDeleteMethod;
  }
  return deleteFromObject;
}
const redirectStatus = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
function isRedirect(status) {
  return redirectStatus.has(status);
}
async function handleRedirect(fetchImpl, init, response) {
  switch (init.redirect ?? "follow") {
    case "error":
      throw new TypeError(`URI requested responded with a redirect and redirect mode is set to error: ${response.url}`);
    case "manual":
      return response;
    case "follow":
      break;
    default:
      throw new TypeError(`Invalid redirect option: ${init.redirect}`);
  }
  const locationUrl = response.headers.get("location");
  if (locationUrl === null) {
    return response;
  }
  const requestUrl = response.url;
  const redirectUrl = new URL(locationUrl, requestUrl).toString();
  const redirectCount = init.redirectCount ?? 0;
  const maxRedirect = init.maxRedirect ?? 20;
  if (redirectCount >= maxRedirect) {
    throw new TypeError(`Reached maximum redirect of ${maxRedirect} for URL: ${requestUrl}`);
  }
  init = {
    ...init,
    redirectCount: redirectCount + 1
  };
  const deleteHeader = identifyDeleteHeader(init);
  if (!isDomainOrSubdomain(requestUrl, redirectUrl)) {
    for (const name of ["authorization", "www-authenticate", "cookie", "cookie2"]) {
      deleteHeader(init, name);
    }
  }
  const maybeNodeStreamBody = init.body;
  const maybeStreamBody = init.body;
  if (response.status !== 303 && init.body != null && (typeof maybeNodeStreamBody.pipe === "function" || typeof maybeStreamBody.pipeTo === "function")) {
    throw new TypeError("Cannot follow redirect with body being a readable stream");
  }
  if (response.status === 303 || (response.status === 301 || response.status === 302) && init.method === "POST") {
    init.method = "GET";
    init.body = void 0;
    deleteHeader(init, "content-length");
  }
  if (response.headers.has("referrer-policy")) {
    init.referrerPolicy = parseReferrerPolicy(response.headers.get("referrer-policy"));
  }
  deleteHeader(init, "host");
  return await fetchImpl(redirectUrl, init);
}
function addCookiesToRequest(input, init, cookie) {
  if (cookie === "") {
    return init;
  }
  const maybeRequest = input;
  const maybeHeaders = init.headers;
  if (maybeRequest.headers && typeof maybeRequest.headers.append === "function") {
    maybeRequest.headers.append("cookie", cookie);
  } else if (maybeHeaders && typeof maybeHeaders.append === "function") {
    maybeHeaders.append("cookie", cookie);
  } else if (Array.isArray(init.headers)) {
    const headers = [...init.headers];
    const cookieHeaderIndex = headers.findIndex((header) => header[0].toLowerCase() === "cookie");
    if (cookieHeaderIndex === -1) {
      headers.push(["cookie", cookie]);
    } else {
      headers[cookieHeaderIndex] = ["cookie", cookie];
    }
    init = { ...init, headers };
  } else {
    init = { ...init, headers: { ...init.headers, cookie } };
  }
  return init;
}
function getCookiesFromResponse(response) {
  const maybeNodeFetchHeaders = response.headers;
  if (typeof maybeNodeFetchHeaders.getAll === "function") {
    return maybeNodeFetchHeaders.getAll("set-cookie");
  }
  if (typeof maybeNodeFetchHeaders.raw === "function") {
    const headers = maybeNodeFetchHeaders.raw();
    if (Array.isArray(headers["set-cookie"])) {
      return headers["set-cookie"];
    }
    return [];
  }
  const cookieString = response.headers.get("set-cookie");
  if (cookieString !== null) {
    return (0, import_set_cookie_parser.splitCookiesString)(cookieString);
  }
  return [];
}
function fetchCookie(fetch, jar, ignoreError = true) {
  const actualFetch = fetch;
  const actualJar = jar ?? new tough.CookieJar();
  async function fetchCookieWrapper(input, init) {
    const originalInit = init ?? {};
    init = { ...init, redirect: "manual" };
    const requestUrl = typeof input === "string" ? input : "href" in input ? input.href : input.url;
    const cookie = await actualJar.getCookieString(requestUrl);
    init = addCookiesToRequest(input, init, cookie);
    const response = await actualFetch(input, init);
    const cookies = getCookiesFromResponse(response);
    await Promise.all(cookies.map(async (cookie2) => await actualJar.setCookie(cookie2, response.url, { ignoreError })));
    if ((init.redirectCount ?? 0) > 0) {
      Object.defineProperty(response, "redirected", { value: true });
    }
    if (!isRedirect(response.status)) {
      return response;
    }
    return await handleRedirect(fetchCookieWrapper, originalInit, response);
  }
  fetchCookieWrapper.toughCookie = tough;
  fetchCookieWrapper.cookieJar = actualJar;
  return fetchCookieWrapper;
}
fetchCookie.toughCookie = tough;
