"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 github_downloads_exports = {};
__export(github_downloads_exports, {
  downloadGitHubRelease: () => downloadGitHubRelease,
  downloadReleaseAsset: () => downloadReleaseAsset
});
module.exports = __toCommonJS(github_downloads_exports);
var import_node_process = __toESM(require("node:process"));
var import_safe = require("../fs/safe");
var import_download = require("../http-request/download");
var import_logger = require("../logger/logger");
var import_error = require("../primordials/error");
var import_string = require("../primordials/string");
var import_spawn = require("../spawn/spawn");
var import_github_asset_url = require("./github-asset-url");
var import_github_listing = require("./github-listing");
var import_fs = require("../node/fs");
var import_path = require("../node/path");
const logger = (0, import_logger.getDefaultLogger)();
async function downloadGitHubRelease(config) {
  const {
    assetName,
    binaryName,
    cwd = import_node_process.default.cwd(),
    downloadDir = "build/downloaded",
    owner,
    platformArch,
    quiet = false,
    removeMacOSQuarantine = true,
    repo,
    tag: explicitTag,
    toolName,
    toolPrefix
  } = config;
  let tag;
  if (explicitTag) {
    tag = explicitTag;
  } else if (toolPrefix) {
    const latestTag = await (0, import_github_listing.getLatestRelease)(toolPrefix, { owner, repo });
    if (!latestTag) {
      throw new import_error.ErrorCtor(`No ${toolPrefix} release found in ${owner}/${repo}`);
    }
    tag = latestTag;
  } else {
    throw new import_error.ErrorCtor("Either toolPrefix or tag must be provided");
  }
  const path = (0, import_path.getNodePath)();
  const resolvedDownloadDir = path.isAbsolute(downloadDir) ? downloadDir : path.join(cwd, downloadDir);
  const binaryDir = resolvedDownloadDir;
  const binaryPath = path.join(binaryDir, binaryName);
  const versionPath = path.join(binaryDir, ".version");
  const fs = (0, import_fs.getNodeFs)();
  if (fs.existsSync(versionPath) && fs.existsSync(binaryPath)) {
    const cachedVersion = (await fs.promises.readFile(versionPath, "utf8")).trim();
    if (cachedVersion === tag && fs.existsSync(binaryPath)) {
      if (!quiet) {
        logger.info(`Using cached ${toolName} (${platformArch}): ${binaryPath}`);
      }
      return binaryPath;
    }
  }
  if (!quiet) {
    logger.info(`Downloading ${toolName} for ${platformArch}...`);
  }
  await downloadReleaseAsset(
    tag,
    assetName,
    binaryPath,
    { owner, repo },
    { quiet }
  );
  const isWindows = (0, import_string.StringPrototypeEndsWith)(binaryName, ".exe");
  if (!isWindows) {
    fs.chmodSync(binaryPath, 493);
    if (removeMacOSQuarantine && import_node_process.default.platform === "darwin" && (0, import_string.StringPrototypeStartsWith)(platformArch, "darwin")) {
      try {
        await (0, import_spawn.spawn)("xattr", ["-d", "com.apple.quarantine", binaryPath], {
          stdio: "ignore"
        });
      } catch {
      }
    }
  }
  await fs.promises.writeFile(versionPath, tag, "utf8");
  if (!quiet) {
    logger.info(`Downloaded ${toolName} to ${binaryPath}`);
  }
  return binaryPath;
}
async function downloadReleaseAsset(tag, assetPattern, outputPath, repoConfig, options = {}) {
  const { owner, repo } = repoConfig;
  const { quiet = false } = options;
  const downloadUrl = await (0, import_github_asset_url.getReleaseAssetUrl)(tag, assetPattern, {
    owner,
    repo
  });
  if (!downloadUrl) {
    const patternDesc = typeof assetPattern === "string" ? assetPattern : "matching pattern";
    throw new import_error.ErrorCtor(`Asset ${patternDesc} not found in release ${tag}`);
  }
  const path = (0, import_path.getNodePath)();
  await (0, import_safe.safeMkdir)(path.dirname(outputPath));
  await (0, import_download.httpDownload)(downloadUrl, outputPath, {
    logger: quiet ? void 0 : logger,
    progressInterval: 10,
    retries: 2,
    retryDelay: 5e3
  });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  downloadGitHubRelease,
  downloadReleaseAsset
});
