import { createRequire as _createRequire } from 'node:module';
const require = _createRequire(import.meta.url);
import {
  useTunnel
} from "./chunk-BK4PC6IQ.js";
import "./chunk-GWE3BRHX.js";
import {
  Box_default,
  CliError,
  CliErrorCode,
  ComponentType,
  Spinner,
  Text,
  Trans,
  attachLogger,
  deattachLogger,
  external_exports,
  require_lib,
  require_react,
  useAsync,
  useDevCenterClient,
  useErrorReporter,
  useHttpClient,
  useProjectModel,
  useTranslation
} from "./chunk-4MWJVDBY.js";
import {
  __toESM,
  init_esm_shims
} from "./chunk-4EFJZ3GQ.js";

// src/components/LogsCommand/index.ts
init_esm_shims();

// src/components/LogsCommand/LogsCommand.tsx
init_esm_shims();
var import_react3 = __toESM(require_react(), 1);
var import_variant3 = __toESM(require_lib(), 1);

// src/components/LogsCommand/useLogsServer.ts
init_esm_shims();
var import_react = __toESM(require_react(), 1);
import { createServer } from "node:http";
var import_variant2 = __toESM(require_lib(), 1);

// src/components/LogsCommand/logsReqHandler.ts
init_esm_shims();
var import_variant = __toESM(require_lib(), 1);
var LogMessageSchema = external_exports.unknown();
var LogMessageLevelSchema = external_exports.enum(["info", "error", "warn", "debug", "log"]);
var LogItemSchema = external_exports.object({
  message: external_exports.array(LogMessageSchema),
  level: LogMessageLevelSchema,
  timestamp: external_exports.number()
});
var ExceptionItemSchema = external_exports.object({
  stack: external_exports.string(),
  name: external_exports.string(),
  message: external_exports.string(),
  timestamp: external_exports.number()
});
var LogResponseSchema = external_exports.object({
  _type: external_exports.literal("log"),
  exceptions: external_exports.array(ExceptionItemSchema),
  logs: external_exports.array(LogItemSchema)
}).passthrough();
var SessionTimeoutResponseSchema = external_exports.object({
  _type: external_exports.literal("session-timeout")
}).passthrough();
var ServerLogResponseSchema = external_exports.discriminatedUnion("_type", [
  LogResponseSchema,
  SessionTimeoutResponseSchema
]);
var AggregatedLog = (0, import_variant.variant)({
  Log: (0, import_variant.fields)(),
  Exception: (0, import_variant.fields)()
});
var LOGS_ENDPOINT = "/logs";
var logsReqHandler = (req, res) => {
  let onLog;
  let onError;
  if (req.method === "POST" && req.url === LOGS_ENDPOINT) {
    let body = "";
    req.on("data", (chunk) => {
      body += chunk.toString();
    });
    req.on("end", () => {
      let parsedBody;
      try {
        parsedBody = ServerLogResponseSchema.parse(JSON.parse(body));
      } catch (err) {
        onError(CliErrorCode.FailedToParseLog(), err, { body });
        res.statusCode = 400;
        return res.end();
      }
      const resultLogs = [];
      if (parsedBody._type === "log") {
        resultLogs.push(
          ...parsedBody.exceptions.map(
            (exception) => AggregatedLog.Exception(exception)
          )
        );
        resultLogs.push(
          ...parsedBody.logs.map((log) => AggregatedLog.Log(log))
        );
      }
      (0, import_variant.match)(parsedBody._type, {
        log: () => {
          onLog(resultLogs);
        },
        "session-timeout": () => {
          res.statusCode = 200;
          res.end();
          onError(CliErrorCode.LogsConnectionTimeout(), {}, { body });
        }
      });
      res.statusCode = 200;
      res.end();
    });
  } else {
    res.statusCode = 404;
    res.end("Not Found");
  }
  const api = {
    onLog: (callback) => {
      onLog = callback;
      return api;
    },
    onError: (callback) => {
      onError = callback;
      return api;
    }
  };
  return api;
};

