if (typeof process === 'object' && process !== null &&
    process.env !== null && typeof process.env === 'object') {
  process.env.DD_GIT_REPOSITORY_URL = 'https://token@github.com/superblocksteam/superblocks.git';
  process.env.DD_GIT_COMMIT_SHA = '71329cb2a26133447acee36261ec5a5145024e84';
}
import { createRequire as $dd_createRequire } from 'module';
import { fileURLToPath as $dd_fileURLToPath } from 'url';
import { dirname as $dd_dirname } from 'path';
globalThis.require ??= $dd_createRequire(import.meta.url);
globalThis.__filename ??= $dd_fileURLToPath(import.meta.url);
globalThis.__dirname ??= $dd_dirname(globalThis.__filename);

import {
  buildToolRegistry,
  executeToolCall,
  handleJsonRpc,
  invalidRequestResponse,
  isJsonRpcRequest,
  package_default,
  resolveProfile,
  toolDefinitions
} from "./chunk-PLP3G6ND.js";
import "./chunk-XDMREZWP.js";
import "./chunk-XT6CAJBF.js";
import "./chunk-DNVZMNUA.js";
import "./chunk-3NCJL5MI.js";
import "./chunk-5NY4M3GG.js";
import "./chunk-CXIPLZBP.js";
import "./chunk-VC3NHPBS.js";
import "./chunk-X5TTAXLY.js";
import {
  init_cjs_shims
} from "./chunk-MTQ2JLIW.js";

