"use strict";
/* Socket Lib - Built with rolldown */
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const require_primordials_error = require('../primordials/error.js');
const require_constants_platform = require('../constants/platform.js');
const require_node_fs = require('../node/fs.js');
const require_releases_github_asset_url = require('./github-asset-url.js');
const require_releases_github_listing = require('./github-listing.js');
const require_releases_github_downloads = require('./github-downloads.js');

//#region src/releases/socket-btm.ts
/**
* @file Socket-btm release download utilities.
*/
/**
* Socket-btm GitHub repository configuration.
*/
const SOCKET_BTM_REPO = {
	owner: "SocketDev",
	repo: "socket-btm"
};
/**
* Map Node.js platform to socket-btm asset platform naming. Identity mapping:
* asset names use `process.platform` verbatim (`darwin`, `linux`, `win32`) to
* align with pnpm's pack-app, the `--os` / `supportedArchitectures.os` config
* keys, and the `@pnpm/exe.<os>-<arch>` package convention.
*/
const PLATFORM_MAP = {
	__proto__: null,
	darwin: "darwin",
	linux: "linux",
	win32: "win32"
};
/**
* Map Node.js arch to socket-btm asset arch naming.
*/
const ARCH_MAP = {
	__proto__: null,
	arm64: "arm64",
	x64: "x64"
};
/**
* Detect the libc variant (musl or glibc) on Linux systems. Returns undefined
* for non-Linux platforms.
*
* @example
*   ;```typescript
*   const libc = detectLibc()
*   console.log(libc) // 'glibc', 'musl', or undefined
*   ```
*
* @returns 'musl', 'glibc', or undefined (for non-Linux)
*/
function detectLibc() {
	/* c8 ignore next 3 */
	if (require_constants_platform.getPlatform() !== "linux") return;
	/* c8 ignore start - Linux-only musl/glibc detection; tested on
	Linux runners. macOS/Windows runners take the early-return above. */
	try {
		const fs = /* @__PURE__ */ require_node_fs.getNodeFs();
		for (const path of [
			"/lib/ld-musl-x86_64.so.1",
			"/lib/ld-musl-aarch64.so.1",
			"/usr/lib/ld-musl-x86_64.so.1",
			"/usr/lib/ld-musl-aarch64.so.1"
		]) if (fs.existsSync(path)) return "musl";
		return "glibc";
	} catch {
		return "glibc";
	}
	/* c8 ignore stop */
}
/**
* Download a release from socket-btm.
*
* @example
*   ;```typescript
*   const binPath = await downloadSocketBtmRelease('lief', {
*     downloadDir: '/tmp/build/downloaded',
*   })
*   ```
*
* @param tool - Tool/package name for release matching (e.g., 'lief', 'curl')
* @param options - Download configuration.
*
* @returns Path to the downloaded file
*/
async function downloadSocketBtmRelease(tool, options) {
	const { cwd, downloadDir, quiet = false, tag } = {
		__proto__: null,
		...options ?? {}
	};
	const toolPrefix = `${tool}-`;
	let downloadConfig;
	if (options && "asset" in options) {
		const { asset, output, removeMacOSQuarantine = false } = {
			__proto__: null,
			...options
		};
		let resolvedAsset;
		let resolvedTag = tag;
		if (typeof asset === "string" && !asset.includes("*")) resolvedAsset = asset;
		else {
			if (tag) throw new require_primordials_error.ErrorCtor("Cannot use asset pattern with explicit tag. Either provide exact asset name or omit tag.");
			resolvedTag = await require_releases_github_listing.getLatestRelease(toolPrefix, SOCKET_BTM_REPO, { assetPattern: asset }) ?? void 0;
			if (!resolvedTag) throw new require_primordials_error.ErrorCtor(`No ${tool} release with matching asset pattern found`);
			const assetUrl = await require_releases_github_asset_url.getReleaseAssetUrl(resolvedTag, asset, SOCKET_BTM_REPO);
			/* c8 ignore start */
			if (!assetUrl) throw new require_primordials_error.ErrorCtor(`No matching asset found in release ${resolvedTag}`);
			resolvedAsset = assetUrl.split("/").pop() || asset.toString();
		}
		/* c8 ignore next */
		const outputName = output || resolvedAsset;
		const platformArch = "assets";
		downloadConfig = {
			owner: SOCKET_BTM_REPO.owner,
			repo: SOCKET_BTM_REPO.repo,
			...cwd !== void 0 && { cwd },
			...downloadDir !== void 0 && { downloadDir },
			toolName: tool,
			platformArch,
			binaryName: outputName,
			assetName: resolvedAsset,
			toolPrefix,
			...resolvedTag !== void 0 && { tag: resolvedTag },
			quiet,
			removeMacOSQuarantine
		};
	} else {
		const { bin, libc = detectLibc(), removeMacOSQuarantine = true, targetArch = require_constants_platform.getArch(), targetPlatform = require_constants_platform.getPlatform() } = {
			__proto__: null,
			...options
		};
		const baseName = bin || tool;
		const assetName = getBinaryAssetName(baseName, targetPlatform, targetArch, libc);
		const platformArch = getPlatformArch(targetPlatform, targetArch, libc);
		const binaryName = getBinaryName(baseName, targetPlatform);
		downloadConfig = {
			owner: SOCKET_BTM_REPO.owner,
			repo: SOCKET_BTM_REPO.repo,
			...cwd !== void 0 && { cwd },
			...downloadDir !== void 0 && { downloadDir },
			toolName: tool,
			platformArch,
			binaryName,
			assetName,
			toolPrefix,
			...tag !== void 0 && { tag },
			quiet,
			removeMacOSQuarantine
		};
	}
	return await require_releases_github_downloads.downloadGitHubRelease(downloadConfig);
}
/**
* Get asset name for a socket-btm binary.
*
* @example
*   ;```typescript
*   getBinaryAssetName('lief', 'linux', 'x64', 'musl')
*   // 'lief-linux-x64-musl'
*   ```
*
* @param binaryBaseName - Binary basename (e.g., 'binject', 'node')
* @param platform - Target platform.
* @param arch - Target architecture.
* @param libc - Linux libc variant (optional)
*
* @returns Asset name (e.g., 'binject-darwin-arm64', 'node-linux-x64-musl')
*/
function getBinaryAssetName(binaryBaseName, platform, arch, libc) {
	const mappedArch = ARCH_MAP[arch];
	if (!mappedArch) throw new require_primordials_error.ErrorCtor(`Unsupported architecture: ${arch}`);
	const muslSuffix = platform === "linux" && libc === "musl" ? "-musl" : "";
	const ext = platform === "win32" ? ".exe" : "";
	if (platform === "darwin") return `${binaryBaseName}-darwin-${mappedArch}${ext}`;
	if (platform === "linux") return `${binaryBaseName}-linux-${mappedArch}${muslSuffix}${ext}`;
	if (platform === "win32") return `${binaryBaseName}-win32-${mappedArch}${ext}`;
	throw new require_primordials_error.ErrorCtor(`Unsupported platform: ${platform}`);
}
/**
* Get binary filename for output.
*
* @example
*   ;```typescript
*   getBinaryName('node', 'win32') // 'node.exe'
*   getBinaryName('node', 'linux') // 'node'
*   ```
*
* @param binaryBaseName - Binary basename (e.g., 'node', 'binject')
* @param platform - Target platform.
*
* @returns Binary filename (e.g., 'node', 'node.exe')
*/
function getBinaryName(binaryBaseName, platform) {
	return platform === "win32" ? `${binaryBaseName}.exe` : binaryBaseName;
}
/**
* Lazily load the fs module to avoid Webpack errors. Uses non-'node:' prefixed
* require to prevent Webpack bundling issues.
*
* @private
*/
/**
* Get platform-arch identifier for directory structure and asset names.
*
* # Format: `<os>-<arch>[-<libc>]`
*
* The OS segment is `process.platform` verbatim: `darwin` / `linux` / `win32`.
* The arch segment is `process.arch` verbatim: `x64` / `arm64`. The optional
* libc suffix is `-musl` (Linux only; the glibc default is unsuffixed to match
* Node.js's own linuxstatic convention).
*
* # Why these specific conventions
*
* ## Why `win32`, not `win`
*
* `win32` is what `process.platform` returns on every Windows host. Every npm
* package whose install-time platform filter uses the standard `os` / `cpu` /
* `libc` manifest fields must match `process.platform` strings exactly (npm
* compares them verbatim — there's no shorthand layer). Using `win` internally
* here would have forced a translation every time we constructed an install
* filter or a target triple, and reviewers would have to remember "we
* abbreviate on disk but not in package filters." Since the two now match,
* there's no translation step to get wrong.
*
* Pnpm's pack-app (v11+) accepts `<os>-<arch>[-<libc>]` target strings and its
* shards are `@pnpm/exe.<os>-<arch>` (with `win32`, not `win` — see
* pnpm#11314). Our naming matches so asset names we emit can flow directly into
* pack-app's `--target` arg, `pnpm.app.targets` config, and
* sibling-package-name construction without a translation map.
*
* ## Why `-musl` is the suffix (and glibc is unsuffixed)
*
* Node.js's own linuxstatic tarballs historically used the unqualified `linux`
* for glibc and a separate download channel for musl. The pnpm ecosystem
* codified that as `linux-<arch>` (glibc, default) and `linux-<arch>-musl` (the
* libc outlier), matching the asymmetric reality of Linux distros — glibc is
* the majority case, musl is Alpine-and-similar. Adding `-glibc` for the
* default would be redundant noise in the name.
*
* ## Why libc is only appended for Linux
*
* MacOS and Windows have exactly one system libc each (Apple libSystem,
* Microsoft UCRT). A hypothetical `darwin-arm64-libsystem` conveys no
* information. Node.js, npm, and pnpm all treat libc as a Linux-only axis; we
* follow the same convention so callers don't have to special- case
* `'darwin-arm64'.startsWith('darwin-arm64')` style matches.
*
* ## Why this function exists at all (vs. inlining)
*
* Two upstream APIs that socket-btm consumers end up calling — the npm manifest
* filter (`os`/`cpu`/`libc`) and pnpm's pack-app `--target` — both need the
* exact same triple format. Centralizing the construction here means a future
* schema change (e.g. Node introducing `riscv64`) gets one edit, and the error
* message for an unsupported platform is uniform across downloaders, pack-app
* invocations, and the `@socketbin/*` resolver logic.
*
* @example
*   ;```typescript
*   getPlatformArch('linux', 'x64', 'musl') // 'linux-x64-musl'
*   getPlatformArch('darwin', 'arm64') // 'darwin-arm64'
*   getPlatformArch('win32', 'x64') // 'win32-x64'
*   getPlatformArch('darwin', 'x64', 'musl') // 'darwin-x64' — libc ignored
*   ```
*
* @param platform - Target platform.
* @param arch - Target architecture.
* @param libc - Linux libc variant (optional; non-linux platforms ignore)
*
* @returns Platform-arch identifier (e.g., 'darwin-arm64', 'linux-x64-musl',
*   'win32-x64')
*/
function getPlatformArch(platform, arch, libc) {
	/* c8 ignore start */
	const mappedPlatform = PLATFORM_MAP[platform];
	if (!mappedPlatform) throw new require_primordials_error.ErrorCtor(`Unsupported platform: ${platform}`);
	const mappedArch = ARCH_MAP[arch];
	if (!mappedArch) throw new require_primordials_error.ErrorCtor(`Unsupported architecture: ${arch}`);
	return `${mappedPlatform}-${mappedArch}${platform === "linux" && libc === "musl" ? "-musl" : ""}`;
	/* c8 ignore stop */
}

//#endregion
exports.SOCKET_BTM_REPO = SOCKET_BTM_REPO;
exports.detectLibc = detectLibc;
exports.downloadSocketBtmRelease = downloadSocketBtmRelease;
exports.getBinaryAssetName = getBinaryAssetName;
exports.getBinaryName = getBinaryName;
exports.getPlatformArch = getPlatformArch;