import { c as defineEventHandler, r as readBody } from '../../_/nitro.mjs';
import { g as getVaxlaConfig, e as execCommandPromise, a as getUserRootDirectory } from '../../_/index.mjs';
import { a as activeProcesses } from '../../_/cli.mjs';
import { u as useServerEvents } from '../../_/useServerEvents.mjs';
import 'node:http';
import 'node:https';
import 'node:events';
import 'node:buffer';
import 'node:fs';
import 'node:path';
import 'node:crypto';
import 'node:url';
import 'jiti';
import 'find-up';
import 'tree-kill';
import 'node:child_process';
import '@lydell/node-pty';
import 'fs';
import 'path';
import 'node:module';

const getCommandDisplayName = (options) => {
  if ("dynamic" in options) {
    if (typeof options.dynamic === "object" && "command" in options.dynamic) return getCommandDisplayName({ script: options.dynamic });
    else return getCommandDisplayName({ command: options.dynamic });
  }
  if ("script" in options && options.script.label) return options.script.label;
  const command = "command" in options ? options.command : options.script?.command;
  if (typeof command === "object") {
    if ("npm" in command) return command.npm;
    else if ("shell" in command) return command.shell;
    else return "Custom Function";
  } else return command ?? "Custom Function";
};
const getCommandShellScript = (options, packagePath) => {
  if ("dynamic" in options) {
    if (typeof options.dynamic === "object" && "command" in options.dynamic) return getCommandShellScript({ script: options.dynamic }, packagePath);
    else return getCommandShellScript({ command: options.dynamic }, packagePath);
  }
  const command = "command" in options ? options.command : options.script?.command;
  let shellCommand = "";
  if (typeof command === "object") {
    if ("package" in command && command.package === true) {
      shellCommand += `cd ${packagePath} && `;
    }
    if ("npm" in command) shellCommand += `npm run ${command.npm}`;
    else if ("shell" in command) shellCommand += command.shell;
    else shellCommand += "::custom_function::";
  } else if (typeof command === "string") shellCommand += command;
  else shellCommand += "::custom_function::";
  return shellCommand;
};

var ScriptStatus = /* @__PURE__ */ ((ScriptStatus2) => {
  ScriptStatus2["Closed"] = "closed";
  ScriptStatus2["Opened"] = "opened";
  return ScriptStatus2;
})(ScriptStatus || {});

const runScript_post = defineEventHandler(async (event) => {
  var _a, _b;
  const body = await readBody(event);
  const { send } = useServerEvents();
  const configPath = process.env.VAXLA_CONFIG;
  const config = typeof configPath === "string" ? await getVaxlaConfig(configPath) : {};
  const commandId = "commandId" in body ? body.commandId : void 0;
  const packageId = "packageId" in body ? body.packageId : void 0;
  const packageInfo = packageId ? config.packages[packageId] : void 0;
  const command = "commandId" in body ? packageInfo == null ? void 0 : packageInfo.scripts[body.commandId].command : body.command;
  let commandShell = command ? getCommandShellScript({ dynamic: command }, (_a = packageInfo == null ? void 0 : packageInfo.path) != null ? _a : "") : "";
  const commandName = command ? getCommandDisplayName({ dynamic: command }) : "";
  const startMessage = (message) => {
    send({
      data: {
        id: body.id,
        message: [
          `\x1B[1m| ${message}`,
          `\x1B[36;1mDate    \x1B[0m\x1B[36m${(/* @__PURE__ */ new Date()).toISOString()}`,
          `\x1B[36;1mOptions \x1B[0m\x1B[36m${commandName}`,
          `\x1B[36;1mShell   \x1B[0m\x1B[36m${commandShell}`
        ].join("\n"),
        status: ScriptStatus.Opened
      }
    });
  };
  if (typeof command === "object" && "fn" in command && command.fn instanceof Function) {
    commandShell = `@vaxla/cli run ${packageId} ${commandId}`;
  }
  if (activeProcesses[body.id]) {
    startMessage("Sending Command");
    activeProcesses[body.id].send(commandShell);
  } else {
    startMessage("Executing Script");
    await execCommandPromise(commandShell, {
      cwd: getUserRootDirectory(),
      interactiveTerminal: (_b = body.interactiveTerminal) != null ? _b : false,
      onLog: (msg) => send({ data: { id: body.id, message: msg, type: "log" } }),
      onError: (msg) => send({ data: { id: body.id, message: msg, type: "error" } }),
      onChildProcessInit: (childProcess) => activeProcesses[body.id] = childProcess
    });
    send({
      data: {
        id: body.id,
        message: "\x1B[1m| Script Killed",
        status: ScriptStatus.Closed,
        type: "meta"
      }
    });
  }
  return {};
});

export { runScript_post as default };
//# sourceMappingURL=run-script.post.mjs.map
