"use strict";
/* Socket Lib - Built with rolldown */
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const require_runtime = require('../_virtual/_rolldown/runtime.js');
const require_primordials_error = require('../primordials/error.js');
const require_primordials_string = require('../primordials/string.js');
const require_node_fs = require('../node/fs.js');
const require_node_path = require('../node/path.js');
const require_logger_default = require('../logger/default.js');
const require_process_spawn_child = require('../process/spawn/child.js');
const require_fs_safe = require('../fs/safe.js');
const require_http_request_download = require('../http-request/download.js');
const require_releases_github_asset_url = require('./github-asset-url.js');
const require_releases_github_listing = require('./github-listing.js');
let node_process = require("node:process");
node_process = require_runtime.__toESM(node_process);

//#region src/releases/github-downloads.ts
/**
* @file GitHub release asset downloads.
*/
const logger = require_logger_default.getDefaultLogger();
/**
* Download a binary from any GitHub repository with version caching.
*
* @example
*   ;```typescript
*   const binaryPath = await downloadGitHubRelease({
*     owner: 'SocketDev',
*     repo: 'socket-btm',
*     toolName: 'lief',
*     toolPrefix: 'lief-',
*     assetName: 'lief-linux-x64',
*     binaryName: 'lief',
*     platformArch: 'linux-x64',
*   })
*   ```
*
* @param config - Download configuration.
*
* @returns Path to the downloaded binary
*/
async function downloadGitHubRelease(config) {
	const { assetName, binaryName, cwd = 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 require_releases_github_listing.getLatestRelease(toolPrefix, {
			owner,
			repo
		});
		if (!latestTag) throw new require_primordials_error.ErrorCtor(`No ${toolPrefix} release found in ${owner}/${repo}`);
		tag = latestTag;
	} else throw new require_primordials_error.ErrorCtor("Either toolPrefix or tag must be provided");
	const path = /* @__PURE__ */ require_node_path.getNodePath();
	const binaryDir = path.isAbsolute(downloadDir) ? downloadDir : path.join(cwd, downloadDir);
	const binaryPath = path.join(binaryDir, binaryName);
	const versionPath = path.join(binaryDir, ".version");
	const fs = /* @__PURE__ */ require_node_fs.getNodeFs();
	if (fs.existsSync(versionPath) && fs.existsSync(binaryPath)) {
		if ((await fs.promises.readFile(versionPath, "utf8")).trim() === 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 });
	if (!require_primordials_string.StringPrototypeEndsWith(binaryName, ".exe")) {
		fs.chmodSync(binaryPath, 493);
		if (removeMacOSQuarantine && node_process.default.platform === "darwin" && require_primordials_string.StringPrototypeStartsWith(platformArch, "darwin")) try {
			await require_process_spawn_child.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;
}
/**
* Download a specific release asset. Supports pattern matching for dynamic
* asset discovery.
*
* @example
*   ;```typescript
*   await downloadReleaseAsset('v1.0.0', 'tool-linux-x64', '/tmp/tool', {
*     owner: 'SocketDev',
*     repo: 'socket-btm',
*   })
*   ```
*
* @param tag - Release tag name.
* @param assetPattern - Asset name or pattern (glob string, prefix/suffix
*   object, or RegExp)
* @param outputPath - Path to write the downloaded file.
* @param repoConfig - Repository configuration (owner/repo)
* @param options - Additional options.
*/
async function downloadReleaseAsset(tag, assetPattern, outputPath, repoConfig, options = {}) {
	const { owner, repo } = repoConfig;
	const { quiet = false } = options;
	const downloadUrl = await require_releases_github_asset_url.getReleaseAssetUrl(tag, assetPattern, {
		owner,
		repo
	});
	if (!downloadUrl) throw new require_primordials_error.ErrorCtor(`Asset ${typeof assetPattern === "string" ? assetPattern : "matching pattern"} not found in release ${tag}`);
	await require_fs_safe.safeMkdir((/* @__PURE__ */ require_node_path.getNodePath()).dirname(outputPath));
	await require_http_request_download.httpDownload(downloadUrl, outputPath, {
		logger: quiet ? void 0 : logger,
		progressInterval: 10,
		retries: 2,
		retryDelay: 5e3
	});
}

//#endregion
exports.downloadGitHubRelease = downloadGitHubRelease;
exports.downloadReleaseAsset = downloadReleaseAsset;