"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true,
});
exports.unstable_spawnDebuggerShellWithArgs =
  unstable_spawnDebuggerShellWithArgs;
const { spawn } = require("cross-spawn");
async function unstable_spawnDebuggerShellWithArgs(
  args,
  { mode = "detached" } = {},
) {
  const electronPath = require("electron");
  return new Promise((resolve, reject) => {
    const child = spawn(
      electronPath,
      [require.resolve("../electron"), ...args],
      {
        stdio: "inherit",
        windowsHide: true,
        detached: mode === "detached",
      },
    );
    if (mode === "detached") {
      child.on("spawn", () => {
        resolve();
      });
      child.on("close", (code) => {
        if (code !== 0) {
          reject(
            new Error(
              `Failed to open debugger shell: ${electronPath} exited with code ${code}`,
            ),
          );
        }
      });
      child.unref();
    } else if (mode === "syncThenExit") {
      child.on("close", function (code, signal) {
        if (code === null) {
          console.error(electronPath, "exited with signal", signal);
          process.exit(1);
        }
        process.exit(code);
      });
      const handleTerminationSignal = function (signal) {
        process.on(signal, function signalHandler() {
          if (!child.killed) {
            child.kill(signal);
          }
        });
      };
      handleTerminationSignal("SIGINT");
      handleTerminationSignal("SIGTERM");
    }
  });
}
