"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var response_exports = {};
__export(response_exports, {
  Response: () => Response,
  parseResponse: () => parseResponse,
  renderTabMarkdown: () => renderTabMarkdown,
  renderTabsMarkdown: () => renderTabsMarkdown,
  requestDebug: () => requestDebug,
  serializeResponse: () => serializeResponse,
  serializeStructuredResponse: () => serializeStructuredResponse
});
module.exports = __toCommonJS(response_exports);
var import_fs = __toESM(require("fs"));
var import_path = __toESM(require("path"));
var import_utilsBundle = require("playwright-core/lib/utilsBundle");
var import_tab = require("./tab");
var import_utils = require("./tools/utils");
var import_screenshot = require("./tools/screenshot");
const requestDebug = (0, import_utilsBundle.debug)("pw:mcp:request");
class Response {
  constructor(ordinal, context, toolName, toolArgs) {
    this._results = [];
    this._errors = [];
    this._code = [];
    this._includeSnapshot = "none";
    this._context = context;
    this.toolName = toolName;
    this.toolArgs = toolArgs;
  }
  static {
    this._ordinal = 0;
  }
  static create(context, toolName, toolArgs) {
    return new Response(++Response._ordinal, context, toolName, toolArgs);
  }
  addTextResult(text) {
    this._results.push({ title: "", text });
  }
  async addResult(title, data, file) {
    this._results.push({
      text: typeof data === "string" ? data : void 0,
      data: typeof data === "string" ? void 0 : data,
      title,
      file
    });
  }
  addError(error) {
    this._errors.push(error);
  }
  addCode(code) {
    this._code.push(code);
  }
  setIncludeSnapshot() {
    this._includeSnapshot = this._context.config.snapshot.mode;
  }
  setIncludeFullSnapshot(includeSnapshotFileName) {
    this._includeSnapshot = "full";
    this._includeSnapshotFileName = includeSnapshotFileName;
  }
  async build() {
    const rootPath = this._context.firstRootPath();
    const sections = [];
    const addSection = (title) => {
      const section = { title, content: [], isError: title === "Error" };
      sections.push(section);
      return section.content;
    };
    if (this._errors.length) {
      const content = addSection("Error");
      content.push({ text: this._errors.join("\n"), title: "error" });
    }
    if (this._results.length) {
      const content = addSection("Result");
      content.push(...this._results);
    }
    if (this._context.config.codegen !== "none" && this._code.length) {
      const content = addSection("Ran Playwright code");
      for (const code of this._code)
        content.push({ text: code, title: "code" });
    }
    const tabSnapshot = this._context.currentTab() ? await this._context.currentTabOrDie().captureSnapshot() : void 0;
    const tabHeaders = await Promise.all(this._context.tabs().map((tab) => tab.headerSnapshot()));
    if (this._includeSnapshot !== "none" || tabHeaders.some((header) => header.changed)) {
      if (tabHeaders.length !== 1) {
        const content2 = addSection("Open tabs");
        content2.push({ text: renderTabsMarkdown(tabHeaders).join("\n"), title: "Open tabs" });
      }
      const content = addSection("Page");
      content.push({ text: renderTabMarkdown(tabHeaders[0]).join("\n"), title: "Page" });
    }
    if (tabSnapshot?.modalStates.length) {
      const content = addSection("Modal state");
      content.push({ text: (0, import_tab.renderModalStates)(this._context.config, tabSnapshot.modalStates).join("\n"), title: "Modal state" });
    }
    if (tabSnapshot && this._includeSnapshot !== "none") {
      const content = addSection("Snapshot");
      const snapshot = this._includeSnapshot === "full" ? tabSnapshot.ariaSnapshot : tabSnapshot.ariaSnapshotDiff ?? tabSnapshot.ariaSnapshot;
      content.push({ text: snapshot, title: "snapshot", file: { prefix: "page", ext: "yml", suggestedFilename: this._includeSnapshotFileName } });
    }
    if (tabSnapshot?.events.filter((event) => event.type !== "request").length) {
      const content = addSection("Events");
      const text = [];
      for (const event of tabSnapshot.events) {
        if (event.type === "console") {
          if ((0, import_tab.shouldIncludeMessage)(this._context.config.console.level, event.message.type))
            text.push(`- ${trimMiddle(event.message.toString(), 100)}`);
        } else if (event.type === "download-start") {
          text.push(`- Downloading file ${event.download.download.suggestedFilename()} ...`);
        } else if (event.type === "download-finish") {
          text.push(`- Downloaded file ${event.download.download.suggestedFilename()} to "${rootPath ? import_path.default.relative(rootPath, event.download.outputFile) : event.download.outputFile}"`);
        }
      }
      content.push({ text: text.join("\n"), title: "events" });
    }
    return sections;
  }
}
function renderTabMarkdown(tab) {
  const lines = [`- Page URL: ${tab.url}`];
  if (tab.title)
    lines.push(`- Page Title: ${tab.title}`);
  return lines;
}
function renderTabsMarkdown(tabs) {
  if (!tabs.length)
    return ["No open tabs. Navigate to a URL to create one."];
  const lines = [];
  for (let i = 0; i < tabs.length; i++) {
    const tab = tabs[i];
    const current = tab.current ? " (current)" : "";
    lines.push(`- ${i}:${current} [${tab.title}](${tab.url})`);
  }
  return lines;
}
function trimMiddle(text, maxLength) {
  if (text.length <= maxLength)
    return text;
  return text.slice(0, Math.floor(maxLength / 2)) + "..." + text.slice(-3 - Math.floor(maxLength / 2));
}
function parseSections(text) {
  const sections = /* @__PURE__ */ new Map();
  const sectionHeaders = text.split(/^### /m).slice(1);
  for (const section of sectionHeaders) {
    const firstNewlineIndex = section.indexOf("\n");
    if (firstNewlineIndex === -1)
      continue;
    const sectionName = section.substring(0, firstNewlineIndex);
    const sectionContent = section.substring(firstNewlineIndex + 1).trim();
    sections.set(sectionName, sectionContent);
  }
  return sections;
}
async function serializeResponse(context, sections, rootPath) {
  const redactText = (text2) => {
    for (const [secretName, secretValue] of Object.entries(context.config.secrets ?? {}))
      text2 = text2.replaceAll(secretValue, `<secret>${secretName}</secret>`);
    return text2;
  };
  const text = [];
  for (const section of sections) {
    text.push(`### ${section.title}`);
    for (const result of section.content) {
      if (!result.file) {
        if (result.text !== void 0)
          text.push(result.text);
        continue;
      }
      if (result.file.suggestedFilename || context.config.outputMode === "file" || result.data) {
        const generatedFileName = await context.outputFile((0, import_utils.dateAsFileName)(result.file.prefix, result.file.ext), { origin: "code", title: section.title });
        const fileName = result.file.suggestedFilename ? await context.outputFile(result.file.suggestedFilename, { origin: "llm", title: section.title }) : generatedFileName;
        text.push(`- [${result.title}](${rootPath ? import_path.default.relative(rootPath, fileName) : fileName})`);
        if (result.data)
          await import_fs.default.promises.writeFile(fileName, result.data, "utf-8");
        else
          await import_fs.default.promises.writeFile(fileName, result.text);
      } else {
        if (result.file.ext === "yml")
          text.push(`\`\`\`yaml
${result.text}
\`\`\``);
        else
          text.push(result.text);
      }
    }
  }
  const content = [
    {
      type: "text",
      text: redactText(text.join("\n"))
    }
  ];
  if (context.config.imageResponses !== "omit") {
    for (const result of sections.flatMap((section) => section.content).filter((result2) => result2.file?.contentType)) {
      const scaledData = (0, import_screenshot.scaleImageToFitMessage)(result.data, result.file.contentType === "image/png" ? "png" : "jpeg");
      content.push({ type: "image", data: scaledData.toString("base64"), mimeType: result.file.contentType });
    }
  }
  return {
    content,
    ...sections.some((section) => section.isError) ? { isError: true } : {}
  };
}
async function serializeStructuredResponse(sections) {
  for (const section of sections) {
    for (const result of section.content) {
      if (!result.data)
        continue;
      result.isBase64 = true;
      result.text = result.data.toString("base64");
      result.data = void 0;
    }
  }
  return {
    content: [{ type: "text", text: "", _meta: { sections } }],
    isError: sections.some((section) => section.isError)
  };
}
function parseResponse(response) {
  if (response.content?.[0].type !== "text")
    return void 0;
  const text = response.content[0].text;
  const sections = parseSections(text);
  const error = sections.get("Error");
  const result = sections.get("Result");
  const code = sections.get("Ran Playwright code");
  const tabs = sections.get("Open tabs");
  const page = sections.get("Page");
  const snapshot = sections.get("Snapshot");
  const events = sections.get("Events");
  const modalState = sections.get("Modal state");
  const codeNoFrame = code?.replace(/^```js\n/, "").replace(/\n```$/, "");
  const isError = response.isError;
  const attachments = response.content.length > 1 ? response.content.slice(1) : void 0;
  return {
    result,
    error,
    code: codeNoFrame,
    tabs,
    page,
    snapshot,
    events,
    modalState,
    isError,
    attachments,
    text
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  Response,
  parseResponse,
  renderTabMarkdown,
  renderTabsMarkdown,
  requestDebug,
  serializeResponse,
  serializeStructuredResponse
});
