"use strict";
/* Socket Lib - Built with rolldown */
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const require_primordials_error = require('../../primordials/error.js');
const require_primordials_object = require('../../primordials/object.js');
const require_primordials_reflect = require('../../primordials/reflect.js');
const require_objects_predicates = require('../../objects/predicates.js');
const require_process_spawn__internal = require('./_internal.js');
let src_external_pony_cause = require("../../external/pony-cause");

//#region src/process/spawn/errors.ts
/**
* @file Spawn error classification and enhancement. `isSpawnError` is a
*   type-guard for shaping unknown errors that crossed an `await spawn(...)`.
*   It checks for the `code` / `errno` / `syscall` properties that Node's
*   child_process tags onto `ENOENT` / `EACCES` / process-exit failures.
*   `enhanceSpawnError` rewrites the upstream `@npmcli/promise-spawn` "command
*   failed" placeholder message into something the operator can actually act
*   on: command + args (truncated at 100 chars), exit code or signal, and the
*   first stderr line (truncated at 200 chars). The stack is computed lazily on
*   first access via a per-error WeakMap so non-error paths don't pay the
*   `stackWithCauses` cost.
*/
/**
* Enhances spawn error with better context. Converts generic "command failed"
* to detailed error with command, exit code, and stderr.
*
* @example
*   ;```typescript
*   try {
*     await spawn('git', ['status'])
*   } catch (e) {
*     throw enhanceSpawnError(e)
*   }
*   ```
*/
/*@__NO_SIDE_EFFECTS__*/
function enhanceSpawnError(error) {
	if (error === null || typeof error !== "object") return error;
	if (!/* @__PURE__ */ isSpawnError(error)) return error;
	const err = error;
	const { args, cmd, code, signal, stderr } = err;
	const stderrText = typeof stderr === "string" ? stderr : stderr?.toString() ?? "";
	let enhancedMessage = `Command failed: ${cmd}`;
	if (args && args.length > 0) {
		const argsStr = args.join(" ");
		if (argsStr.length < 100) enhancedMessage += ` ${argsStr}`;
		else enhancedMessage += ` ${argsStr.slice(0, 97)}...`;
	}
	/* c8 ignore start */
	if (signal) enhancedMessage += ` (terminated by ${signal})`;
	else if (code !== void 0) enhancedMessage += ` (exit code ${code})`;
	const trimmedStderr = stderrText.trim();
	if (trimmedStderr) {
		const firstLine = trimmedStderr.split("\n")[0] ?? "";
		if (firstLine.length < 200) enhancedMessage += `\n${firstLine}`;
		else enhancedMessage += `\n${firstLine.slice(0, 197)}...`;
	}
	if (err.message === "command failed") {
		require_primordials_object.ObjectDefineProperty(err, "message", {
			__proto__: null,
			value: enhancedMessage,
			writable: true,
			enumerable: false,
			configurable: true
		});
		return err;
	}
	const enhancedError = new require_primordials_error.ErrorCtor(enhancedMessage, { cause: err });
	const descriptors = require_primordials_object.ObjectGetOwnPropertyDescriptors(err);
	require_primordials_reflect.ReflectDeleteProperty(descriptors, "message");
	require_primordials_reflect.ReflectDeleteProperty(descriptors, "stack");
	require_primordials_object.ObjectDefineProperties(enhancedError, descriptors);
	require_primordials_object.ObjectDefineProperty(enhancedError, "stack", {
		__proto__: null,
		configurable: true,
		enumerable: false,
		get() {
			let stack = require_process_spawn__internal.stackCache.get(enhancedError);
			/* c8 ignore next - Lazy-init second-call branch on the per-error cache. */
			if (stack === void 0) {
				try {
					stack = (0, src_external_pony_cause.stackWithCauses)(err);
				} catch {
					stack = err.stack ?? new require_primordials_error.ErrorCtor().stack ?? "";
				}
				/* c8 ignore stop */
				require_process_spawn__internal.stackCache.set(enhancedError, stack);
			}
			return stack;
		}
	});
	return enhancedError;
}
/**
* Check if a value is a spawn error with expected error properties. Tests for
* common error properties from child process failures.
*
* @example
*   try {
*     await spawn('nonexistent-command')
*   } catch (e) {
*     if (isSpawnError(e)) {
*       console.error(`Spawn failed: ${e.code}`)
*     }
*   }
*
* @param {unknown} value - Value to check.
*
* @returns {boolean} `true` if the value has spawn error properties
*/
/*@__NO_SIDE_EFFECTS__*/
function isSpawnError(value) {
	if (value === null || typeof value !== "object") return false;
	const err = value;
	return /* @__PURE__ */ require_objects_predicates.hasOwn(err, "code") && typeof err["code"] !== "undefined" || /* @__PURE__ */ require_objects_predicates.hasOwn(err, "errno") && typeof err["errno"] !== "undefined" || /* @__PURE__ */ require_objects_predicates.hasOwn(err, "syscall") && typeof err["syscall"] === "string";
}

//#endregion
exports.enhanceSpawnError = enhanceSpawnError;
exports.isSpawnError = isSpawnError;