"use strict";
/* Socket Lib - Built with esbuild */
"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 ghsa_exports = {};
__export(ghsa_exports, {
  cacheFetchGhsa: () => cacheFetchGhsa,
  fetchGhsaDetails: () => fetchGhsaDetails,
  fetchGhsaDetailsViaGraphQL: () => fetchGhsaDetailsViaGraphQL
});
module.exports = __toCommonJS(ghsa_exports);
var import_node_process = __toESM(require("node:process"));
var import_request = require("../http-request/request");
var import_error = require("../primordials/error");
var import_json = require("../primordials/json");
var import_fetch = require("./fetch");
var import_refs = require("./refs");
var import_token = require("./token");
var import_constants = require("./constants");
var import_errors = require("./errors");
async function cacheFetchGhsa(ghsaId, options) {
  const cache = (0, import_refs.getGithubCache)();
  const key = `ghsa:${ghsaId}`;
  if (import_node_process.default.env["DISABLE_GITHUB_CACHE"]) {
    return await fetchGhsaDetails(ghsaId, options);
  }
  return await cache.getOrFetch(key, async () => {
    return await fetchGhsaDetails(ghsaId, options);
  });
}
async function fetchGhsaDetails(ghsaId, options) {
  const url = `https://api.github.com/advisories/${ghsaId}`;
  try {
    const data = await (0, import_fetch.fetchGitHub)(url, options);
    return {
      ghsaId: data.ghsa_id,
      summary: data.summary,
      details: data.details,
      severity: data.severity,
      aliases: data.aliases || [],
      publishedAt: data.published_at,
      updatedAt: data.updated_at,
      withdrawnAt: data.withdrawn_at,
      references: data.references || [],
      vulnerabilities: data.vulnerabilities || [],
      cvss: data.cvss,
      cwes: data.cwes || []
    };
  } catch (e) {
    if (e instanceof import_errors.GitHubEmptyBodyError) {
      try {
        return await fetchGhsaDetailsViaGraphQL(ghsaId, options);
      } catch (cause) {
        throw new import_error.ErrorCtor(
          `Failed to fetch advisory ${ghsaId}: both REST and GraphQL backends degraded`,
          { cause }
        );
      }
    }
    throw e;
  }
}
async function fetchGhsaDetailsViaGraphQL(ghsaId, options) {
  const opts = { __proto__: null, ...options };
  const token = opts.token || (0, import_token.getGitHubToken)();
  const headers = {
    Accept: "application/vnd.github.v3+json",
    "Content-Type": "application/json",
    "User-Agent": "socket-registry-github-client",
    ...opts.headers
  };
  if (token) {
    headers["Authorization"] = `Bearer ${token}`;
  }
  const query = `query($ghsaId: String!) {
    securityAdvisory(ghsaId: $ghsaId) {
      ghsaId
      summary
      description
      severity
      publishedAt
      updatedAt
      withdrawnAt
      cvss { score vectorString }
      cwes(first: 50) { nodes { cweId name description } }
      references { url }
      vulnerabilities(first: 100) {
        nodes {
          package { ecosystem name }
          vulnerableVersionRange
          firstPatchedVersion { identifier }
        }
      }
      identifiers { type value }
    }
  }`;
  const response = await (0, import_request.httpRequest)(import_constants.GITHUB_GRAPHQL_URL, {
    body: (0, import_json.JSONStringify)({ query, variables: { ghsaId } }),
    headers,
    method: "POST"
  });
  if (!response.ok) {
    throw new import_error.ErrorCtor(
      `GitHub GraphQL API error ${response.status}: ${response.statusText}`
    );
  }
  if (response.body.byteLength === 0) {
    throw new import_errors.GitHubEmptyBodyError(import_constants.GITHUB_GRAPHQL_URL);
  }
  let parsed;
  try {
    parsed = (0, import_json.JSONParse)(response.body.toString("utf8"));
  } catch (cause) {
    throw new import_error.ErrorCtor(
      `Failed to parse GitHub GraphQL response for advisory ${ghsaId}`,
      { cause }
    );
  }
  if (parsed.errors?.length) {
    throw new import_error.ErrorCtor(
      `GraphQL securityAdvisory(${ghsaId}) returned errors: ${parsed.errors.map((e) => e.message).join("; ")}`
    );
  }
  const adv = parsed.data?.securityAdvisory;
  if (!adv) {
    throw new import_error.ErrorCtor(`GHSA ${ghsaId} not found`);
  }
  return {
    ghsaId: adv.ghsaId,
    summary: adv.summary,
    details: adv.description,
    severity: adv.severity.toLowerCase(),
    aliases: adv.identifiers?.filter((i) => i.type !== "GHSA").map((i) => i.value) ?? [],
    publishedAt: adv.publishedAt,
    updatedAt: adv.updatedAt,
    withdrawnAt: adv.withdrawnAt ?? "",
    references: adv.references ?? [],
    vulnerabilities: adv.vulnerabilities?.nodes ?? [],
    // GhsaDetails.cvss is typed `... | null` to match the REST
    // `/advisories/:id` shape. Preserving `null` here is the external-
    // API-contract exception called out in the lint rule docs.
    // oxlint-disable-next-line socket/prefer-undefined-over-null
    cvss: adv.cvss ?? null,
    cwes: adv.cwes?.nodes ?? []
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  cacheFetchGhsa,
  fetchGhsaDetails,
  fetchGhsaDetailsViaGraphQL
});