// src/components/LogsCommand/useLogsServer.ts
var deploymentIdRegex = /([0-9a-f-]{36})/;
var useLogsServer = ({
  onLog,
  version,
  appId
}) => {
  const { reportError } = useErrorReporter();
  const { getAppByVersion } = useDevCenterClient();
  const createTunnelClient = useTunnel();
  const httpClient = useHttpClient({ type: "backoffice" });
  const localServerPortResolverRef = (0, import_react.useRef)();
  const server = (0, import_react.useMemo)(() => {
    return createServer((req, res) => {
      logsReqHandler(req, res).onLog(onLog).onError((code, err, info) => {
        server.close();
        throw new CliError({ code, cause: err, info });
      });
    });
  }, [onLog]);
  const localServerPortPromise = (0, import_react.useMemo)(() => {
    return new Promise((resolve) => {
      localServerPortResolverRef.current = resolve;
    });
  }, []);
  (0, import_react.useEffect)(() => {
    server.listen(0, async () => {
      const port = server.address().port;
      localServerPortResolverRef.current?.(port);
    });
    return () => {
      if (server.listening) {
        server.close();
      }
    };
  }, [server]);
  const { status } = useAsync(async () => {
    const localServerPort = await localServerPortPromise;
    const { url: tunnelUrl } = await createTunnelClient(localServerPort);
    const { data } = await getAppByVersion({ appId, version });
    const topologyComponent = data.components.find(
      (component) => {
        return component.compType === ComponentType.TOPOLOGY;
      }
    );
    const match3 = deploymentIdRegex.exec(
      topologyComponent?.compData.topology.topology.backendApiUrl ?? ""
    );
    if (!match3?.[1]) {
      throw new CliError({
        code: CliErrorCode.FailedToGetLogsTopology(),
        cause: null
      });
    }
    const deploymentId = match3[1];
    const loggerReq = {
      appId,
      deploymentId,
      destinationUrl: new URL(LOGS_ENDPOINT, tunnelUrl).href
    };
    try {
      await httpClient.request(attachLogger(loggerReq));
    } catch (error) {
      server.close();
      throw new CliError({
        code: CliErrorCode.FailedToConnectToLogsService(),
        cause: error
      });
    }
    return deploymentId;
  }, []);
  (0, import_react.useEffect)(() => {
    return () => {
      if ((0, import_variant2.isType)(status, "Success")) {
        httpClient.request(
          deattachLogger({
            appId,
            deploymentId: status.result
          })
        ).catch(reportError);
      }
    };
  }, []);
  return status;
};

// src/components/LogsCommand/ServerLogMessage.tsx
init_esm_shims();
var import_react2 = __toESM(require_react(), 1);
var ServerLogMessage = ({ message, level }) => {
  let content = "unknown";
  if (typeof message === "object") {
    content = JSON.stringify(message);
  } else {
    content = String(message);
  }
  return /* @__PURE__ */ import_react2.default.createElement(Text, { skin: level === "error" ? "error" : "standard" }, content);
};

// src/components/LogsCommand/LogsCommand.tsx
var LogsCommand = ({ version }) => {
  const { model } = useProjectModel();
  const { t } = useTranslation();
  const [logs, setLogs] = (0, import_react3.useState)([]);
  const serverResult = useLogsServer({
    appId: model.config.appId,
    version,
    onLog: (0, import_react3.useCallback)(
      (serverLogs) => {
        setLogs((prevLogs) => {
          return [...prevLogs, ...serverLogs];
        });
      },
      [setLogs]
    )
  });
  return (0, import_variant3.match)(serverResult, {
    Success: () => /* @__PURE__ */ import_react3.default.createElement(Box_default, { marginTop: 1, marginBottom: 1, flexDirection: "column" }, /* @__PURE__ */ import_react3.default.createElement(Box_default, { marginBottom: 1, flexDirection: "column" }, /* @__PURE__ */ import_react3.default.createElement(Text, null, /* @__PURE__ */ import_react3.default.createElement(Trans, { i18nKey: "logs_command.listening_to_logs" })), /* @__PURE__ */ import_react3.default.createElement(Text, null, /* @__PURE__ */ import_react3.default.createElement(Trans, { i18nKey: "logs_command.prod_env_logs", values: { version } }))), logs.map((log, logIdx) => /* @__PURE__ */ import_react3.default.createElement(Box_default, { key: logIdx, flexDirection: "column" }, /* @__PURE__ */ import_react3.default.createElement(Box_default, { columnGap: 1 }, /* @__PURE__ */ import_react3.default.createElement(Box_default, { flexShrink: 0 }, /* @__PURE__ */ import_react3.default.createElement(Text, { skin: "secondary" }, new Date(log.timestamp).toLocaleTimeString())), /* @__PURE__ */ import_react3.default.createElement(Box_default, { columnGap: 1 }, (0, import_variant3.match)(log, {
      Log: ({ message, level }) => message.map((msgItem, idx) => /* @__PURE__ */ import_react3.default.createElement(
        ServerLogMessage,
        {
          key: `${logIdx}-${idx}`,
          message: msgItem,
          level
        }
      )),
      Exception: ({ message }) => /* @__PURE__ */ import_react3.default.createElement(
        ServerLogMessage,
        {
          key: logIdx,
          message,
          level: "error"
        }
      )
    }))), (0, import_variant3.match)(log, {
      Log: () => null,
      Exception: ({ stack }) => /* @__PURE__ */ import_react3.default.createElement(Text, { skin: "error" }, stack)
    })))),
    Loading: () => /* @__PURE__ */ import_react3.default.createElement(Spinner, { text: t("logs_command.connecting") }),
    Error: () => null
  });
};
export {
  LogsCommand
};
//# sourceMappingURL=LogsCommand-5RGV3J3N.js.map