var __importMetaUrl = require("url").pathToFileURL(__filename).href;
"use strict";
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 __commonJS = (cb, mod) => function __require() {
  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
));

// ../../node_modules/.pnpm/node-windows@1.0.0-beta.8/node_modules/node-windows/lib/binaries.js
var require_binaries = __commonJS({
  "../../node_modules/.pnpm/node-windows@1.0.0-beta.8/node_modules/node-windows/lib/binaries.js"(exports2, module2) {
    var path = require("path");
    var bin = path.join(__dirname, "..", "bin");
    var exec = require("child_process").exec;
    var params = function(options, callback2) {
      callback2 = callback2 || function() {
      };
      options = options || {};
      if (typeof options === "function") {
        callback2 = options;
        options = {};
      }
      if (typeof options !== "object") {
        throw "Invalid options parameter.";
      }
      return { options, callback: callback2 };
    };
    module2.exports = {
      /**
       * @method elevate
       * @member nodewindows
       * Elevate is similar to `sudo` on Linux/Mac. It attempts to elevate the privileges of the
       * current user to a local administrator. Using this does not require a password, but it
       * does require that the current user have administrative privileges. Without these
       * privileges, the command will fail with a `access denied` error.
       *
       * On systems with UAC enabled, this may prompt the user for permission to proceed:
       *
       * ![UAC Prompt](http://upload.wikimedia.org/wikipedia/en/5/51/Windows_7_UAC.png)
       *
       * **Syntax**:
       *
       * `elevate(cmd[,options,callback])`
       *
       * @param {String} cmd
       * The command to execute with elevated privileges. This can be any string that would be typed at the command line.
       * @param {Object} [options]
       * Any options that will be passed to `require('child_process').exec(cmd,<OPTIONS>,callback)`.
       * @param {Function} callback
       * The callback function passed to `require('child_process').exec(cmd,options,<CALLBACK>)`.
       */
      elevate: function(cmd, options, callback2) {
        var p = params(options, callback2);
        exec('"' + path.join(bin, "elevate", "elevate.cmd") + '" ' + cmd, p.options, p.callback);
      },
      /**
       * @method sudo
       * @member nodewindows
       * Sudo acts similarly to `sudo` on Linux/Mac. Unlike _elevate_, it requires a password, but it
       * will not prompt the user for permission to proceed. Like _elevate_, this
       * _still requires administrative privileges_ for the user, otherwise the command will fail.
       * The primary difference between this and _elevate()_ is the prompt.
       *
       * **Syntax**:
       *
       * `sudo(cmd,password[,options,callback])`
       *
       * @param {String} cmd
       * The command to execute with elevated privileges. This can be any string that would be typed at the command line.
       * @param {String} password
       * The password of the user
       * @param {Object} [options]
       * Any options that will be passed to `require('child_process').exec(cmd,<OPTIONS>,callback)`.
       * @param {Function} [callback]
       * The callback function passed to `require('child_process').exec(cmd,options,<CALLBACK>)`.
       */
      sudo: function(cmd, password, options, callback2) {
        password = password || "";
        if (typeof password !== "string") {
          callback2 = options;
          options = password;
          password = "";
        }
        var p = params(options, callback2);
        exec(path.join(bin, "sudowin", "sudo.exe") + " " + (password !== "" ? "-p " + password : "") + cmd, p.options, p.callback);
      }
    };
  }
});

