#!/usr/bin/env node
import {
  daemonRelayArgs
} from "./chunk-3HJM2NFD.js";
import {
  spawnScript
} from "./chunk-IHUQNJF6.js";
import {
  createIpcReader
} from "./chunk-IHIFDLM4.js";
import {
  terminalLogger
} from "./chunk-LWDOXOWY.js";
import {
  PROFILE_NAME,
  SERVICE_LOG_PATH,
  SOCK_PATH,
  STOPPED_PATH
} from "./chunk-7RSBFN2G.js";

// src/terminal/serve-bootstrap.ts
import { connect } from "net";
import { existsSync, unlinkSync } from "fs";
import { setTimeout as sleep } from "timers/promises";
var ENSURE_SERVICE_MAX_RETRIES = 20;
var ENSURE_SERVICE_INITIAL_DELAY_MS = 100;
var ENSURE_SERVICE_MAX_DELAY_MS = 2e3;
var WAIT_FOR_MESSAGE_TIMEOUT_MS = 1e4;
function tryConnect(sockPath) {
  return new Promise((resolve) => {
    const s = connect(sockPath);
    s.on("connect", () => resolve(s));
    s.on("error", () => resolve(null));
  });
}
async function ensureService(autoStart = true) {
  const existing = await tryConnect(SOCK_PATH);
  if (existing) {
    terminalLogger.info("Connected to existing service");
    return existing;
  }
  if (!autoStart) throw new Error("Service is not running");
  if (existsSync(STOPPED_PATH)) unlinkSync(STOPPED_PATH);
  terminalLogger.info("Auto-starting serve daemon");
  const child = spawnScript("serve", ["--profile", PROFILE_NAME, ...daemonRelayArgs()], {
    env: { ...process.env },
    logger: terminalLogger
  });
  let childFailed = false;
  let exitCode = null;
  let exitSignal = null;
  let spawnError = null;
  child.once("exit", (code, signal) => {
    childFailed = true;
    exitCode = code;
    exitSignal = signal;
  });
  child.once("error", (err) => {
    childFailed = true;
    spawnError = err;
  });
  for (let i = 0; i < ENSURE_SERVICE_MAX_RETRIES; i++) {
    const delay = Math.min(ENSURE_SERVICE_INITIAL_DELAY_MS * (i + 1), ENSURE_SERVICE_MAX_DELAY_MS);
    await sleep(delay);
    if (childFailed) {
      terminalLogger.error(
        { code: exitCode, signal: exitSignal, err: spawnError && String(spawnError) },
        "Serve daemon failed to start"
      );
      const detail = spawnError ? `spawn error=${String(spawnError)}` : `code=${exitCode}, signal=${exitSignal}`;
      throw new Error(
        `Serve daemon failed to start (${detail}). Check ${SERVICE_LOG_PATH} for details.`
      );
    }
    const socket = await tryConnect(SOCK_PATH);
    if (socket) {
      terminalLogger.info({ attempt: i + 1 }, "Connected to service after retry");
      return socket;
    }
  }
  terminalLogger.error({ maxRetries: ENSURE_SERVICE_MAX_RETRIES }, "Failed to connect to service");
  throw new Error(
    `Failed to connect to dev-anywhere service after ${ENSURE_SERVICE_MAX_RETRIES} retries. Check ${SERVICE_LOG_PATH} for details.`
  );
}
function waitForMessage(socket, messageType) {
  return new Promise((resolve, reject) => {
    let timeout = null;
    const dispose = createIpcReader(socket, (msg) => {
      if (msg.type === messageType) {
        if (timeout) clearTimeout(timeout);
        dispose();
        resolve(msg);
      }
    });
    timeout = setTimeout(() => {
      dispose();
      reject(new Error(`Timeout waiting for ${messageType}`));
    }, WAIT_FOR_MESSAGE_TIMEOUT_MS);
  });
}

// src/terminal/serve-socket-swap.ts
function swapServeSocket(prev, next) {
  prev.removeAllListeners();
  return next;
}

export {
  tryConnect,
  ensureService,
  waitForMessage,
  swapServeSocket
};
//# sourceMappingURL=chunk-55PSMIVK.js.map