"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 __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var child_wrapper_exports = {};
__export(child_wrapper_exports, {
  ChildProcessWrapper: () => ChildProcessWrapper
});
module.exports = __toCommonJS(child_wrapper_exports);
var childProcess = __toESM(require("child_process"));
var import_child_entrypoint = require("./child-entrypoint");
var import_config = require("./config");
var import_is_child = require("./is-child");
const SPAWN_SHELL_ENV = {
  FORCE_COLOR: "true"
  // well-known env var used by most shells to enable color output in child processes
};
const listenForChildSpawn = (child, logger) => new Promise((resolve, reject) => {
  child.on("spawn", () => {
    logger.debug(`Child process spawned with pid ${child.pid}`);
    resolve();
  });
  child.on("error", (err) => {
    logger.debug(`Child process error: ${err.message}`);
    reject(err);
  });
});
const listenForChildExit = (child, logger) => new Promise((resolve, reject) => {
  child.on("disconnect", () => {
    logger.debug("Child process disconnected");
  });
  child.on("close", (exitCode, signal) => {
    logger.debug(`Child process closed with code ${exitCode} and signal ${signal}`);
  });
  child.on("exit", (exitCode, signal) => {
    logger.debug(`Child process exited with code ${exitCode} and signal ${signal}`);
    resolve({ exitCode, signal });
  });
  child.on("error", (err) => {
    logger.debug(`Child process error: ${err.message}`);
    reject(err);
  });
  child.on("message", (message) => {
    logger.debug(`Child process message: ${message}`);
  });
});
class ChildProcessWrapper {
  constructor(_child, _exitPromise) {
    this._child = _child;
    this._exitPromise = _exitPromise;
  }
  static async spawn(config, logger) {
    if (import_is_child.isChildProcess) {
      throw new Error("Cannot spawn child process from child process");
    }
    const child = childProcess.fork(import_child_entrypoint.ENTRY_POINT, [], {
      stdio: "inherit",
      env: {
        ...SPAWN_SHELL_ENV,
        [import_is_child.CHILD_ENV_KEY]: import_is_child.CHILD_ENV_VALUE,
        [import_config.CONFIG_ENV_KEY]: JSON.stringify(config),
        ...config.env
      }
    });
    const childSpawnPromise = listenForChildSpawn(child, logger);
    const childExitPromise = listenForChildExit(child, logger);
    const instance = new ChildProcessWrapper(child, childExitPromise);
    void childExitPromise.finally(() => {
      instance._exited = true;
    });
    await childSpawnPromise;
    return instance;
  }
  _exited = false;
  async kill() {
    if (this._exited) {
      throw new Error("Child process already exited and cannot be killed");
    }
    this._child.kill();
    const res = await this._exitPromise;
    return res;
  }
  async listen() {
    if (this._exited) {
      throw new Error("Child process already exited and cannot be listened on");
    }
    const res = await this._exitPromise;
    return res;
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  ChildProcessWrapper
});
//# sourceMappingURL=child-wrapper.js.map
