var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
  if (typeof require !== "undefined") return require.apply(this, arguments);
  throw Error('Dynamic require of "' + x + '" is not supported');
});

// src/cli.ts
import { spawn } from "node:child_process";

// ../tool-debug/dist/index.mjs
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __require2 = /* @__PURE__ */ ((x) => typeof __require !== "undefined" ? __require : typeof Proxy !== "undefined" ? new Proxy(x, {
  get: (a, b) => (typeof __require !== "undefined" ? __require : a)[b]
}) : x)(function(x) {
  if (typeof __require !== "undefined") return __require.apply(this, arguments);
  throw Error('Dynamic require of "' + x + '" is not supported');
});
var __commonJS = (cb, mod) => function __require22() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var require_ms = __commonJS({
  "../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js"(exports, module) {
    var s = 1e3;
    var m = s * 60;
    var h = m * 60;
    var d = h * 24;
    var w = d * 7;
    var y = d * 365.25;
    module.exports = function(val, options) {
      options = options || {};
      var type = typeof val;
      if (type === "string" && val.length > 0) {
        return parse(val);
      } else if (type === "number" && isFinite(val)) {
        return options.long ? fmtLong(val) : fmtShort(val);
      }
      throw new Error(
        "val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
      );
    };
    function parse(str) {
      str = String(str);
      if (str.length > 100) {
        return;
      }
      var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
        str
      );
      if (!match) {
        return;
      }
      var n = parseFloat(match[1]);
      var type = (match[2] || "ms").toLowerCase();
      switch (type) {
        case "years":
        case "year":
        case "yrs":
        case "yr":
        case "y":
          return n * y;
        case "weeks":
        case "week":
        case "w":
          return n * w;
        case "days":
        case "day":
        case "d":
          return n * d;
        case "hours":
        case "hour":
        case "hrs":
        case "hr":
        case "h":
          return n * h;
        case "minutes":
        case "minute":
        case "mins":
        case "min":
        case "m":
          return n * m;
        case "seconds":
        case "second":
        case "secs":
        case "sec":
        case "s":
          return n * s;
        case "milliseconds":
        case "millisecond":
        case "msecs":
        case "msec":
        case "ms":
          return n;
        default:
          return void 0;
      }
    }
    function fmtShort(ms) {
      var msAbs = Math.abs(ms);
      if (msAbs >= d) {
        return Math.round(ms / d) + "d";
      }
      if (msAbs >= h) {
        return Math.round(ms / h) + "h";
      }
      if (msAbs >= m) {
        return Math.round(ms / m) + "m";
      }
      if (msAbs >= s) {
        return Math.round(ms / s) + "s";
      }
      return ms + "ms";
    }
    function fmtLong(ms) {
      var msAbs = Math.abs(ms);
      if (msAbs >= d) {
        return plural(ms, msAbs, d, "day");
      }
      if (msAbs >= h) {
        return plural(ms, msAbs, h, "hour");
      }
      if (msAbs >= m) {
        return plural(ms, msAbs, m, "minute");
      }
      if (msAbs >= s) {
        return plural(ms, msAbs, s, "second");
      }
      return ms + " ms";
    }
    function plural(ms, msAbs, n, name) {
      var isPlural = msAbs >= n * 1.5;
      return Math.round(ms / n) + " " + name + (isPlural ? "s" : "");
    }
  }
});
var require_common = __commonJS({
  "../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js"(exports, module) {
    function setup(env) {
      createDebug2.debug = createDebug2;
      createDebug2.default = createDebug2;
      createDebug2.coerce = coerce;
      createDebug2.disable = disable;
      createDebug2.enable = enable;
      createDebug2.enabled = enabled;
      createDebug2.humanize = require_ms();
      createDebug2.destroy = destroy;
      Object.keys(env).forEach((key) => {
        createDebug2[key] = env[key];
      });
      createDebug2.names = [];
      createDebug2.skips = [];
      createDebug2.formatters = {};
      function selectColor(namespace) {
        let hash = 0;
        for (let i = 0; i < namespace.length; i++) {
          hash = (hash << 5) - hash + namespace.charCodeAt(i);
          hash |= 0;
        }
        return createDebug2.colors[Math.abs(hash) % createDebug2.colors.length];
      }
      createDebug2.selectColor = selectColor;
      function createDebug2(namespace) {
        let prevTime;
        let enableOverride = null;
        let namespacesCache;
        let enabledCache;
        function debug(...args) {
          if (!debug.enabled) {
            return;
          }
          const self = debug;
          const curr = Number(/* @__PURE__ */ new Date());
          const ms = curr - (prevTime || curr);
          self.diff = ms;
          self.prev = prevTime;
          self.curr = curr;
          prevTime = curr;
          args[0] = createDebug2.coerce(args[0]);
          if (typeof args[0] !== "string") {
            args.unshift("%O");
          }
          let index = 0;
          args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
            if (match === "%%") {
              return "%";
            }
            index++;
            const formatter = createDebug2.formatters[format];
            if (typeof formatter === "function") {
              const val = args[index];
              match = formatter.call(self, val);
              args.splice(index, 1);
              index--;
            }
            return match;
          });
          createDebug2.formatArgs.call(self, args);
          const logFn = self.log || createDebug2.log;
          logFn.apply(self, args);
        }
        debug.namespace = namespace;
        debug.useColors = createDebug2.useColors();
        debug.color = createDebug2.selectColor(namespace);
        debug.extend = extend;
        debug.destroy = createDebug2.destroy;
        Object.defineProperty(debug, "enabled", {
          enumerable: true,
          configurable: false,
          get: () => {
            if (enableOverride !== null) {
              return enableOverride;
            }
            if (namespacesCache !== createDebug2.namespaces) {
              namespacesCache = createDebug2.namespaces;
              enabledCache = createDebug2.enabled(namespace);
            }
            return enabledCache;
          },
          set: (v) => {
            enableOverride = v;
          }
        });
        if (typeof createDebug2.init === "function") {
          createDebug2.init(debug);
        }
        return debug;
      }
      function extend(namespace, delimiter) {
        const newDebug = createDebug2(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
        newDebug.log = this.log;
        return newDebug;
      }
      function enable(namespaces) {
        createDebug2.save(namespaces);
        createDebug2.namespaces = namespaces;
        createDebug2.names = [];
        createDebug2.skips = [];
        const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean);
        for (const ns of split) {
          if (ns[0] === "-") {
            createDebug2.skips.push(ns.slice(1));
          } else {
            createDebug2.names.push(ns);
          }
        }
      }
      function matchesTemplate(search, template) {
        let searchIndex = 0;
        let templateIndex = 0;
        let starIndex = -1;
        let matchIndex = 0;
        while (searchIndex < search.length) {
          if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) {
            if (template[templateIndex] === "*") {
              starIndex = templateIndex;
              matchIndex = searchIndex;
              templateIndex++;
            } else {
              searchIndex++;
              templateIndex++;
            }
          } else if (starIndex !== -1) {
            templateIndex = starIndex + 1;
            matchIndex++;
            searchIndex = matchIndex;
          } else {
            return false;
          }
        }
        while (templateIndex < template.length && template[templateIndex] === "*") {
          templateIndex++;
        }
        return templateIndex === template.length;
      }
      function disable() {
        const namespaces = [
          ...createDebug2.names,
          ...createDebug2.skips.map((namespace) => "-" + namespace)
        ].join(",");
        createDebug2.enable("");
        return namespaces;
      }
      function enabled(name) {
        for (const skip of createDebug2.skips) {
          if (matchesTemplate(name, skip)) {
            return false;
          }
        }
        for (const ns of createDebug2.names) {
          if (matchesTemplate(name, ns)) {
            return true;
          }
        }
        return false;
      }
      function coerce(val) {
        if (val instanceof Error) {
          return val.stack || val.message;
        }
        return val;
      }
      function destroy() {
        console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
      }
      createDebug2.enable(createDebug2.load());
      return createDebug2;
    }
    module.exports = setup;
  }
});
var require_browser = __commonJS({
  "../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/browser.js"(exports, module) {
    exports.formatArgs = formatArgs;
    exports.save = save;
    exports.load = load;
    exports.useColors = useColors;
    exports.storage = localstorage();
    exports.destroy = /* @__PURE__ */ (() => {
      let warned = false;
      return () => {
        if (!warned) {
          warned = true;
          console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
        }
      };
    })();
    exports.colors = [
      "#0000CC",
      "#0000FF",
      "#0033CC",
      "#0033FF",
      "#0066CC",
      "#0066FF",
      "#0099CC",
      "#0099FF",
      "#00CC00",
      "#00CC33",
      "#00CC66",
      "#00CC99",
      "#00CCCC",
      "#00CCFF",
      "#3300CC",
      "#3300FF",
      "#3333CC",
      "#3333FF",
      "#3366CC",
      "#3366FF",
      "#3399CC",
      "#3399FF",
      "#33CC00",
      "#33CC33",
      "#33CC66",
      "#33CC99",
      "#33CCCC",
      "#33CCFF",
      "#6600CC",
      "#6600FF",
      "#6633CC",
      "#6633FF",
      "#66CC00",
      "#66CC33",
      "#9900CC",
      "#9900FF",
      "#9933CC",
      "#9933FF",
      "#99CC00",
      "#99CC33",
      "#CC0000",
      "#CC0033",
      "#CC0066",
      "#CC0099",
      "#CC00CC",
      "#CC00FF",
      "#CC3300",
      "#CC3333",
      "#CC3366",
      "#CC3399",
      "#CC33CC",
      "#CC33FF",
      "#CC6600",
      "#CC6633",
      "#CC9900",
      "#CC9933",
      "#CCCC00",
      "#CCCC33",
      "#FF0000",
      "#FF0033",
      "#FF0066",
      "#FF0099",
      "#FF00CC",
      "#FF00FF",
      "#FF3300",
      "#FF3333",
      "#FF3366",
      "#FF3399",
      "#FF33CC",
      "#FF33FF",
      "#FF6600",
      "#FF6633",
      "#FF9900",
      "#FF9933",
      "#FFCC00",
      "#FFCC33"
    ];
    function useColors() {
      if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
        return true;
      }
      if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
        return false;
      }
      let m;
      return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
      typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
      // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
      typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
      typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
    }
    function formatArgs(args) {
      args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff);
      if (!this.useColors) {
        return;
      }
      const c = "color: " + this.color;
      args.splice(1, 0, c, "color: inherit");
      let index = 0;
      let lastC = 0;
      args[0].replace(/%[a-zA-Z%]/g, (match) => {
        if (match === "%%") {
          return;
        }
        index++;
        if (match === "%c") {
          lastC = index;
        }
      });
      args.splice(lastC, 0, c);
    }
    exports.log = console.debug || console.log || (() => {
    });
    function save(namespaces) {
      try {
        if (namespaces) {
          exports.storage.setItem("debug", namespaces);
        } else {
          exports.storage.removeItem("debug");
        }
      } catch (error) {
      }
    }
    function load() {
      let r;
      try {
        r = exports.storage.getItem("debug") || exports.storage.getItem("DEBUG");
      } catch (error) {
      }
      if (!r && typeof process !== "undefined" && "env" in process) {
        r = process.env.DEBUG;
      }
      return r;
    }
    function localstorage() {
      try {
        return localStorage;
      } catch (error) {
      }
    }
    module.exports = require_common()(exports);
    var { formatters } = module.exports;
    formatters.j = function(v) {
      try {
        return JSON.stringify(v);
      } catch (error) {
        return "[UnexpectedJSONParseError]: " + error.message;
      }
    };
  }
});
var require_has_flag = __commonJS({
  "../../node_modules/.pnpm/has-flag@4.0.0/node_modules/has-flag/index.js"(exports, module) {
    "use strict";
    module.exports = (flag, argv = process.argv) => {
      const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
      const position = argv.indexOf(prefix + flag);
      const terminatorPosition = argv.indexOf("--");
      return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
    };
  }
});
var require_supports_color = __commonJS({
  "../../node_modules/.pnpm/supports-color@7.2.0/node_modules/supports-color/index.js"(exports, module) {
    "use strict";
    var os = __require2("os");
    var tty = __require2("tty");
    var hasFlag = require_has_flag();
    var { env } = process;
    var forceColor;
    if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
      forceColor = 0;
    } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
      forceColor = 1;
    }
    if ("FORCE_COLOR" in env) {
      if (env.FORCE_COLOR === "true") {
        forceColor = 1;
      } else if (env.FORCE_COLOR === "false") {
        forceColor = 0;
      } else {
        forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);
      }
    }
    function translateLevel(level) {
      if (level === 0) {
        return false;
      }
      return {
        level,
        hasBasic: true,
        has256: level >= 2,
        has16m: level >= 3
      };
    }
    function supportsColor(haveStream, streamIsTTY) {
      if (forceColor === 0) {
        return 0;
      }
      if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
        return 3;
      }
      if (hasFlag("color=256")) {
        return 2;
      }
      if (haveStream && !streamIsTTY && forceColor === void 0) {
        return 0;
      }
      const min = forceColor || 0;
      if (env.TERM === "dumb") {
        return min;
      }
      if (process.platform === "win32") {
        const osRelease = os.release().split(".");
        if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
          return Number(osRelease[2]) >= 14931 ? 3 : 2;
        }
        return 1;
      }
      if ("CI" in env) {
        if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
          return 1;
        }
        return min;
      }
      if ("TEAMCITY_VERSION" in env) {
        return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
      }
      if (env.COLORTERM === "truecolor") {
        return 3;
      }
      if ("TERM_PROGRAM" in env) {
        const version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
        switch (env.TERM_PROGRAM) {
          case "iTerm.app":
            return version >= 3 ? 3 : 2;
          case "Apple_Terminal":
            return 2;
        }
      }
      if (/-256(color)?$/i.test(env.TERM)) {
        return 2;
      }
      if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
        return 1;
      }
      if ("COLORTERM" in env) {
        return 1;
      }
      return min;
    }
    function getSupportLevel(stream) {
      const level = supportsColor(stream, stream && stream.isTTY);
      return translateLevel(level);
    }
    module.exports = {
      supportsColor: getSupportLevel,
      stdout: translateLevel(supportsColor(true, tty.isatty(1))),
      stderr: translateLevel(supportsColor(true, tty.isatty(2)))
    };
  }
});
var require_node = __commonJS({
  "../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/node.js"(exports, module) {
    var tty = __require2("tty");
    var util = __require2("util");
    exports.init = init;
    exports.log = log;
    exports.formatArgs = formatArgs;
    exports.save = save;
    exports.load = load;
    exports.useColors = useColors;
    exports.destroy = util.deprecate(
      () => {
      },
      "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."
    );
    exports.colors = [6, 2, 3, 4, 5, 1];
    try {
      const supportsColor = require_supports_color();
      if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
        exports.colors = [
          20,
          21,
          26,
          27,
          32,
          33,
          38,
          39,
          40,
          41,
          42,
          43,
          44,
          45,
          56,
          57,
          62,
          63,
          68,
          69,
          74,
          75,
          76,
          77,
          78,
          79,
          80,
          81,
          92,
          93,
          98,
          99,
          112,
          113,
          128,
          129,
          134,
          135,
          148,
          149,
          160,
          161,
          162,
          163,
          164,
          165,
          166,
          167,
          168,
          169,
          170,
          171,
          172,
          173,
          178,
          179,
          184,
          185,
          196,
          197,
          198,
          199,
          200,
          201,
          202,
          203,
          204,
          205,
          206,
          207,
          208,
          209,
          214,
          215,
          220,
          221
        ];
      }
    } catch (error) {
    }
    exports.inspectOpts = Object.keys(process.env).filter((key) => {
      return /^debug_/i.test(key);
    }).reduce((obj, key) => {
      const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => {
        return k.toUpperCase();
      });
      let val = process.env[key];
      if (/^(yes|on|true|enabled)$/i.test(val)) {
        val = true;
      } else if (/^(no|off|false|disabled)$/i.test(val)) {
        val = false;
      } else if (val === "null") {
        val = null;
      } else {
        val = Number(val);
      }
      obj[prop] = val;
      return obj;
    }, {});
    function useColors() {
      return "colors" in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd);
    }
    function formatArgs(args) {
      const { namespace: name, useColors: useColors2 } = this;
      if (useColors2) {
        const c = this.color;
        const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c);
        const prefix = `  ${colorCode};1m${name} \x1B[0m`;
        args[0] = prefix + args[0].split("\n").join("\n" + prefix);
        args.push(colorCode + "m+" + module.exports.humanize(this.diff) + "\x1B[0m");
      } else {
        args[0] = getDate() + name + " " + args[0];
      }
    }
    function getDate() {
      if (exports.inspectOpts.hideDate) {
        return "";
      }
      return (/* @__PURE__ */ new Date()).toISOString() + " ";
    }
    function log(...args) {
      return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + "\n");
    }
    function save(namespaces) {
      if (namespaces) {
        process.env.DEBUG = namespaces;
      } else {
        delete process.env.DEBUG;
      }
    }
    function load() {
      return process.env.DEBUG;
    }
    function init(debug) {
      debug.inspectOpts = {};
      const keys = Object.keys(exports.inspectOpts);
      for (let i = 0; i < keys.length; i++) {
        debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
      }
    }
    module.exports = require_common()(exports);
    var { formatters } = module.exports;
    formatters.o = function(v) {
      this.inspectOpts.colors = this.useColors;
      return util.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" ");
    };
    formatters.O = function(v) {
      this.inspectOpts.colors = this.useColors;
      return util.inspect(v, this.inspectOpts);
    };
  }
});
var require_src = __commonJS({
  "../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/index.js"(exports, module) {
    if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) {
      module.exports = require_browser();
    } else {
      module.exports = require_node();
    }
  }
});
var import_debug = __toESM(require_src());
var logInfo = (0, import_debug.default)("info");
var logTask = (0, import_debug.default)("task");
var logError = (0, import_debug.default)("error");
var logDetail = (0, import_debug.default)("detail");
function logNamespace(namespace) {
  logInfo.namespace = `${namespace}:INFO`;
  logTask.namespace = `${namespace}:TASK`;
  logError.namespace = `${namespace}:ERROR`;
  logDetail.namespace = `${namespace}:DETAIL`;
  logInfo.color = "45";
  logTask.color = "40";
  logError.color = "160";
  logDetail.color = "240";
}