// ../mcp-server/dist/http.js
init_cjs_shims();
import { createHmac, randomUUID, timingSafeEqual } from "node:crypto";
import { createServer } from "node:http";
var MAX_BODY_BYTES = 1e6;
function collectBody(req) {
  return new Promise((resolve, reject) => {
    const chunks = [];
    let totalBytes = 0;
    let settled = false;
    const finalizeReject = (error) => {
      if (settled) {
        return;
      }
      settled = true;
      reject(error);
    };
    const finalizeResolve = (body) => {
      if (settled) {
        return;
      }
      settled = true;
      resolve(body);
    };
    req.on("data", (chunk) => {
      if (settled) {
        return;
      }
      totalBytes += chunk.length;
      if (totalBytes > MAX_BODY_BYTES) {
        req.pause();
        finalizeReject(new Error("Request body too large"));
        return;
      }
      chunks.push(chunk);
    });
    req.on("end", () => {
      finalizeResolve(Buffer.concat(chunks).toString("utf-8"));
    });
    req.on("error", (error) => {
      finalizeReject(error instanceof Error ? error : new Error(String(error)));
    });
  });
}
function constantTimeTokenEquals(expected, provided) {
  const key = "superblocks-mcp-http-auth-compare-v1";
  const expectedDigest = createHmac("sha256", key).update(expected).digest();
  const providedDigest = createHmac("sha256", key).update(provided).digest();
  return timingSafeEqual(expectedDigest, providedDigest);
}
async function startHttpServer(options = {}) {
  const port = options.port ?? 8484;
  const profile = options.profile ?? resolveProfile();
  const waitUntilClose = options.waitUntilClose ?? false;
  const authToken = options.authToken ?? process.env.SUPERBLOCKS_MCP_HTTP_TOKEN;
  if (!authToken) {
    throw new Error("HTTP transport requires auth token. Pass authToken option or set SUPERBLOCKS_MCP_HTTP_TOKEN.");
  }
  const registry = buildToolRegistry(toolDefinitions, profile);
  const jsonRpcOptions = {
    version: package_default.version,
    listTools: () => registry.listTools(),
    executeToolCall: (name, args) => executeToolCall(name, args, registry)
  };
  const ALLOWED_ORIGINS = /* @__PURE__ */ new Set([
    "http://localhost",
    "http://127.0.0.1",
    "https://localhost",
    "https://127.0.0.1"
  ]);
  function corsOrigin(req) {
    const origin = req.headers.origin;
    if (!origin)
      return void 0;
    try {
      const { protocol, hostname } = new URL(origin);
      const base = `${protocol}//${hostname}`;
      return ALLOWED_ORIGINS.has(base) ? origin : void 0;
    } catch {
      return void 0;
    }
  }
  function isAuthorized(req) {
    const authorization = req.headers.authorization;
    if (!authorization?.startsWith("Bearer ")) {
      return false;
    }
    const providedToken = authorization.slice("Bearer ".length);
    return constantTimeTokenEquals(authToken, providedToken);
  }
  function resolveSessionId(req) {
    const header = req.headers["mcp-session-id"];
    if (typeof header === "string" && header.length > 0) {
      return header;
    }
    if (Array.isArray(header) && typeof header[0] === "string" && header[0].length > 0) {
      return header[0];
    }
    return randomUUID();
  }
  const httpServer = createServer((req, res) => {
    void (async () => {
      const requestUrl = new URL(req.url ?? "", "http://127.0.0.1");
      const allowed = corsOrigin(req);
      if (allowed) {
        res.setHeader("Access-Control-Allow-Origin", allowed);
        res.setHeader("Vary", "Origin");
        res.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Mcp-Session-Id");
        res.setHeader("Access-Control-Expose-Headers", "Mcp-Session-Id");
        res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
      }
      if (requestUrl.pathname !== "/mcp") {
        res.writeHead(404, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "Not found" }));
        return;
      }
      if (req.method === "OPTIONS") {
        if (!allowed) {
          res.writeHead(403, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "Origin not allowed" }));
          return;
        }
        res.writeHead(204);
        res.end();
        return;
      }
      if (!isAuthorized(req)) {
        res.writeHead(401, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "Unauthorized" }));
        return;
      }
      if (req.method === "POST") {
        let body;
        try {
          body = await collectBody(req);
        } catch (error) {
          if (error instanceof Error && error.message === "Request body too large") {
            res.writeHead(413, {
              "Content-Type": "application/json",
              Connection: "close"
            });
            res.end(JSON.stringify({ error: "Request body too large" }), () => {
              if (!req.destroyed) {
                req.destroy();
              }
            });
            return;
          }
          throw error;
        }
        let parsed;
        try {
          parsed = JSON.parse(body);
        } catch {
          res.writeHead(400, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "Invalid JSON" }));
          return;
        }
        const sessionId = resolveSessionId(req);
        if (Array.isArray(parsed)) {
          if (parsed.length === 0) {
            res.writeHead(200, {
              "Content-Type": "application/json",
              "Mcp-Session-Id": sessionId
            });
            res.end(JSON.stringify(invalidRequestResponse()));
            return;
          }
          const results = (await Promise.all(parsed.map((r) => isJsonRpcRequest(r) ? handleJsonRpc(r, jsonRpcOptions) : Promise.resolve(invalidRequestResponse())))).filter((r) => r !== null);
          if (results.length === 0) {
            res.writeHead(202);
            res.end();
          } else {
            res.writeHead(200, {
              "Content-Type": "application/json",
              "Mcp-Session-Id": sessionId
            });
            res.end(JSON.stringify(results));
          }
        } else {
          const result = isJsonRpcRequest(parsed) ? await handleJsonRpc(parsed, jsonRpcOptions) : invalidRequestResponse();
          if (result === null) {
            res.writeHead(202);
            res.end();
          } else {
            res.writeHead(200, {
              "Content-Type": "application/json",
              "Mcp-Session-Id": sessionId
            });
            res.end(JSON.stringify(result));
          }
        }
        return;
      }
      if (req.method === "GET") {
        const sessionId = resolveSessionId(req);
        let closed = false;
        const cleanup = () => {
          if (closed) {
            return;
          }
          closed = true;
          clearInterval(heartbeat);
          if (!res.writableEnded) {
            res.end();
          }
        };
        res.writeHead(200, {
          "Content-Type": "text/event-stream",
          "Cache-Control": "no-cache",
          Connection: "keep-alive",
          "Mcp-Session-Id": sessionId
        });
        res.write(":\n\n");
        const heartbeat = setInterval(() => {
          if (closed || res.destroyed || res.writableEnded) {
            cleanup();
            return;
          }
          try {
            res.write(":\n\n");
          } catch (error) {
            console.error("SSE heartbeat write failed:", error);
            cleanup();
          }
        }, 3e4);
        req.on("close", cleanup);
        req.on("aborted", cleanup);
        res.on("close", cleanup);
        res.on("error", (error) => {
          console.error("SSE response stream error:", error);
          cleanup();
        });
        return;
      }
      if (req.method === "DELETE") {
        res.writeHead(200, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ ok: true }));
        return;
      }
      res.writeHead(405, { "Content-Type": "application/json" });
      res.end(JSON.stringify({ error: "Method not allowed" }));
    })().catch((err) => {
      console.error("Unhandled error in MCP HTTP handler:", err);
      if (res.headersSent) {
        if (!res.writableEnded) {
          res.end();
        }
        return;
      }
      res.writeHead(500, { "Content-Type": "application/json" });
      res.end(JSON.stringify({ error: "Internal server error" }));
    });
  });
  return new Promise((resolve, reject) => {
    const onRuntimeError = (error) => {
      console.error("MCP HTTP server runtime error:", error);
    };
    const onError = (error) => reject(error);
    httpServer.once("error", onError);
    httpServer.listen(port, "127.0.0.1", () => {
      httpServer.off("error", onError);
      httpServer.on("error", onRuntimeError);
      console.error(`superblocks-mcp HTTP server started on http://127.0.0.1:${port}/mcp (profile: ${profile}, tools: ${registry.listTools().length})`);
      if (!waitUntilClose) {
        resolve();
        return;
      }
      httpServer.once("close", () => {
        httpServer.off("error", onRuntimeError);
        resolve();
      });
      httpServer.once("error", (error) => {
        reject(error);
      });
    });
  });
}
export {
  startHttpServer
};
//# sourceMappingURL=http-EQGTTVXT.js.map
