import path from 'node:path';
import { stat, readFile, writeFile, readdir } from 'node:fs/promises';
import { e as error, j as json, t as text } from './index-Djsj11qr.js';
import { glob } from 'glob';
import fs from 'node:fs';

const legacyPath = "src/bosun/workflows.ts";
async function getRootPath() {
  const warnings = [];
  let projectRoot;
  if (process.env.BOSUN_NPX_RUN === "true") {
    if (fs.existsSync(path.join(process.cwd(), "package.json"))) {
      projectRoot = path.join(process.cwd(), "package.json");
    }
  } else {
    warnings.push(
      "Run Bosun from your project folder.\n `projects` folder inside Bosun is deprecated, only first project is loaded!"
    );
    const projectFiles = await glob(`projects/*/package.json`, { absolute: true });
    projectRoot = projectFiles[0];
  }
  if (!projectRoot) {
    throw new Error("Cannot find project root directory or package.json in it.");
  }
  const pkg = JSON.parse(fs.readFileSync(projectRoot, "utf-8"));
  let bosunRoot = pkg?.bosun?.root;
  if (!bosunRoot) {
    warnings.push(
      `Specify \`bosun.root\` in your \`package.json\`.
Running with legacy path: \`${legacyPath}\` which is deprecated!`
    );
    bosunRoot = legacyPath;
  }
  if (warnings.length) {
    printWarnings(warnings);
  }
  return path.resolve(path.dirname(projectRoot), bosunRoot);
}
function printWarnings(warnings) {
  if (warnings.length === 0) return;
  const length = 100;
  const orange = "\x1B[91m";
  const reset = "\x1B[0m";
  const header = "WARNING";
  console.log(`${orange}┌─ ${header} ${"─".repeat(length - header.length - 3)}┐${reset}`);
  for (const warning of warnings) {
    const lines = warning.split("\n");
    for (let i = 0; i < lines.length; i++) {
      const prefix = i === 0 ? "• " : "  ";
      console.log(`${orange}│ ${prefix}${lines[i].padEnd(length - 4)} │${reset}`);
    }
  }
  console.log(`${orange}└${"─".repeat(length)}┘${reset}`);
}
function assertUnderRoot(root, candidate) {
  const normalizedRoot = path.resolve(root) + path.sep;
  const normalized = path.resolve(candidate);
  if (!normalized.startsWith(normalizedRoot)) {
    throw error(400, "Path traversal is not allowed");
  }
}
async function buildTree(root, rel = "") {
  const abs = path.resolve(root, rel);
  const st = await stat(abs);
  const node = {
    name: rel ? path.basename(rel) : path.basename(root),
    path: rel,
    type: st.isDirectory() ? "dir" : "file"
  };
  if (st.isDirectory()) {
    const entries = await readdir(abs, { withFileTypes: true });
    const children = [];
    for (const ent of entries) {
      if (ent.name.startsWith(".")) continue;
      const childRel = path.posix.join(rel || "", ent.name);
      const childAbs = path.resolve(root, childRel);
      const childStat = await stat(childAbs);
      const child = {
        name: ent.name,
        path: childRel,
        type: childStat.isDirectory() ? "dir" : "file"
      };
      if (child.type === "dir") {
        child.children = await buildTree(root, childRel).then((d) => d.children ?? []);
      }
      children.push(child);
    }
    children.sort((a, b) => {
      if (a.type !== b.type) return a.type === "dir" ? -1 : 1;
      return a.name.localeCompare(b.name);
    });
    node.children = children;
  }
  return node;
}
const GET = async ({ url, request }) => {
  const project = url.searchParams.get("project");
  const pathParam = url.searchParams.get("path");
  const wantTree = url.searchParams.get("tree") === "1";
  if (!project) {
    throw error(400, "Missing project");
  }
  const root = path.dirname(await getRootPath());
  console.log("[files][GET]", {
    project,
    pathParam,
    wantTree,
    origin: request.headers.get("origin") ?? null,
    contentType: request.headers.get("content-type") ?? null
  });
  if (wantTree) {
    try {
      const st = await stat(root);
      if (!st.isDirectory()) throw new Error("Agents folder not found");
    } catch (e) {
      throw error(404, `Agents folder not found: ${root}`);
    }
    const tree = await buildTree(root);
    return json({ root, tree });
  }
  if (!pathParam) {
    throw error(400, "Missing path for file read");
  }
  const abs = path.resolve(root, pathParam);
  assertUnderRoot(root, abs);
  try {
    const st = await stat(abs);
    if (st.isDirectory()) {
      const node = await buildTree(abs);
      return json({ node });
    }
    const content = await readFile(abs, "utf-8");
    return json({ content });
  } catch (e) {
    throw error(404, e?.message || "Not found");
  }
};
const PUT = async ({ url, request }) => {
  const project = url.searchParams.get("project");
  const pathParam = url.searchParams.get("path");
  if (!project || !pathParam) {
    throw error(400, "Missing project or path");
  }
  const root = path.dirname(await getRootPath());
  const abs = path.resolve(root, pathParam);
  assertUnderRoot(root, abs);
  const contentType = request.headers.get("content-type") || "";
  console.log("[files][PUT]", {
    project,
    pathParam,
    origin: request.headers.get("origin") ?? null,
    contentType
  });
  let content;
  if (contentType.includes("application/json")) {
    const body = await request.json();
    content = body?.content ?? "";
  } else {
    content = await request.text();
  }
  await writeFile(abs, content, "utf-8");
  return text("OK");
};

export { GET, PUT };
//# sourceMappingURL=_server.ts-DLCS1Ypt.js.map