// src/resolve-cli-path.ts
import { existsSync } from "node:fs";
import { dirname, isAbsolute, join } from "node:path";
import { fileURLToPath } from "node:url";
function getCurrentModuleDir() {
  if (typeof import.meta !== "undefined" && import.meta.url) {
    return dirname(fileURLToPath(import.meta.url));
  }
  if (typeof __dirname !== "undefined") {
    return __dirname;
  }
  return process.cwd();
}
function resolveCliPath() {
  const exeName = process.platform === "win32" ? "pmd3_cli.exe" : "pmd3_cli";
  if (process.env.PMD_CLI_PATH) {
    if (isAbsolute(process.env.PMD_CLI_PATH)) {
      return join(process.env.PMD_CLI_PATH, exeName);
    }
    const absolutePath = join(process.cwd(), process.env.PMD_CLI_PATH, exeName);
    if (existsSync(absolutePath)) {
      return absolutePath;
    }
    logError(`Absolute path does not exist: ${absolutePath}`);
    return "";
  }
  const moduleDir = getCurrentModuleDir();
  const possiblePaths = [
    join(moduleDir, "..", "dist", "bin", "pmd3_cli", exeName),
    join(moduleDir, "..", "bin", "pmd3_cli", exeName),
    join(moduleDir, "bin", "pmd3_cli", exeName)
  ];
  for (const path of possiblePaths) {
    logDetail("Checking path:", path);
    if (existsSync(path)) {
      return path;
    }
  }
  return "";
}

