'use strict';

var X64VX57C_cjs = require('./X64VX57C.cjs');
var WFBRUQAF_cjs = require('./WFBRUQAF.cjs');
var S6PEV2YJ_cjs = require('./S6PEV2YJ.cjs');
var REVK4LZT_cjs = require('./REVK4LZT.cjs');
var _4BP4CCPZ_cjs = require('./4BP4CCPZ.cjs');
var _7WWOPL2K_cjs = require('./7WWOPL2K.cjs');
var KHVGLVR5_cjs = require('./KHVGLVR5.cjs');
var esToolkit = require('es-toolkit');
var os = require('os');
var path = require('path');
var process = require('process');
var semver = require('semver');
var zx = require('zx');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

function _interopNamespace(e) {
  if (e && e.__esModule) return e;
  var n = Object.create(null);
  if (e) {
    Object.keys(e).forEach(function (k) {
      if (k !== 'default') {
        var d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: function () { return e[k]; }
        });
      }
    });
  }
  n.default = e;
  return Object.freeze(n);
}

var os__default = /*#__PURE__*/_interopDefault(os);
var path__default = /*#__PURE__*/_interopDefault(path);
var process__default = /*#__PURE__*/_interopDefault(process);
var semver__namespace = /*#__PURE__*/_interopNamespace(semver);