// ../../node_modules/.pnpm/node-windows@1.0.0-beta.8/node_modules/node-windows/lib/cmd.js
var require_cmd = __commonJS({
  "../../node_modules/.pnpm/node-windows@1.0.0-beta.8/node_modules/node-windows/lib/cmd.js"(exports2, module2) {
    var exec = require("child_process").exec;
    var bin = require_binaries();
    module2.exports = {
      /**
       * @method isAdminUser
       * @member nodewindows
       * This asynchronous command determines whether the current user has administrative privileges.
       * It passes a boolean value to the callback, returning `true` if the user is an administrator
       * or `false` if it is not.
       * @param {Function} callback
       * @param {Boolean} callback.isAdmin
       * Receives true/false as an argument to the callback.
       */
      isAdminUser: function(callback2) {
        exec("NET SESSION", function(err, so, se) {
          if (se.length !== 0) {
            bin.elevate("NET SESSION", function(_err, _so, _se) {
              callback2(_se.length === 0);
            });
          } else {
            callback2(true);
          }
        });
      },
      /**
       * @method kill
       * @member nodewindows
       * Kill a specific process
       * @param {Number} PID
       * Process ID
       * @param {Boolean} [force=false]
       * Force close the process.
       * @param {Function} [callback]
       */
      kill: function(pid, force, callback2) {
        if (!pid) {
          throw new Error("PID is required for the kill operation.");
        }
        if (typeof isNaN(pid)) {
          throw new Error("PID must be a number.");
        }
        callback2 = callback2 || function() {
        };
        if (typeof force == "function") {
          callback2 = force;
          force = false;
        }
        exec("taskkill /PID " + pid + (force == true ? " /f" : ""), callback2);
      },
      /**
       * @method list
       * @member nodewindows
       * List the processes running on the server.
       * @param {Function} callback
       * Receives the process object as the only callback argument
       * @param {Boolean} [verbose=false]
       */
      list: function(callback2, verbose) {
        verbose = typeof verbose == "boolean" ? verbose : false;
        exec("tasklist /FO CSV" + (verbose == true ? " /V" : ""), function(err, stdout, stderr) {
          var p = stdout.split("\r\n");
          var proc = [];
          var head = null;
          while (p.length > 1) {
            var rec = p.shift();
            rec = rec.replace(/\"\,/gi, '";').replace(/\"|\'/gi, "").split(";");
            if (head == null) {
              head = rec;
              for (var i = 0; i < head.length; i++) {
                head[i] = head[i].replace(/ /gi, "");
              }
            } else {
              var tmp = {};
              for (var i = 0; i < rec.length; i++) {
                tmp[head[i]] = rec[i].replace(/\"|\'/gi, "");
              }
              proc.push(tmp);
            }
          }
          callback2(proc);
        });
      }
    };
  }
});

// ../../node_modules/.pnpm/node-windows@1.0.0-beta.8/node_modules/node-windows/lib/eventlog.js
var require_eventlog = __commonJS({
  "../../node_modules/.pnpm/node-windows@1.0.0-beta.8/node_modules/node-windows/lib/eventlog.js"(exports2, module2) {
    var wincmd = require_binaries();
    var exec = require("child_process").exec;
    var eventlogs = ["APPLICATION", "SYSTEM"];
    var validtypes = ["ERROR", "WARNING", "INFORMATION", "SUCCESSAUDIT", "FAILUREAUDIT"];
    var write = function(log2, src, type, msg, id, callback2) {
      var cmd;
      if (msg == null) {
        return;
      }
      ;
      if (msg.trim().length == 0) {
        return;
      }
      ;
      msg = msg.replace(/\r\n|\n\r|\r|\n/g, "\f");
      log2 = log2 || "APPLICATION";
      log2 = eventlogs.indexOf(log2.toUpperCase()) >= 0 ? log2 : "APPLICATION";
      type = (type || "INFORMATION").trim().toUpperCase();
      type = (validtypes.indexOf(type.trim().toUpperCase()) >= 0 ? type : "INFORMATION").trim().toUpperCase();
      id = typeof id == "number" ? id > 0 ? id : 1e3 : 1e3;
      src = (src || "Unknown Application").trim();
      cmd = "eventcreate /L " + log2 + " /T " + type + ' /SO "' + src + '" /D "' + msg + '" /ID ' + id;
      exec(cmd, function(err) {
        if (err && err.message.indexOf("Access is Denied")) {
          wincmd.elevate(cmd, callback2);
        } else if (callback2) {
          callback2(err);
        }
      });
    };
    var logger = function(config) {
      config = config || {};
      if (typeof config == "string") {
        config = {
          source: config
        };
      }
      Object.defineProperties(this, {
        /**
         * @cfg {String} [name=Node.js]
         * The source of the log information. This is commonly the title of an application
         * or the Node.js script name (i.e. MyApp).
         */
        source: {
          enumerable: true,
          writable: true,
          configurable: false,
          value: config.source || "Node.js"
        },
        _logname: {
          enumerable: false,
          writable: true,
          configurable: false,
          value: config.eventLog || "APPLICATION"
        },
        /**
         * @cfg {String} [eventLog=APPLICATION]
         * The event log where messages should be written. This is either `APPLICATION` or `SYSTEM`.
         */
        eventLog: {
          enumerable: true,
          get: function() {
            return this._logname.toUpperCase();
          },
          set: function(value) {
            if (value) {
              this._logname = eventlogs.indexOf(value.toUpperCase()) >= 0 ? value.toUpperCase() : "APPLICATION";
            }
          }
        },
        /**
         * @method info
         * Log an informational message.
         * @param {String} message
         * The content of the log message.
         * @param {Number} [code=1000]
         * The event code to assign to the message.
         * @param {Function} [callback]
         * An optional callback to run when the message is logged.
         */
        info: {
          enumerable: true,
          writable: true,
          configurable: false,
          value: function(message, code, callback2) {
            write(this.eventLog, this.source, "INFORMATION", message, code, callback2);
          }
        },
        information: {
          enumerable: false,
          get: function() {
            return this.info;
          }
        },
        /**
         * @method error
         * Log an error message.
         * @param {String} message
         * The content of the log message.
         * @param {Number} [code=1000]
         * The event code to assign to the message.
         * @param {Function} [callback]
         * An optional callback to run when the message is logged.
         */
        error: {
          enumerable: true,
          writable: true,
          configurable: false,
          value: function(message, code, callback2) {
            write(this.eventLog, this.source, "ERROR", message, code, callback2);
          }
        },
        /**
         * @method warn
         * Log a warning message.
         * @param {String} message
         * The content of the log message.
         * @param {Number} [code=1000]
         * The event code to assign to the message.
         * @param {Function} [callback]
         * An optional callback to run when the message is logged.
         */
        warn: {
          enumerable: true,
          writable: true,
          configurable: false,
          value: function(message, code, callback2) {
            write(this.eventLog, this.source, "WARNING", message, code, callback2);
          }
        },
        warning: {
          enumerable: false,
          get: function() {
            return this.warn;
          }
        },
        /**
         * @method auditSuccess
         * Log an audit success message.
         * @param {String} message
         * The content of the log message.
         * @param {Number} [code=1000]
         * The event code to assign to the message.
         * @param {Function} [callback]
         * An optional callback to run when the message is logged.
         */
        auditSuccess: {
          enumerable: true,
          writable: true,
          configurable: false,
          value: function(message, code, callback2) {
            write(this.eventLog, this.source, "SUCCESSAUDIT", message, code, callback2);
          }
        },
        /**
         * @method auditFailure
         * Log an audit failure message.
         * @param {String} message
         * The content of the log message.
         * @param {Number} [code=1000]
         * The event code to assign to the message.
         * @param {Function} [callback]
         * An optional callback to run when the message is logged.
         */
        auditFailure: {
          enumerable: true,
          writable: true,
          configurable: false,
          value: function(message, code, callback2) {
            write(this.eventLog, this.source, "FAILUREAUDIT", message, code, callback2);
          }
        }
      });
    };
    module2.exports = logger;
  }
});

// ../../node_modules/.pnpm/xml@1.0.1/node_modules/xml/lib/escapeForXML.js
var require_escapeForXML = __commonJS({
  "../../node_modules/.pnpm/xml@1.0.1/node_modules/xml/lib/escapeForXML.js"(exports2, module2) {
    var XML_CHARACTER_MAP = {
      "&": "&amp;",
      '"': "&quot;",
      "'": "&apos;",
      "<": "&lt;",
      ">": "&gt;"
    };
    function escapeForXML(string) {
      return string && string.replace ? string.replace(/([&"<>'])/g, function(str, item) {
        return XML_CHARACTER_MAP[item];
      }) : string;
    }
    module2.exports = escapeForXML;
  }
});

// ../../node_modules/.pnpm/xml@1.0.1/node_modules/xml/lib/xml.js
var require_xml = __commonJS({
  "../../node_modules/.pnpm/xml@1.0.1/node_modules/xml/lib/xml.js"(exports2, module2) {
    var escapeForXML = require_escapeForXML();
    var Stream = require("stream").Stream;
    var DEFAULT_INDENT = "    ";
    function xml(input, options) {
      if (typeof options !== "object") {
        options = {
          indent: options
        };
      }
      var stream = options.stream ? new Stream() : null, output = "", interrupted = false, indent = !options.indent ? "" : options.indent === true ? DEFAULT_INDENT : options.indent, instant = true;
      function delay(func) {
        if (!instant) {
          func();
        } else {
          process.nextTick(func);
        }
      }
      function append(interrupt, out) {
        if (out !== void 0) {
          output += out;
        }
        if (interrupt && !interrupted) {
          stream = stream || new Stream();
          interrupted = true;
        }
        if (interrupt && interrupted) {
          var data = output;
          delay(function() {
            stream.emit("data", data);
          });
          output = "";
        }
      }
      function add(value, last) {
        format(append, resolve(value, indent, indent ? 1 : 0), last);
      }
      function end() {
        if (stream) {
          var data = output;
          delay(function() {
            stream.emit("data", data);
            stream.emit("end");
            stream.readable = false;
            stream.emit("close");
          });
        }
      }
      function addXmlDeclaration(declaration) {
        var encoding = declaration.encoding || "UTF-8", attr = { version: "1.0", encoding };
        if (declaration.standalone) {
          attr.standalone = declaration.standalone;
        }
        add({ "?xml": { _attr: attr } });
        output = output.replace("/>", "?>");
      }
      delay(function() {
        instant = false;
      });
      if (options.declaration) {
        addXmlDeclaration(options.declaration);
      }
      if (input && input.forEach) {
        input.forEach(function(value, i) {
          var last;
          if (i + 1 === input.length)
            last = end;
          add(value, last);
        });
      } else {
        add(input, end);
      }
      if (stream) {
        stream.readable = true;
        return stream;
      }
      return output;
    }
    function element() {
      var input = Array.prototype.slice.call(arguments), self = {
        _elem: resolve(input)
      };
      self.push = function(input2) {
        if (!this.append) {
          throw new Error("not assigned to a parent!");
        }
        var that = this;
        var indent = this._elem.indent;
        format(
          this.append,
          resolve(
            input2,
            indent,
            this._elem.icount + (indent ? 1 : 0)
          ),
          function() {
            that.append(true);
          }
        );
      };
      self.close = function(input2) {
        if (input2 !== void 0) {
          this.push(input2);
        }
        if (this.end) {
          this.end();
        }
      };
      return self;
    }
    function create_indent(character, count) {
      return new Array(count || 0).join(character || "");
    }
    function resolve(data, indent, indent_count) {
      indent_count = indent_count || 0;
      var indent_spaces = create_indent(indent, indent_count);
      var name;
      var values = data;
      var interrupt = false;
      if (typeof data === "object") {
        var keys = Object.keys(data);
        name = keys[0];
        values = data[name];
        if (values && values._elem) {
          values._elem.name = name;
          values._elem.icount = indent_count;
          values._elem.indent = indent;
          values._elem.indents = indent_spaces;
          values._elem.interrupt = values;
          return values._elem;
        }
      }
      var attributes = [], content = [];
      var isStringContent;
      function get_attributes(obj) {
        var keys2 = Object.keys(obj);
        keys2.forEach(function(key) {
          attributes.push(attribute(key, obj[key]));
        });
      }
      switch (typeof values) {
        case "object":
          if (values === null) break;
          if (values._attr) {
            get_attributes(values._attr);
          }
          if (values._cdata) {
            content.push(
              ("<![CDATA[" + values._cdata).replace(/\]\]>/g, "]]]]><![CDATA[>") + "]]>"
            );
          }
          if (values.forEach) {
            isStringContent = false;
            content.push("");
            values.forEach(function(value) {
              if (typeof value == "object") {
                var _name = Object.keys(value)[0];
                if (_name == "_attr") {
                  get_attributes(value._attr);
                } else {
                  content.push(resolve(
                    value,
                    indent,
                    indent_count + 1
                  ));
                }
              } else {
                content.pop();
                isStringContent = true;
                content.push(escapeForXML(value));
              }
            });
            if (!isStringContent) {
              content.push("");
            }
          }
          break;
        default:
          content.push(escapeForXML(values));
      }
      return {
        name,
        interrupt,
        attributes,
        content,
        icount: indent_count,
        indents: indent_spaces,
        indent
      };
    }
    function format(append, elem, end) {
      if (typeof elem != "object") {
        return append(false, elem);
      }
      var len = elem.interrupt ? 1 : elem.content.length;
      function proceed() {
        while (elem.content.length) {
          var value = elem.content.shift();
          if (value === void 0) continue;
          if (interrupt(value)) return;
          format(append, value);
        }
        append(false, (len > 1 ? elem.indents : "") + (elem.name ? "</" + elem.name + ">" : "") + (elem.indent && !end ? "\n" : ""));
        if (end) {
          end();
        }
      }
      function interrupt(value) {
        if (value.interrupt) {
          value.interrupt.append = append;
          value.interrupt.end = proceed;
          value.interrupt = false;
          append(true);
          return true;
        }
        return false;
      }
      append(false, elem.indents + (elem.name ? "<" + elem.name : "") + (elem.attributes.length ? " " + elem.attributes.join(" ") : "") + (len ? elem.name ? ">" : "" : elem.name ? "/>" : "") + (elem.indent && len > 1 ? "\n" : ""));
      if (!len) {
        return append(false, elem.indent ? "\n" : "");
      }
      if (!interrupt(elem)) {
        proceed();
      }
    }
    function attribute(key, value) {
      return key + '="' + escapeForXML(value) + '"';
    }
    module2.exports = xml;
    module2.exports.element = module2.exports.Element = element;
  }
});

// ../../node_modules/.pnpm/node-windows@1.0.0-beta.8/node_modules/node-windows/lib/winsw.js
var require_winsw = __commonJS({
  "../../node_modules/.pnpm/node-windows@1.0.0-beta.8/node_modules/node-windows/lib/winsw.js"(exports2, module2) {
    module2.exports = {
      /**
       * @method generateXml
       * Generate the XML for the winsw configuration file.
       * @param {Object} config
       * The config object must have the following attributes:
       *
       * - *id* This is is how the service is identified. Alphanumeric, no spaces.
       * - *name* The descriptive name of the service.
       * - *script* The absolute path of the node.js server script. i.e. in this case
       *  it's the wrapper script, not the user's server script.
       *
       * Optional attributes include
       *
       * - *description* The description that shows up in the service manager.
       * - *nodeOptions* Array or space separated string of node options (e.g. '--harmony')
       * - *wrapperArgs* additional arguments to pass to wrapper script to control restarts, etc.
       * - *logmode* Valid values include `rotate` (default), `reset` (clear log), `roll` (move to .old), and `append`.
       * - *logging* Supersedes *logmode*. Object of form `{mode: 'append'}`,
       * `{mode: 'reset'}`, `{mode: 'none'}`, `{mode: 'roll-by-time', pattern: 'yyyMMdd'}`,
       * or `{mode: 'roll-by-size', sizeThreshold: 10240, keepFiles: 8}` (all attributes optional,
       * example shows defaults). See [winsw docs](https://github.com/kohsuke/winsw/tree/winsw-1.17#logging).
       * - *logpath* The absolute path to the directory where logs should be stored. Defaults to the current directory.
       * - *dependencies* A comma delimited list or array of process dependencies.
       * - *env* A key/value object or array of key/value objects containing
       * environment variables to pass to the process. The object might look like `{name:'HOME',value:'c:\Windows'}`.
       * - *logOnAs* A key/value object that contains the service logon credentials.
       * The object might look like `{account:'user', password:'pwd', domain:'MYDOMAIN'}
       * If this is not included or does not have all 3 members set then it is not used.
       * - *workingdirectory* optional working directory that service should run in.
       * If this is not included, the current working directory of the install process
       * is used.
       */
      generateXml: function(config) {
        var xml;
        function multi(tag, input, splitter) {
          if (input === void 0 || input === null) {
            return;
          }
          if (!(input instanceof Array)) {
            input = input.split(splitter || ",");
          }
          input.forEach(function(val) {
            var ele = {};
            ele[tag] = String(val).trim();
            xml.push(ele);
          });
        }
        if (!config || !config.id || !config.name || !config.script) {
          throw "WINSW must be configured with a minimum of id, name and script";
        }
        xml = [
          { id: config.id },
          { name: config.name },
          { description: config.description || "" },
          { executable: config.execPath || process.execPath }
        ];
        multi("argument", config.nodeOptions, " ");
        xml.push({ argument: config.script.trim() });
        console.log({ loc: "winsw.js ~line 77", xml, config });
        multi("argument", config.wrapperArgs, " ");
        if (config.logging) {
          var logcontent = [{ _attr: { mode: config.logging.mode || "append" } }];
          if (config.logging.mode === "roll-by-time") {
            logcontent.push({ pattern: config.logging.pattern || "yyyMMdd" });
          }
          if (config.logging.mode === "roll-by-size") {
            logcontent.push({ sizeThreshold: config.logging.sizeThreshold || 10240 });
            logcontent.push({ keepFiles: config.logging.keepFiles || 8 });
          }
          xml.push({ log: logcontent });
        } else {
          xml.push({ logmode: config.logmode || "rotate" });
        }
        if (config.logpath) {
          xml.push({ logpath: config.logpath });
        }
        if (config.stopparentfirst) {
          xml.push({ stopparentprocessfirst: config.stopparentfirst });
        }
        if (config.stoptimeout) {
          xml.push({ stoptimeout: config.stoptimeout + "sec" });
        }
        multi("depend", config.dependencies);
        if (config.env) {
          config.env = config.env instanceof Array == true ? config.env : [config.env];
          config.env.forEach(function(env) {
            xml.push({ env: { _attr: { name: env.name, value: env.value } } });
          });
        }
        if (config.logOnAs) {
          var serviceaccount = [
            { domain: config.logOnAs.domain || "NT AUTHORITY" },
            { user: config.logOnAs.account || "LocalSystem" },
            { password: config.logOnAs.password || "" }
          ];
          if (config.allowServiceLogon) {
            serviceaccount.push({ allowservicelogon: "true" });
          }
          xml.push({
            serviceaccount
          });
        }
        xml.push({ workingdirectory: config.workingdirectory || process.cwd() });
        return require_xml()({ service: xml }, { indent: "	" }).replace(/\n/g, "\r\n");
      },
      /**
       * Copy install version of winsw.exe to specific renamed version according to
       * the service id. Also copy .exe.config file that allows it to run under
       * .NET 4+ runtime on newer versions of windows.
       * (see https://github.com/kohsuke/winsw#net-runtime-40)
       *
       * @method createExe
       * Create the executable
       * @param {String} name
       * The alphanumeric string (spaces are stripped) of the `.exe` file. For example, `My App` generates `myapp.exe`
       * @param {String} [dir=cwd]
       * The output directory where the executable will be saved.
       * @param {Function} [callback]
       * The callback to fire upon completion.
       */
      createExe: function(name, dir, callback2) {
        var fs = require("fs"), p = require("path");
        if (typeof dir === "function") {
          callback2 = dir;
          dir = null;
        }
        dir = dir || process.cwd();
        var exeOrigin = p.join(__dirname, "..", "bin", "winsw", "winsw.exe"), cfgOrigin = p.join(__dirname, "..", "bin", "winsw", "winsw.exe.config"), exeDest = p.join(dir, name.replace(/[^\w]/gi, "").toLowerCase() + ".exe"), cfgDest = p.join(dir, name.replace(/[^\w]/gi, "").toLowerCase() + ".exe.config"), exeData = fs.readFileSync(exeOrigin, { encoding: "binary" }), cfgData = fs.readFileSync(cfgOrigin, { encoding: "binary" });
        fs.writeFileSync(exeDest, exeData, { encoding: "binary" });
        fs.writeFileSync(cfgDest, cfgData, { encoding: "binary" });
        callback2 && callback2();
      }
    };
  }
});

// ../../node_modules/.pnpm/node-windows@1.0.0-beta.8/node_modules/node-windows/lib/daemon.js
var require_daemon = __commonJS({
  "../../node_modules/.pnpm/node-windows@1.0.0-beta.8/node_modules/node-windows/lib/daemon.js"(exports2, module2) {
    var exec = require("child_process").exec;
    var path = require("path");
    var fs = require("fs");
    var PermError = "Permission Denied. Requires administrative privileges.";
    var wincmd = require_binaries();
    var Logger = require_eventlog();
    var daemonDir = "daemon";
    var wrapper = path.resolve(path.join(__dirname, "./wrapper.js"));
    var sleep = function(period) {
      var st = (/* @__PURE__ */ new Date()).getTime();
      while ((/* @__PURE__ */ new Date()).getTime() <= st + period * 1e3) {
      }
      return;
    };
    var daemon = function(config) {
      Object.defineProperties(this, {
        _name: {
          enumerable: false,
          writable: true,
          configurable: false,
          value: config.name || null
        },
        _eventlog: {
          enumerable: false,
          writable: true,
          configurable: false,
          value: null
        },
        _xml: {
          enumerable: false,
          get: function() {
            var wrapperArgs = [
              "--file",
              this.script,
              "--scriptoptions=" + this.scriptOptions,
              "--log",
              this.name + " wrapper",
              "--grow",
              this.grow,
              "--wait",
              this.wait,
              "--maxrestarts",
              this.maxRestarts,
              "--abortonerror",
              this.abortOnError == true ? "y" : "n",
              "--stopparentfirst",
              this.stopparentfirst
            ];
            if (this.maxRetries !== null) {
              wrapperArgs.push("--maxretries");
              wrapperArgs.push(this.maxRetries);
            }
            return require_winsw().generateXml({
              name: this.name,
              id: this._exe,
              nodeOptions: this.nodeOptions,
              script: wrapper,
              scriptOptions: this.scriptOptions,
              wrapperArgs,
              description: this.description,
              logpath: this.logpath,
              env: config.env,
              execPath: this.execPath,
              logOnAs: this.logOnAs,
              workingdirectory: this.workingdirectory,
              stopparentfirst: this.stopparentfirst,
              stoptimeout: this.stoptimeout,
              logmode: this.logmode,
              logging: config.logging,
              allowServiceLogon: config.allowServiceLogon
            });
          }
        },
        _exe: {
          enumerable: false,
          get: function() {
            return this.id + ".exe";
          }
        },
        /**
         * @cfg {Number} [maxRetries=null]
         * The maximum number of restart attempts to make before the service is considered non-responsive/faulty.
         * Ignored by default.
         */
        maxRetries: {
          enumerable: true,
          writable: false,
          configurable: false,
          value: config.hasOwnProperty("maxRetries") ? config.maxRetries : null
        },
        /**
         * @cfg {Boolean} [stopparentfirst=false]
         * Allow the service to shutdown cleanly.
         */
        stopparentfirst: {
          enumerable: true,
          writable: false,
          configurable: false,
          value: config.stopparentfirst
        },
        /**
         * @cfg {Number} [stoptimeout=30]
         * How long to wait in seconds before force killing the application.
         * This only takes effect when stopparentfirst is enabled.
         */
        stoptimeout: {
          enumerable: true,
          writable: false,
          configurable: false,
          value: config.hasOwnProperty("stoptimeout") ? config.stoptimeout : 30
        },
        /**
         * @cfg {string} [nodeOptions='--harmony']
         * Options to be passed to the node process.
         */
        nodeOptions: {
          enumerable: true,
          writable: false,
          configurable: false,
          value: config.nodeOptions || "--harmony"
        },
        /**
        * @cfg {string} [scriptOptions='']
        * Options to be passed to the script.
        */
        scriptOptions: {
          enumerable: true,
          writable: false,
          configurable: false,
          value: config.scriptOptions || ""
        },
        /**
         * @cfg {Number} [maxRestarts=3]
         * The maximum number of restarts within a 60 second period before haulting the process.
         * This cannot be _disabled_, but it can be rendered ineffective by setting a value of `0`.
         */
        maxRestarts: {
          enumerable: true,
          writable: false,
          configurable: false,
          value: config.hasOwnProperty("maxRestarts") ? config.maxRestarts : 3
        },
        /**
         * @cfg {Boolean} [abortOnError=false]
         * Setting this to `true` will force the process to exit if it encounters an error that stops the node.js script from running.
         * This does not mean the process will stop if the script throws an error. It will only abort if the
         * script throws an error causing the process to exit (i.e. `process.exit(1)`).
         */
        abortOnError: {
          enumerable: true,
          writable: false,
          configurable: false,
          value: config.abortOnError instanceof Boolean ? config.abortOnError : false
        },
        /**
         * @cfg {Number} [wait=1]
         * The initial number of seconds to wait before attempting a restart (after the script stops).
         */
        wait: {
          enumerable: true,
          writable: false,
          configurable: false,
          value: !isNaN(config.wait) ? config.wait : 1
        },
        /**
         * @cfg {Number} [grow=.25]
         * A number between 0-1 representing the percentage growth rate for the #wait interval.
         * Setting this to anything other than `0` allows the process to increase it's wait period
         * on every restart attempt. If a process dies fatally, this will prevent the server from
         * restarting the process too rapidly (and too strenuously).
         */
        grow: {
          enumerable: true,
          writable: false,
          configurable: false,
          value: !isNaN(config.grow) ? config.grow : 0.25
        },
        _directory: {
          enumerable: false,
          writable: true,
          configurable: false,
          value: config.script !== null ? path.dirname(config.script) : null
        },
        /**
         * Resolves the directory where the script is saved.
         */
        directory: {
          enumerable: false,
          writable: false,
          configurable: false,
          value: function(dir) {
            if (this.script == null || this.name == null) {
              throw Error("Script and Name are required but were not provided.");
            }
            if (dir) {
              this._directory = path.resolve(dir);
            }
            return path.resolve(path.join(this._directory, daemonDir));
          }
        },
        /**
         * @property {String} root
         * The root directory where the process files are stored.
         */
        root: {
          enumerable: true,
          get: function() {
            return this.directory();
          }
        },
        // Generates the primary logging utility
        log: {
          enumerable: false,
          get: function() {
            if (this._eventlog !== null)
              return this._eventlog;
            if (this.name == null)
              throw "No name was specified for the service";
            this._eventlog = new Logger(this.name + " Monitor");
            return this._eventlog;
          }
        },
        // The path where log files should be stored
        logpath: {
          enumerable: true,
          writable: false,
          configurable: false,
          value: config.logpath || null
        },
        // The log mode. Options are the same as winsw#generateXml
        logmode: {
          enumerable: true,
          writable: false,
          configurable: false,
          value: config.logmode || "rotate"
        },
        // The name of the process
        name: {
          enumerable: false,
          get: function() {
            return this._name;
          },
          set: function(value) {
            this._name = value;
          }
        },
        // The ID for the process
        id: {
          enumerable: true,
          get: function() {
            return this.name.replace(/[^\w]/gi, "").toLowerCase();
          }
        },
        // Description of the service
        description: {
          enumerable: true,
          writable: false,
          configurable: false,
          value: config.description || ""
        },
        /**
         * @property {Object} [user]
         * If you need to specify a specific user or particular credentials to manage a service, the following
         * attributes may be helpful.
         *
         * The `user` attribute is an object with three keys: `domain`,`account`, and `password`.
         * This can be used to identify which user the service library should use to perform system commands.
         * By default, the domain is set to the local computer name, but it can be overridden with an Active Directory
         * or LDAP domain. For example:
         *
         * **app.js**
         *
         *     var Service = require('node-windows').Service;
         *
         *     // Create a new service object
         *     var svc = new Service({
         *       name:'Hello World',
         *       script: require('path').join(__dirname,'helloworld.js')
         *     });
         *
         *     svc.user.domain = 'mydomain.local';
         *     svc.user.account = 'username';
         *     svc.user.password = 'password';
         *     ...
         *
         * Both the account and password must be explicitly defined if you want the service module to
         * run commands as a specific user. By default, it will run using the user account that launched
         * the process (i.e. who launched `node app.js`).
         */
        user: {
          enumerable: false,
          writable: true,
          configurable: false,
          value: {
            account: null,
            password: null,
            domain: process.env.COMPUTERNAME
          }
        },
        /**
         * @property {Object} [logOnAs]
         * If you need to specify a specific user or particular credentials for the service log on as once installed, the following
         * attributes may be helpful.
         *
         * The `logOnAs` attribute is an object with four keys: `domain`,`account`, `password`, and `mungeCredentialsAfterInstall`.
         * This can be used to identify which user the service should run as once installed.
         *
         * If no account and password is specified, the logOnAs property is not used and the service will run as the "Local System" account.
         * If account and password is specified, but domain is not specified then the domain is set to the local computer name, but it can be overridden with an Active Directory
         * or LDAP domain. For example:
         *
         * **app.js**
         *
         *     var Service = require('node-windows').Service;
         *
         *     // Create a new service object
         *     var svc = new Service({
         *       name:'Hello World',
         *       script: require('path').join(__dirname,'helloworld.js')
         *     });
         *
         *     svc.logOnAs.domain = 'mydomain.local';
         *     svc.logOnAs.account = 'username';
         *     svc.logOnAs.password = 'password';
         *     ...
         *
         * Both the account and password must be explicitly defined if you want the service to log on as that user,
         * otherwise the Local System account will be used.
         */
        logOnAs: {
          enumerable: false,
          writable: true,
          configurable: false,
          value: {
            account: null,
            password: null,
            domain: process.env.COMPUTERNAME,
            mungeCredentialsAfterInstall: true
          }
        },
        /**
         * @property {String} [workingdirectory]
         * The full path to the working directory that the service process
         * should launch from. If this is omitted, it will default to the
         * current processes working directory.
         */
        workingdirectory: {
          enumerable: false,
          writable: true,
          configurable: false,
          value: config.hasOwnProperty("workingDirectory") ? config.workingDirectory : process.cwd()
        },
        // Optionally provide a sudo password.
        sudo: {
          enumerable: false,
          writable: true,
          configurable: false,
          value: {
            password: null
          }
        },
        /**
         * @cfg {String} script
         * The absolute path of the script to launch as a service.
         * @required
         */
        script: {
          enumerable: true,
          writable: true,
          configurable: false,
          value: config.script !== void 0 ? require("path").resolve(config.script) : null
        },
        /**
         * @cfg {String} execPath
         * The absolute path to the executable that will launch the script.
         * If omitted process.execPath is used.
         */
        execPath: {
          enumerable: true,
          writable: true,
          configurable: false,
          value: config.execPath !== void 0 ? require("path").resolve(config.execPath) : null
        },
        /**
         * @method install
         * Install the script as a process.
         * @param {String} [dir=root of script]
         * The directory where the process files will be saved. Defaults to #script path.
         * @param {Function} [callback]
         * The callback to fire when the installation completes.
         */
        /**
         * @event install
         * Fired when the installation process is complete.
         */
        /**
         * @event alreadyinstalled
         * Fired if the script is already known to be a service.
         */
        /**
         * @event invalidinstallation
         * Fired if an installation is detected but missing required files.
         */
        /**
         * @event error
         * Fired in some instances when an error occurs.
         */
        install: {
          enumerable: true,
          writable: false,
          configurable: false,
          value: function(dir) {
            if (this.script == null || this.name == null) {
              throw Error("Script and Name are required but were not provided.");
            }
            if (this.exists) {
              var missing = false;
              if (!fs.existsSync(path.join(this.root, this._exe))) {
                this.log.warn("The main executable is missing or cannot be found (" + path.join(this.root, this._exe) + ")");
                missing = true;
              }
              if (!fs.existsSync(path.join(this.root, this.id + ".xml"))) {
                this.log.warn("The primary configuration file is missing or cannot be found (" + path.join(this.root, this.id + ".xml") + ")");
                missing = true;
              }
              if (missing.length > 0) {
                this.emit("invalidinstallation");
                return;
              }
              this.log.warn("The process cannot be installed again because it already exists.");
              this.emit("alreadyinstalled");
              return;
            }
            var winsw = require_winsw(), me = this;
            if (typeof dir === "function") {
              callback = dir;
              dir = null;
            }
            dir = this.directory(dir);
            fs.exists(dir, function(exists) {
              if (!exists) {
                fs.mkdirSync(dir);
              }
              fs.writeFile(path.resolve(dir, me.id + ".xml"), me._xml, function() {
                winsw.createExe(me.id, dir, function() {
                  me.execute('"' + path.resolve(dir, me._exe) + '" install', function() {
                    sleep(2);
                    me.emit("install");
                  });
                });
              });
            });
          }
        },
        /**
         * @method uninstall
         * Uninstall the service.
         * @param {Number} [waitTime]
         * Seconds to wait until winsw.exe finish processing the uninstall command.
         *
         *      var Service = require('node-windows').Service;
         *
         *      // Create a new service object
         *      var svc = new Service({
         *        name:'Hello World',
         *        script: require('path').join(__dirname,'helloworld.js')
         *      });
         *
         *      // Listen for the "uninstall" event so we know when it's done.
         *      svc.on('uninstall',function(){
         *        console.log('Uninstall complete.');
         *        console.log('The service exists: ',svc.exists);
         *      });
         *
         *      // Uninstall the service.
         *      svc.uninstall();
         */
        /**
         * @event uninstall
         * Fired when the uninstall is complete.
         */
        /**
         * @event alreadyuninstalled
         * Fired if the script is unknown as a service.
         */
        uninstall: {
          enumerable: true,
          writable: false,
          value: function(waitTime) {
            var me = this;
            waitTime = waitTime || 2;
            if (!this.exists) {
              console.log("Uninstall was skipped because process does not exist or could not be found.");
              this.emit("alreadyuninstalled");
              return;
            }
            var uninstaller = function() {
              me.execute('"' + path.resolve(me.root, me._exe) + '" uninstall', function(error, stdout, stderr) {
                if (error) {
                  me.checkPermError(error);
                } else if (stderr.trim().length > 0) {
                  console.log("Error: ", stderr);
                } else {
                  sleep(waitTime);
                  var rm = function(file) {
                    if (fs.existsSync(path.join(me.root, file))) {
                      fs.unlinkSync(path.join(me.root, file));
                    }
                  };
                  rm(me.id + ".xml");
                  rm(me.id + ".wrapper.log");
                  rm(me.id + ".out.log");
                  rm(me.id + ".err.log");
                  rm(me.id + ".exe");
                  rm(me.id + ".exe.config");
                  var _other_files = fs.readdirSync(me.root).filter(function(file) {
                    const regex = /^.+\.((wrapper|out|err)\.log)|(exe|xml)$/g;
                    return !regex.exec(file);
                  });
                  _other_files.forEach(function(f) {
                    rm(f);
                  });
                  if (fs.readdirSync(me.root).length === 0) {
                    if (me.root !== path.dirname(me.script)) {
                      fs.rmdir(me.root, function() {
                        sleep(1);
                        me.emit("uninstall");
                      });
                    } else {
                      me.emit("uninstall");
                    }
                  } else {
                    me.emit("uninstall");
                  }
                }
              });
            };
            this.once("stop", uninstaller);
            this.once("alreadystopped", uninstaller);
            this.stop();
          }
        },
        /**
         * @method start
         * Start an existing method.
         */
        /**
         * @event start
         * Fired when the event has started.
         */
        start: {
          enumerable: true,
          writable: false,
          configurable: false,
          value: function() {
            var me = this;
            if (this.name == null) {
              throw "A name for the service is required.";
            }
            if (!this.exists) {
              throw Error('The service "' + this.name + '" does not exist or could not be found.');
            }
            this.execute('NET START "' + me._exe + '"', function(err, stdout, stderr) {
              if (err) {
                if (err.code == 2) {
                  if (err.message.indexOf("already been started") >= 0 && err.message.indexOf("service name is invalid") < 0) {
                    me.log.warn("An attempt to start the service failed because the service is already running. The process should be stopped before starting, or the restart method should be used.");
                    me.emit("error", err);
                    return;
                  } else if (err.message.indexOf("service name is invalid") < 0) {
                    me.checkPermError(err);
                    console.log(err);
                    me.emit("error", err);
                    return;
                  }
                } else {
                  me.log.error(err.toString());
                }
              } else {
                me.emit("start");
              }
            });
          }
        },
        /**
         * @method stop
         * Stop the service.
         */
        /**
         * @event stop
         * Fired when the service is stopped.
         */
        stop: {
          enumerable: true,
          writable: false,
          value: function() {
            var me = this;
            me.execute('NET STOP "' + me._exe + '"', function(err, stdout, stderr) {
              if (err) {
                if (err.code == 2) {
                  me.log.warn("An attempt to stop the service failed because the service is/was not running.");
                  me.emit("alreadystopped");
                } else {
                  me.checkPermError(err);
                }
              } else {
                me.log.info(stdout);
                me.emit("stop");
              }
            });
          }
        },
        /**
         * @method restart
         * Restart an existing service
         */
        restart: {
          enumerable: true,
          writable: false,
          value: function(callback2) {
            var me = this;
            this.once("stop", me.start);
            this.stop();
          }
        },
        /**
         * @property {Boolean} exists
         * Determine whether the service exists.
         */
        exists: {
          enumerable: true,
          get: function() {
            if (this.script == null || this.name == null) {
              throw Error("Script and name are required but were not specified.");
            }
            return fs.existsSync(path.join(this.directory(), this.id + ".exe")) && fs.existsSync(path.join(this.directory(), this.id + ".xml"));
          }
        },
        // Execute commands with elevated privileges.
        execute: {
          enumerable: false,
          writable: false,
          configurable: false,
          value: function(cmd, options, callback2) {
            var me = this;
            callback2 = callback2 || function() {
            };
            options = options || {};
            wincmd.isAdminUser(function(isAdmin) {
              if (isAdmin) {
                if (typeof options === "function") {
                  callback2 = options;
                  options = {};
                }
                if (me.user.account !== null && me.user.password !== null) {
                  _cmd = "runas /profile /user:" + me.user.domain + "\\" + me.user.account + " " + cmd;
                  exec(cmd, options, callback2);
                } else if (me.sudo.password !== null) {
                  wincmd.sudo(cmd, me.sudo.password || "", options, callback2);
                } else {
                  wincmd.elevate(cmd, options, callback2);
                }
              } else {
                console.log(PermError);
                throw PermError;
              }
            });
          }
        },
        // Check for permission errors
        checkPermError: {
          enumerable: false,
          writable: false,
          configurable: false,
          value: function(error) {
            if (error.message.indexOf("Administrator access") >= 0 || error.message.indexOf("Access is denied") >= 0) {
              try {
                this.log.error(PermError);
              } catch (e) {
                console.log(PermError);
              }
            } else {
              try {
                this.log.error(error.toString());
              } catch (e) {
                console.log(error.toString());
              }
            }
            process.exit(1);
          }
        }
      });
    };
    var util = require("util");
    var EventEmitter = require("events").EventEmitter;
    util.inherits(daemon, EventEmitter);
    module2.exports = daemon;
  }
});

// ../../node_modules/.pnpm/node-windows@1.0.0-beta.8/node_modules/node-windows/lib/node-windows.js
var require_node_windows = __commonJS({
  "../../node_modules/.pnpm/node-windows@1.0.0-beta.8/node_modules/node-windows/lib/node-windows.js"(exports2, module2) {
    if (require("os").platform().indexOf("win32") < 0) {
      throw "node-windows is only supported on Windows.";
    }
    module2.exports = require_binaries();
    var commands = require_cmd();
    for (item in commands) {
      module2.exports[item] = commands[item];
    }
    var item;
    module2.exports.Service = require_daemon();
    module2.exports.EventLogger = require_eventlog();
  }
});

// src/service/window-service.ts
var import_node_fs = require("node:fs");
var import_node_path = require("node:path");
var import_node_url = require("node:url");
var import_node_windows = __toESM(require_node_windows());
var log = new import_node_windows.EventLogger({
  source: "PMD-TUNNEL"
});
if (!(0, import_node_fs.existsSync)((0, import_node_path.join)(process.env.PROGRAMDATA || "C:\\ProgramData", "PMD-TUNNEL", "logs"))) {
  (0, import_node_fs.mkdirSync)((0, import_node_path.join)(process.env.PROGRAMDATA || "C:\\ProgramData", "PMD-TUNNEL", "logs"), {
    recursive: true
  });
}
var svc = new import_node_windows.Service({
  name: "PMD-TUNNEL",
  description: "Pythonmobiledevice3 tunnel",
  script: (0, import_node_path.join)((0, import_node_path.dirname)((0, import_node_url.fileURLToPath)(__importMetaUrl)), "tunnel.js"),
  logpath: (0, import_node_path.join)(process.env.PROGRAMDATA || "C:\\ProgramData", "PMD-TUNNEL", "logs"),
  wait: 5,
  grow: 5,
  maxRetries: 10,
  env: [
    {
      name: "PMD_CLI_PATH",
      value: process.env.PMD_CLI_PATH ?? "pymobiledevice3.exe"
    }
  ]
});
svc.on("install", () => {
  svc.start();
  log.info("Service installed and started!");
  console.log("Service installed and started!");
});
svc.on("uninstall", () => {
  log.info("Service uninstalled!");
  console.log("Service uninstalled!");
});
svc.on("error", (err) => {
  log.error(`Service error: ${err}`);
  console.log(`Service error: ${err}`);
});
svc.on("start", () => {
  log.info("Service started!");
  console.log("Service started!");
});
svc.on("stop", () => {
  log.info("Service stopped!");
});
if (process.argv.includes("-U")) {
  svc.uninstall();
} else {
  svc.install();
}
//# sourceMappingURL=window-service.js.map