// src/cli.ts
logNamespace("cli");
async function runPyMobileDevice(args, options = {}) {
  return new Promise((resolve, reject) => {
    const timeout = options.timeout ?? 3e4;
    let command;
    if (options.executablePath) {
      command = options.executablePath;
    } else {
      const resolved = resolveCliPath();
      command = resolved;
    }
    logInfo("Executing command:", command, args);
    const child = spawn(command, args);
    const timeoutId = setTimeout(() => {
      child.kill();
      reject(new Error("Command timed out"));
    }, timeout);
    let stdout = "";
    let stderr = "";
    child.stdout.on("data", (data) => {
      stdout += data.toString();
    });
    child.stderr.on("error", (error) => {
      logError("Error:", error);
      stderr += error.toString();
      clearTimeout(timeoutId);
      reject(error);
    });
    child.on("exit", (code, _signal) => {
      clearTimeout(timeoutId);
      let data;
      try {
        data = JSON.parse(stdout);
      } catch {
        data = stdout;
      }
      resolve({
        success: code === 0,
        stdout: data,
        stderr,
        exitCode: code
      });
    });
  });
}

// src/pymobiledevice.ts
import { existsSync as existsSync2, mkdirSync } from "node:fs";
async function listDevices(options) {
  const result = await runPyMobileDevice(["usbmux", "list"], {
    executablePath: options?.executablePath,
    timeout: options?.timeout
  });
  if (!result.success) {
    return [];
  }
  try {
    if (typeof result.stdout === "string") {
      const parsed = JSON.parse(result.stdout);
      return Array.isArray(parsed) ? parsed : [];
    }
    if (Array.isArray(result.stdout)) {
      return result.stdout;
    }
    return [];
  } catch {
    return [];
  }
}
async function info(udid, options) {
  const result = await runPyMobileDevice(["lockdown", "info", "--udid", udid], {
    executablePath: options?.executablePath,
    timeout: options?.timeout
  });
  if (typeof result.stdout === "object") {
    return result.stdout;
  }
  try {
    return JSON.parse(result.stdout);
  } catch {
    return {};
  }
}
async function eraseDevice(udid, options) {
  return runPyMobileDevice(["profile", "erase-device", "--udid", udid], {
    executablePath: options?.executablePath,
    timeout: options?.timeout ?? 6e4
    // Erase may take longer
  });
}
async function superviseDevice(udid, organizationName, options) {
  return runPyMobileDevice(["profile", "supervise", organizationName, "--udid", udid], {
    executablePath: options?.executablePath,
    timeout: options?.timeout ?? 6e4
  });
}
async function setCloudConfiguration(udid, plistPath, options) {
  return runPyMobileDevice(
    ["profile", "cloud-configuration", "--udid", udid, "--config", plistPath],
    {
      executablePath: options?.executablePath,
      timeout: options?.timeout ?? 6e4
    }
  );
}
async function getCloudConfiguration(udid, options) {
  const result = await runPyMobileDevice(["profile", "cloud-configuration", "--udid", udid], {
    executablePath: options?.executablePath,
    timeout: options?.timeout
  });
  if (!result.success) {
    return null;
  }
  try {
    if (typeof result.stdout === "object") {
      return result.stdout;
    }
    return JSON.parse(result.stdout);
  } catch {
    return null;
  }
}
async function launchApp(udid, appId, options) {
  return runPyMobileDevice(["developer", "dvt", "launch", appId, "--udid", udid], {
    executablePath: options?.executablePath,
    timeout: options?.timeout
  });
}
async function setLanguage(udid, language, options) {
  return runPyMobileDevice(["lockdown", "language", "--language", language, "--udid", udid], {
    executablePath: options?.executablePath,
    timeout: options?.timeout
  });
}
async function setLocale(udid, locale, options) {
  return runPyMobileDevice(["lockdown", "locale", "--locale", locale, "--udid", udid], {
    executablePath: options?.executablePath,
    timeout: options?.timeout
  });
}
async function restartDevice(udid, options) {
  return runPyMobileDevice(["diagnostics", "restart", "--udid", udid], {
    executablePath: options?.executablePath,
    timeout: options?.timeout
  });
}
async function checkDeveloperModeStatus(udid, options) {
  const result = await runPyMobileDevice(["amfi", "developer-mode-status", "--udid", udid], {
    executablePath: options?.executablePath,
    timeout: options?.timeout
  });
  if (!result.success) {
    return false;
  }
  const output = String(result.stdout || result.stderr || "").trim().toLowerCase();
  return output === "true" || output === "enabled" || output.includes("enabled") && !output.includes("not enabled");
}
async function enableDeveloperMode(udid, options) {
  const args = ["amfi", "enable-developer-mode", "--udid", udid];
  if (options?.useTunnel) {
    args.push("--tunnel", "");
  }
  return runPyMobileDevice(args, {
    executablePath: options?.executablePath,
    timeout: options?.timeout ?? 6e4
  });
}
async function activateDevice(udid, options) {
  return runPyMobileDevice(["activation", "activate", "--udid", udid], {
    executablePath: options?.executablePath,
    timeout: options?.timeout
  });
}
async function pairDevice(udid, options) {
  return runPyMobileDevice(["lockdown", "pair", "--udid", udid], {
    executablePath: options?.executablePath,
    timeout: options?.timeout
  });
}
async function getDevicesInfo(udids, options) {
  const devices = await listDevices(options);
  return devices.filter((d) => d.Identifier && udids.includes(d.Identifier)) ?? [];
}
async function isDeviceSupervised(udid, options) {
  const config = await getCloudConfiguration(udid, options);
  return config?.IsSupervised === true;
}
async function waitForDevice(udid, timeout = 12e4, options) {
  const startTime = Date.now();
  const pollInterval = 2e3;
  while (Date.now() - startTime < timeout) {
    const devices = await listDevices(options);
    const found = devices.some((d) => d.Identifier === udid);
    if (found) {
      return true;
    }
    await new Promise((resolve) => setTimeout(resolve, pollInterval));
  }
  return false;
}
async function waitForDeviceDisconnect(udid, timeout = 3e4, options) {
  const startTime = Date.now();
  const pollInterval = 1e3;
  while (Date.now() - startTime < timeout) {
    const devices = await listDevices(options);
    const found = devices.some((d) => d.Identifier === udid);
    if (!found) {
      return true;
    }
    await new Promise((resolve) => setTimeout(resolve, pollInterval));
  }
  return false;
}
async function generateProfile(profileData, name = "mce_profile") {
  const fs = await import("node:fs/promises");
  const os = await import("node:os");
  const path = await import("node:path");
  const tempDir = os.tmpdir();
  if (!existsSync2(path.join(tempDir, "mce"))) {
    mkdirSync(path.join(tempDir, "mce"), { recursive: true });
  }
  const profilePath = path.join(tempDir, "mce", `${name}_${Date.now()}.mobileconfig`);
  let profileContent;
  if (profileData.includes("<?xml") || profileData.includes("<plist")) {
    profileContent = profileData;
  } else {
    profileContent = Buffer.from(profileData, "base64").toString("utf-8");
  }
  await fs.writeFile(profilePath, profileContent, "utf-8");
  return profilePath;
}
async function installProfile(profilePath, udid, options) {
  return runPyMobileDevice(["profile", "install", "--udid", udid, profilePath], {
    executablePath: options?.executablePath,
    timeout: options?.timeout
  });
}
async function installProfileFromFile(profileFilePath, udid, name = "mce_profile", options) {
  const fs = await import("node:fs/promises");
  const profileContent = await fs.readFile(profileFilePath, "utf-8");
  const randomizedContent = profileContent.replace(
    /(<key>PayloadIdentifier<\/key>\s*<string>)(.*?)(<\/string>)/g,
    `$1$2.${Date.now()}$3`
  );
  const tempPath = await generateProfile(randomizedContent, name);
  return installProfile(tempPath, udid, options);
}
async function uninstallApp(bundleId, udid, options) {
  return runPyMobileDevice(["apps", "uninstall", "--udid", udid, bundleId], {
    executablePath: options?.executablePath,
    timeout: options?.timeout
  });
}
async function isAppInstalled(bundleId, udid, options) {
  const result = await runPyMobileDevice(["apps", "list", "--udid", udid], {
    executablePath: options?.executablePath,
    timeout: options?.timeout
  });
  if (!result.success) {
    return false;
  }
  try {
    const apps = result.stdout;
    if (typeof apps === "object" && apps !== null && !Array.isArray(apps)) {
      return Object.keys(apps).includes(bundleId);
    }
    if (Array.isArray(apps)) {
      return apps.some((app) => {
        if (typeof app === "string") {
          return app === bundleId;
        }
        return app.CFBundleIdentifier === bundleId;
      });
    }
    return false;
  } catch {
    return false;
  }
}
export {
  activateDevice,
  checkDeveloperModeStatus,
  enableDeveloperMode,
  eraseDevice,
  generateProfile,
  getCloudConfiguration,
  getDevicesInfo,
  info,
  installProfile,
  installProfileFromFile,
  isAppInstalled,
  isDeviceSupervised,
  launchApp,
  listDevices,
  pairDevice,
  resolveCliPath,
  restartDevice,
  runPyMobileDevice,
  setCloudConfiguration,
  setLanguage,
  setLocale,
  superviseDevice,
  uninstallApp,
  waitForDevice,
  waitForDeviceDisconnect
};
//# sourceMappingURL=index.mjs.map
