// @bun
import {
  getPreferredUserConfigFile,
  init_redscopeCompat,
  init_slowOperations,
  jsonParse,
  jsonStringify
} from "./chunk-s3hafnk3.js";
import"./chunk-kb3758f7.js";
import"./chunk-9h9k5vz3.js";
import"./chunk-xmpgmeb8.js";
import"./chunk-2kz09j2s.js";
import"./chunk-c0k7b0jw.js";
import"./chunk-hhsxm2yr.js";

// src/server/lockfile.ts
init_redscopeCompat();
init_slowOperations();
import { mkdir, readFile, rm, writeFile } from "fs/promises";
import { dirname } from "path";
var LOCK_FILE = "server-lock.json";
function getServerLockPath() {
  return getPreferredUserConfigFile(LOCK_FILE);
}
function isRecord(value) {
  return typeof value === "object" && value !== null;
}
function parseLock(value) {
  if (!isRecord(value))
    return null;
  if (typeof value.pid !== "number" || typeof value.port !== "number" || typeof value.host !== "string" || typeof value.httpUrl !== "string" || typeof value.startedAt !== "number") {
    return null;
  }
  return {
    pid: value.pid,
    port: value.port,
    host: value.host,
    httpUrl: value.httpUrl,
    startedAt: value.startedAt
  };
}
function isPidAlive(pid) {
  try {
    process.kill(pid, 0);
    return true;
  } catch (error) {
    return isRecord(error) && (error.code === "EPERM" || error.code === "EACCES");
  }
}
async function healthCheck(httpUrl) {
  if (!httpUrl.startsWith("http://") && !httpUrl.startsWith("https://")) {
    return true;
  }
  try {
    const response = await fetch(`${httpUrl.replace(/\/$/, "")}/health`, {
      signal: AbortSignal.timeout(750)
    });
    return response.ok;
  } catch {
    return false;
  }
}
async function writeServerLock(info) {
  const lockPath = getServerLockPath();
  await mkdir(dirname(lockPath), { recursive: true });
  await writeFile(lockPath, `${jsonStringify(info)}
`, "utf8");
}
async function removeServerLock() {
  await rm(getServerLockPath(), { force: true });
}
async function probeRunningServer() {
  const lockPath = getServerLockPath();
  let lock = null;
  try {
    lock = parseLock(jsonParse(await readFile(lockPath, "utf8")));
  } catch {
    return null;
  }
  if (!lock) {
    await removeServerLock();
    return null;
  }
  if (!isPidAlive(lock.pid) || !await healthCheck(lock.httpUrl)) {
    await removeServerLock();
    return null;
  }
  return lock;
}
export {
  writeServerLock,
  removeServerLock,
  probeRunningServer
};
