#!/usr/bin/env node

// src/common/env.ts
import { spawn } from "child_process";
import { fileURLToPath } from "url";
var IS_DEV = false;
function resolveTopLevelScript(name) {
  const baseDir = IS_DEV ? new URL("../", import.meta.url) : new URL("./", import.meta.url);
  return new URL(name, baseDir);
}
function spawnScript(script, args = [], options = {}) {
  const { unref = true, logger, ...rest } = options;
  const stdio = rest.stdio ?? (logger ? ["ignore", "ignore", "pipe"] : "ignore");
  const scriptBaseUrl = typeof script === "string" ? resolveTopLevelScript(script) : script;
  const basePath = fileURLToPath(scriptBaseUrl);
  const scriptPath = `${basePath}${IS_DEV ? ".ts" : ".js"}`;
  const runtimeArgs = IS_DEV ? ["--import", "tsx", scriptPath, ...args] : [scriptPath, ...args];
  const child = spawn(process.execPath, runtimeArgs, {
    detached: true,
    ...rest,
    stdio
  });
  if (logger) {
    if (child.stderr) {
      child.stderr.setEncoding("utf-8");
      let buf = "";
      const emit = (line) => {
        const trimmed = line.trim();
        if (trimmed) logger.warn({ pid: child.pid, src: "child-stderr" }, trimmed);
      };
      child.stderr.on("data", (chunk) => {
        buf += chunk;
        const lines = buf.split("\n");
        buf = lines.pop() ?? "";
        for (const line of lines) emit(line);
      });
      child.stderr.on("end", () => {
        if (buf) {
          emit(buf);
          buf = "";
        }
      });
    }
    child.once("error", (err) => {
      logger.error({ pid: child.pid, err: String(err) }, "spawn failed");
    });
    child.once("exit", (code, signal) => {
      if (code !== 0 && code !== null) {
        logger.error({ pid: child.pid, code, signal }, "child exited abnormally");
      }
    });
  }
  if (unref) child.unref();
  return child;
}

export {
  spawnScript
};
//# sourceMappingURL=chunk-IHUQNJF6.js.map