// src/core/tool-executor.ts
KHVGLVR5_cjs.init_cjs_shims();
var getHostUserIds = /* @__PURE__ */ KHVGLVR5_cjs.__name(() => {
  const userInfo = os__default.default.userInfo();
  if (userInfo.uid === -1 || userInfo.gid === -1) {
    return void 0;
  }
  return {
    uid: userInfo.uid,
    gid: userInfo.gid
  };
}, "getHostUserIds");
zx.$.verbose = true;
zx.$.stdio = [
  "inherit",
  "pipe",
  process__default.default.stderr
];
var mergeVolumes = /* @__PURE__ */ KHVGLVR5_cjs.__name((defaultVolumes, userVolumes) => esToolkit.uniqBy([
  ...userVolumes,
  ...defaultVolumes
], (volume) => volume.containerPath), "mergeVolumes");
var resolveVolumePath = /* @__PURE__ */ KHVGLVR5_cjs.__name((volume, workspaceRoot) => volume.type === "host" ? {
  ...volume,
  hostPath: path__default.default.resolve(workspaceRoot, volume.hostPath.replace(/^~/, os__default.default.homedir()))
} : volume, "resolveVolumePath");
var ensureDockerImage = /* @__PURE__ */ KHVGLVR5_cjs.__name(async (imageUri) => {
  let output;
  try {
    output = await zx.$`docker image inspect --format {{.Id}} ${imageUri}`.nothrow().quiet();
    if (!output.exitCode) {
      console.info(`\u2705 Using cached Docker image: ${imageUri}`);
      return;
    }
    console.info("\u{1F4E5} Pulling Docker image from:", imageUri);
    output = await zx.$`docker pull ${imageUri}`.nothrow();
  } catch (error) {
    throw new Error(`Failed to pull Docker image ${imageUri}: ${X64VX57C_cjs.stringifyError(error)}`);
  }
  if (output.exitCode) {
    const stderr = output.stderr ?? "";
    const isAuthError = stderr.includes("authorization token has expired") || stderr.includes("denied") || stderr.includes("pull access denied");
    throw new Error([
      "Docker image not available:",
      `  - Image: ${imageUri} (pull failed)`,
      isAuthError ? "  - ECR auth expired. Run: pnpm localnet login" : "  - Check if the image tag exists in image registry."
    ].join("\n"));
  }
  console.info(`\u2705 Successfully pulled: ${imageUri}`);
}, "ensureDockerImage");
async function executeToolCommand(context, toolName, args, { cwd, volumes: userVolumes, customEntrypoint: entrypoint, env: customEnvVars, script, publish, versions = {}, defaultVolumesEnabled = true }) {
  const tool = _4BP4CCPZ_cjs.findToolByName(context, toolName);
  if (tool.preExecute) {
    await tool.preExecute(context, {
      cwd,
      args,
      volumes: userVolumes,
      env: customEnvVars,
      script,
      publish,
      versions,
      defaultVolumesEnabled
    });
  }
  const workspaceRoot = await REVK4LZT_cjs.findWorkspaceRoot(cwd);
  const defaultVolumes = defaultVolumesEnabled ? tool.defaultVolumes ?? [] : [];
  const volumes = mergeVolumes(defaultVolumes, userVolumes).map((volume) => resolveVolumePath(volume, workspaceRoot)).map(S6PEV2YJ_cjs.qualifyVolumeName);
  if (defaultVolumes.length > 0) {
    console.info(`\u{1F4E6} Using ${defaultVolumes.length} default volume(s) for ${tool.name}`);
    if (userVolumes.length > 0) {
      const overrides = userVolumes.filter((uv) => defaultVolumes.some((dv) => dv.containerPath === uv.containerPath));
      if (overrides.length > 0) {
        console.info(`\u{1F527} User volumes override ${overrides.length} default volume(s)`);
      }
    }
  }
  const resolvedVersion = WFBRUQAF_cjs.resolveTypeVersions(context, versions)[tool.name];
  if (!resolvedVersion) {
    throw new Error(`No version resolved for tool ${tool.name}`);
  }
  console.info(`\u{1F527} ${tool.name} version: ${resolvedVersion}`);
  if (tool.getSecondaryVersion) {
    try {
      const secondaryVersion = await tool.getSecondaryVersion({
        cwd
      });
      if (!semver__namespace.satisfies(secondaryVersion, resolvedVersion)) {
        console.warn(`Warning: Local configuration version (${secondaryVersion}) differs from resolved version (${resolvedVersion})`);
      }
    } catch (error) {
      console.warn("Could not validate secondary version:", X64VX57C_cjs.stringifyError(error));
    }
  }
  const imageUri = await S6PEV2YJ_cjs.getImageUriForTool(context, tool.name, resolvedVersion);
  const relativePath = path__default.default.relative(workspaceRoot, cwd);
  await ensureDockerImage(imageUri);
  if (entrypoint?.trim()) {
    console.info(`\u{1F527} Using custom entrypoint: ${entrypoint}`);
  }
  const defaultEnv = tool.defaultEnv ?? [];
  const hasDockerSocketMount = volumes.some((volume) => volume.type === "host" && volume.containerPath === "/var/run/docker.sock");
  const dockerSocketEnv = hasDockerSocketMount ? [
    {
      name: "HOST_CWD",
      value: cwd
    },
    {
      name: "HOST_WORKSPACE_ROOT",
      value: workspaceRoot
    }
  ] : [];
  const envArgs = esToolkit.uniqBy([
    ...customEnvVars,
    ...dockerSocketEnv,
    ...defaultEnv
  ], ({ name }) => name).flatMap(({ name, value }) => [
    "-e",
    `${name}=${value}`
  ]);
  const hostUserIds = getHostUserIds();
  const userIdEnvArgs = hostUserIds ? [
    "-e",
    `LOCAL_UID=${hostUserIds.uid}`,
    "-e",
    `LOCAL_GID=${hostUserIds.gid}`
  ] : [];
  console.info(`\u{1F464} Running container as UID:GID ${hostUserIds?.uid}:${hostUserIds?.gid}`);
  if (defaultEnv.length > 0) {
    console.info(`\u{1F30D} Using ${defaultEnv.length} default environment variable(s) for ${tool.name}`);
  }
  if (customEnvVars.length > 0) {
    console.info(`\u{1F30D} Using ${customEnvVars.length} custom environment variable(s)`);
  }
  let finalArgs;
  if (script && script.trim() !== "") {
    console.info(`\u{1F4DC} Executing custom script: ${script}`);
    finalArgs = [
      "bash",
      "-c",
      script
    ];
  } else {
    finalArgs = entrypoint === void 0 ? [
      tool.name,
      ...args
    ] : args;
  }
  const dockerArgs = [
    "run",
    ...tool.privileged ? [
      "--privileged"
    ] : [],
    "--rm",
    "--add-host=host.docker.internal:host-gateway",
    ...envArgs,
    ...userIdEnvArgs,
    "-v",
    `${workspaceRoot}:/workspace`,
    "-w",
    `/workspace/${relativePath}`,
    ...(publish ?? []).flatMap((p) => [
      "-p",
      p.trim()
    ]),
    ...volumes.flatMap((volume) => [
      "-v",
      `${volume.type === "host" ? volume.hostPath : volume.name}:${volume.containerPath}`
    ]),
    ...entrypoint ? [
      "--entrypoint",
      entrypoint
    ] : [],
    imageUri,
    ...finalArgs
  ];
  const output = await _7WWOPL2K_cjs.lockMany(volumes.flatMap((volume) => volume.type === "isolate" && volume.locked ? [
    volume.name
  ] : []), async () => {
    const label = `\u23F3 ${finalArgs.join(" ")}`;
    console.time(label);
    const result = await zx.$`docker ${dockerArgs}`.nothrow();
    console.timeEnd(label);
    return result;
  });
  if (output.exitCode) {
    const stdout = output.stdout.trim();
    throw new Error(`Failed to run Docker container (exit code: ${output.exitCode})${stdout ? `
${stdout}` : ""}`);
  }
  return output;
}
KHVGLVR5_cjs.__name(executeToolCommand, "executeToolCommand");

exports.executeToolCommand = executeToolCommand;
//# sourceMappingURL=56KN6KX2.cjs.map
//# sourceMappingURL=56KN6KX2.cjs.map