"use strict";
/* Socket Lib - Built with rolldown */
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const require_primordials_string = require('../primordials/string.js');
const require_constants_platform = require('../constants/platform.js');
const require_paths_normalize = require('../paths/normalize.js');
const require_node_fs = require('../node/fs.js');
const require_node_path = require('../node/path.js');
const require_bin__internal = require('./_internal.js');
const require_fs_read_json = require('../fs/read-json.js');
const require_bin_which = require('./which.js');

//#region src/bin/resolve.ts
/**
* @file Resolve a binary path to the underlying script file. Wrapper-script
*   unwrapping: a binary like `npm` is rarely an executable — on Windows it's
*   `npm.cmd` / `npm.ps1` / extensionless `npm` shell script. Each wrapper
*   variant has a fixed format generated by either the npm CLI build (npm/npx
*   specific) or by `cmd-shim` for arbitrary package binaries. We pattern-match
*   each format and extract the relative path to the underlying `.js` so
*   callers can spawn Node with that path directly (cheaper than re-launching a
*   shell wrapper). Volta managed installs: Volta layers binaries through
*   `~/.volta/tools/{image,user}/...` with version-pinned subdirs. We detect
*   the `.volta/` segment in the path and walk into the image directory to find
*   the real CLI script. Caching: per-Volta-key cache + a final `realpathSync`
*   to dedupe symlinked installations. Both caches live in `_internal.ts` so
*   `which.ts` can flush them when its own cache eviction fires. Cycles with
*   `which.ts`: `resolveRealBinSync` calls `whichRealSync` to handle relative
*   input paths. ESM tolerates the cycle since both sides expose only functions
*   (no eager top-level evaluation that needs the other module's bindings).
*/
/**
* Resolve a binary path to the real underlying script file. Handles Windows
* .cmd wrappers and Unix shell scripts, resolving them to the actual .js files
* they execute.
*
* @example
*   ;```typescript
*   const realPath = resolveRealBinSync('/usr/local/bin/npm')
*   // e.g. '/usr/local/lib/node_modules/npm/bin/npm-cli.js'
*   ```
*/
/*@__NO_SIDE_EFFECTS__*/
function resolveRealBinSync(binPath) {
	const fs = /* @__PURE__ */ require_node_fs.getNodeFs();
	const path = /* @__PURE__ */ require_node_path.getNodePath();
	if (!path.isAbsolute(binPath)) try {
		const resolved = require_bin_which.whichRealSync(binPath);
		if (resolved) binPath = resolved;
	} catch {}
	binPath = /* @__PURE__ */ require_paths_normalize.normalizePath(binPath);
	if (binPath === ".") return binPath;
	const ext = path.extname(binPath);
	const extLowered = ext.toLowerCase();
	const basename = path.basename(binPath, ext);
	const voltaIndex = basename === "node" ? -1 : /(?<=\/)\.volta\//i.exec(binPath)?.index ?? -1;
	if (voltaIndex !== -1) {
		const voltaPath = binPath.slice(0, voltaIndex);
		const voltaCacheKey = `${voltaPath}:${basename}`;
		const cachedVolta = require_bin__internal.voltaBinCache.get(voltaCacheKey);
		/* c8 ignore start */
		if (cachedVolta) {
			if (fs.existsSync(cachedVolta)) return cachedVolta;
			require_bin__internal.voltaBinCache.delete(voltaCacheKey);
		}
		/* c8 ignore stop */
		const voltaToolsPath = path.join(voltaPath, "tools");
		const voltaImagePath = path.join(voltaToolsPath, "image");
		const voltaUserPath = path.join(voltaToolsPath, "user");
		const voltaPlatform = /* @__PURE__ */ require_fs_read_json.readJsonSync(path.join(voltaUserPath, "platform.json"), { throws: false });
		const voltaNodeVersion = voltaPlatform?.node?.runtime;
		const voltaNpmVersion = voltaPlatform?.node?.npm;
		let voltaBinPath = "";
		/* c8 ignore start */
		if (basename === "npm" || basename === "npx") {
			if (voltaNpmVersion) {
				const relCliPath = `bin/${basename}-cli.js`;
				voltaBinPath = path.join(voltaImagePath, `npm/${voltaNpmVersion}/${relCliPath}`);
				if (voltaNodeVersion && !fs.existsSync(voltaBinPath)) {
					voltaBinPath = path.join(voltaImagePath, `node/${voltaNodeVersion}/lib/node_modules/npm/${relCliPath}`);
					if (!fs.existsSync(voltaBinPath)) voltaBinPath = "";
				}
			}
		} else {
			const voltaUserBinPath = path.join(voltaUserPath, "bin");
			const binPackage = (/* @__PURE__ */ require_fs_read_json.readJsonSync(path.join(voltaUserBinPath, `${basename}.json`), { throws: false }))?.package;
			if (binPackage) {
				voltaBinPath = path.join(voltaImagePath, `packages/${binPackage}/bin/${basename}`);
				if (!fs.existsSync(voltaBinPath)) {
					voltaBinPath = `${voltaBinPath}.cmd`;
					if (!fs.existsSync(voltaBinPath)) voltaBinPath = "";
				}
			}
		}
		/* c8 ignore stop */
		if (voltaBinPath) {
			let resolvedVoltaPath = voltaBinPath;
			try {
				resolvedVoltaPath = /* @__PURE__ */ require_paths_normalize.normalizePath(fs.realpathSync.native(voltaBinPath));
			} catch {}
			require_bin__internal.voltaBinCache.set(voltaCacheKey, resolvedVoltaPath);
			return resolvedVoltaPath;
		}
	}
	/* c8 ignore start - Windows-only wrapper-script resolution; tested
	on Windows runners. The whole `if (WIN32)` block parses npm/npx/ // socket-hook: allow npx
	pnpm/yarn .cmd/.bat/.ps1 shims to extract the underlying CLI JS
	path. Unreachable on macOS/Linux. */
	if (require_constants_platform.WIN32) {
		const hasKnownExt = extLowered === "" || extLowered === ".cmd" || extLowered === ".exe" || extLowered === ".ps1";
		const isNpmOrNpx = basename === "npm" || basename === "npx";
		const isPnpmOrYarn = basename === "pnpm" || basename === "yarn";
		if (hasKnownExt && isNpmOrNpx) {
			const quickPath = path.join(path.dirname(binPath), `node_modules/npm/bin/${basename}-cli.js`);
			if (fs.existsSync(quickPath)) {
				try {
					return fs.realpathSync.native(quickPath);
				} catch {}
				return quickPath;
			}
		}
		let relPath = "";
		if (hasKnownExt && extLowered !== ".exe" && fs.existsSync(binPath)) {
			const source = fs.readFileSync(binPath, "utf8");
			if (isNpmOrNpx) {
				if (extLowered === ".cmd") relPath = basename === "npm" ? /(?<="NPM_CLI_JS=%~dp0\\).*(?=")/.exec(source)?.[0] || "" : /(?<="NPX_CLI_JS=%~dp0\\).*(?=")/.exec(source)?.[0] || "";
				else if (extLowered === "") relPath = basename === "npm" ? /(?<=NPM_CLI_JS="\$CLI_BASEDIR\/).*(?=")/.exec(source)?.[0] || "" : /(?<=NPX_CLI_JS="\$CLI_BASEDIR\/).*(?=")/.exec(source)?.[0] || "";
				else if (extLowered === ".ps1") relPath = basename === "npm" ? /(?<=\$NPM_CLI_JS="\$PSScriptRoot\/).*(?=")/.exec(source)?.[0] || "" : /(?<=\$NPX_CLI_JS="\$PSScriptRoot\/).*(?=")/.exec(source)?.[0] || "";
			} else if (isPnpmOrYarn) {
				if (extLowered === ".cmd") {
					relPath = /(?<=node\s+")%~dp0\\([^"]+)(?="\s+%\*)/.exec(source)?.[1] || "";
					if (!relPath) relPath = /(?<="%~dp0\\[^"]*node[^"]*"\s+")%~dp0\\([^"]+)(?="\s+%\*)/.exec(source)?.[1] || "";
					if (!relPath) relPath = /(?<="%dp0%\\).*(?=" %\*\r\n)/.exec(source)?.[0] || "";
				} else if (extLowered === "") {
					relPath = /(?<="\$basedir\/)\.tools\/pnpm\/[^"]+(?="\s+"\$@")/.exec(source)?.[0] || "";
					if (!relPath) relPath = /(?<=exec\s+node\s+"\$basedir\/)\.tools\/pnpm\/[^"]+(?="\s+"\$@")/.exec(source)?.[0] || "";
					if (!relPath) relPath = /(?<="\$basedir\/).*(?=" "\$@"\n)/.exec(source)?.[0] || "";
				} else if (extLowered === ".ps1") relPath = /(?<="\$basedir\/).*(?=" $args\n)/.exec(source)?.[0] || "";
			} else if (extLowered === ".cmd") relPath = /(?<="%dp0%\\).*(?=" %\*\r\n)/.exec(source)?.[0] || "";
			else if (extLowered === "") relPath = /(?<="$basedir\/).*(?=" "\$@"\n)/.exec(source)?.[0] || "";
			else if (extLowered === ".ps1") relPath = /(?<="\$basedir\/).*(?=" $args\n)/.exec(source)?.[0] || "";
			if (relPath) binPath = /* @__PURE__ */ require_paths_normalize.normalizePath(path.resolve(path.dirname(binPath), relPath));
		}
	} else {
		let hasNoExt = extLowered === "";
		const isPnpmOrYarn = basename === "pnpm" || basename === "yarn";
		const isNpmOrNpx = basename === "npm" || basename === "npx";
		if (isPnpmOrYarn && binPath.includes("/.bin/pnpm/bin/")) {
			const binIndex = binPath.indexOf("/.bin/pnpm");
			if (binIndex !== -1) {
				const baseBinPath = binPath.slice(0, binIndex + 10);
				try {
					if (fs.statSync(baseBinPath).isFile()) {
						binPath = /* @__PURE__ */ require_paths_normalize.normalizePath(baseBinPath);
						hasNoExt = !path.extname(binPath);
					}
				} catch {}
			}
		}
		if (hasNoExt && (isPnpmOrYarn || isNpmOrNpx) && fs.existsSync(binPath)) {
			const source = fs.readFileSync(binPath, "utf8");
			let relPath = "";
			if (isPnpmOrYarn) {
				relPath = /(?<="\$basedir\/)\.tools\/[^"]+(?="\s+"\$@")/.exec(source)?.[0] || "";
				if (!relPath) relPath = /(?<="\$basedir\/)[^"]+(?="\s+"\$@")/.exec(source)?.[0] || "";
				if (!relPath) {
					const match = /exec\s+node\s+"?\$basedir\/([^"]+)"?\s+"\$@"/.exec(source);
					if (match) relPath = match[1] || "";
				}
				if (relPath && basename === "pnpm" && require_primordials_string.StringPrototypeStartsWith(relPath, "pnpm/")) relPath = `../${relPath}`;
			} else if (isNpmOrNpx) relPath = basename === "npm" ? /(?<=NPM_CLI_JS="\$CLI_BASEDIR\/).*(?=")/.exec(source)?.[0] || "" : /(?<=NPX_CLI_JS="\$CLI_BASEDIR\/).*(?=")/.exec(source)?.[0] || "";
			if (relPath) binPath = /* @__PURE__ */ require_paths_normalize.normalizePath(path.resolve(path.dirname(binPath), relPath));
		}
	}
	/* c8 ignore stop */
	try {
		return /* @__PURE__ */ require_paths_normalize.normalizePath(fs.realpathSync.native(binPath));
	} catch {}
	return /* @__PURE__ */ require_paths_normalize.normalizePath(binPath);
}

//#endregion
exports.resolveRealBinSync = resolveRealBinSync;