"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);

// src/utils.ts
var utils_exports = {};
__export(utils_exports, {
  getLogDir: () => getLogDir,
  getLogDirByType: () => getLogDirByType,
  getTmpDir: () => getTmpDir,
  getTmpFile: () => getTmpFile,
  getVersion: () => getVersion,
  groupedActionDumpFileExt: () => groupedActionDumpFileExt,
  insightDumpFileExt: () => insightDumpFileExt,
  overlapped: () => overlapped,
  replacerForPageObject: () => replacerForPageObject,
  reportHTMLContent: () => reportHTMLContent,
  setLogDir: () => setLogDir,
  sleep: () => sleep,
  stringifyDumpData: () => stringifyDumpData,
  uploadTestInfoToServer: () => uploadTestInfoToServer,
  writeDumpReport: () => writeDumpReport,
  writeLogFile: () => writeLogFile
});
module.exports = __toCommonJS(utils_exports);
var import_node_assert = __toESM(require("assert"));
var import_node_child_process = require("child_process");
var import_node_fs = require("fs");
var import_node_os = require("os");
var import_node_path = require("path");
var import_fs = require("@midscene/shared/fs");
var import_utils = require("@midscene/shared/utils");

// src/env.ts
var MIDSCENE_OPENAI_INIT_CONFIG_JSON = "MIDSCENE_OPENAI_INIT_CONFIG_JSON";
var MIDSCENE_MODEL_NAME = "MIDSCENE_MODEL_NAME";
var MIDSCENE_LANGSMITH_DEBUG = "MIDSCENE_LANGSMITH_DEBUG";
var MIDSCENE_DEBUG_AI_PROFILE = "MIDSCENE_DEBUG_AI_PROFILE";
var MIDSCENE_DANGEROUSLY_PRINT_ALL_CONFIG = "MIDSCENE_DANGEROUSLY_PRINT_ALL_CONFIG";
var MIDSCENE_DEBUG_MODE = "MIDSCENE_DEBUG_MODE";
var MIDSCENE_OPENAI_SOCKS_PROXY = "MIDSCENE_OPENAI_SOCKS_PROXY";
var OPENAI_API_KEY = "OPENAI_API_KEY";
var OPENAI_BASE_URL = "OPENAI_BASE_URL";
var MIDSCENE_MODEL_TEXT_ONLY = "MIDSCENE_MODEL_TEXT_ONLY";
var MIDSCENE_CACHE = "MIDSCENE_CACHE";
var MATCH_BY_POSITION = "MATCH_BY_POSITION";
var MIDSCENE_REPORT_TAG_NAME = "MIDSCENE_REPORT_TAG_NAME";
var MIDSCENE_USE_AZURE_OPENAI = "MIDSCENE_USE_AZURE_OPENAI";
var MIDSCENE_AZURE_OPENAI_SCOPE = "MIDSCENE_AZURE_OPENAI_SCOPE";
var MIDSCENE_AZURE_OPENAI_INIT_CONFIG_JSON = "MIDSCENE_AZURE_OPENAI_INIT_CONFIG_JSON";
var MIDSCENE_USE_ANTHROPIC_SDK = "MIDSCENE_USE_ANTHROPIC_SDK";
var ANTHROPIC_API_KEY = "ANTHROPIC_API_KEY";
var OPENAI_USE_AZURE = "OPENAI_USE_AZURE";
var allConfigFromEnv = () => {
  return {
    [MIDSCENE_OPENAI_INIT_CONFIG_JSON]: process.env[MIDSCENE_OPENAI_INIT_CONFIG_JSON] || void 0,
    [MIDSCENE_MODEL_NAME]: process.env[MIDSCENE_MODEL_NAME] || void 0,
    [MIDSCENE_DEBUG_MODE]: process.env[MIDSCENE_DEBUG_MODE] || void 0,
    [MIDSCENE_LANGSMITH_DEBUG]: process.env[MIDSCENE_LANGSMITH_DEBUG] || void 0,
    [MIDSCENE_DEBUG_AI_PROFILE]: process.env[MIDSCENE_DEBUG_AI_PROFILE] || void 0,
    [MIDSCENE_DANGEROUSLY_PRINT_ALL_CONFIG]: process.env[MIDSCENE_DANGEROUSLY_PRINT_ALL_CONFIG] || void 0,
    [OPENAI_API_KEY]: process.env[OPENAI_API_KEY] || void 0,
    [OPENAI_BASE_URL]: process.env[OPENAI_BASE_URL] || void 0,
    [MIDSCENE_MODEL_TEXT_ONLY]: process.env[MIDSCENE_MODEL_TEXT_ONLY] || void 0,
    [OPENAI_USE_AZURE]: process.env[OPENAI_USE_AZURE] || void 0,
    [MIDSCENE_CACHE]: process.env[MIDSCENE_CACHE] || void 0,
    [MATCH_BY_POSITION]: process.env[MATCH_BY_POSITION] || void 0,
    [MIDSCENE_REPORT_TAG_NAME]: process.env[MIDSCENE_REPORT_TAG_NAME] || void 0,
    [MIDSCENE_OPENAI_SOCKS_PROXY]: process.env[MIDSCENE_OPENAI_SOCKS_PROXY] || void 0,
    [MIDSCENE_USE_AZURE_OPENAI]: process.env[MIDSCENE_USE_AZURE_OPENAI] || void 0,
    [MIDSCENE_AZURE_OPENAI_SCOPE]: process.env[MIDSCENE_AZURE_OPENAI_SCOPE] || "https://cognitiveservices.azure.com/.default",
    [MIDSCENE_AZURE_OPENAI_INIT_CONFIG_JSON]: process.env[MIDSCENE_AZURE_OPENAI_INIT_CONFIG_JSON] || void 0,
    [MIDSCENE_USE_ANTHROPIC_SDK]: process.env[MIDSCENE_USE_ANTHROPIC_SDK] || void 0,
    [ANTHROPIC_API_KEY]: process.env[ANTHROPIC_API_KEY] || void 0
  };
};
var userConfig = {};
var getAIConfig = (configKey) => {
  if (typeof userConfig[configKey] !== "undefined") {
    return userConfig[configKey];
  }
  return allConfigFromEnv()[configKey];
};
var getAIConfigInJson = (configKey) => {
  const config = getAIConfig(configKey);
  try {
    return config ? JSON.parse(config) : void 0;
  } catch (error) {
    throw new Error(
      `Failed to parse json config: ${configKey}. ${error.message}`,
      {
        cause: error
      }
    );
  }
};

// src/utils.ts
var logDir = (0, import_node_path.join)(process.cwd(), "./midscene_run/");
var logEnvReady = false;
var insightDumpFileExt = "insight-dump.json";
var groupedActionDumpFileExt = "web-dump.json";
function getLogDir() {
  return logDir;
}
function setLogDir(dir) {
  logDir = dir;
}
function getLogDirByType(type) {
  const dir = (0, import_node_path.join)(getLogDir(), type);
  if (!(0, import_node_fs.existsSync)(dir)) {
    (0, import_node_fs.mkdirSync)(dir, { recursive: true });
  }
  return dir;
}
var reportTpl = null;
function getReportTpl() {
  if (import_utils.ifInBrowser) {
    if (!reportTpl && window.midscene_report_tpl) {
      reportTpl = window.midscene_report_tpl;
    }
    (0, import_node_assert.default)(
      reportTpl,
      "reportTpl should be set before writing report in browser"
    );
    return reportTpl;
  }
  if (!reportTpl) {
    let reportPath = (0, import_node_path.join)(__dirname, "../../report/index.html");
    if (!(0, import_node_fs.existsSync)(reportPath)) {
      reportPath = (0, import_node_path.join)(__dirname, "../report/index.html");
    }
    reportTpl = (0, import_node_fs.readFileSync)(reportPath, "utf-8");
  }
  return reportTpl;
}
function reportHTMLContent(dumpData) {
  const tpl = getReportTpl();
  let reportContent;
  if (Array.isArray(dumpData) && dumpData.length === 0 || typeof dumpData === "undefined") {
    reportContent = tpl.replace(
      /\s+{{dump}}\s+/,
      `<script type="midscene_web_dump" type="application/json"></script>`
    );
  } else if (typeof dumpData === "string") {
    reportContent = tpl.replace(
      /\s+{{dump}}\s+/,
      `<script type="midscene_web_dump" type="application/json">${dumpData}</script>`
    );
  } else {
    const dumps = dumpData.map(({ dumpString, attributes }) => {
      const attributesArr = Object.keys(attributes || {}).map((key) => {
        return `${key}="${encodeURIComponent(attributes[key])}"`;
      });
      return `<script type="midscene_web_dump" type="application/json" ${attributesArr.join(
        " "
      )}
>${dumpString}
</script>`;
    });
    reportContent = tpl.replace(/\s+{{dump}}\s+/, dumps.join("\n"));
  }
  return reportContent;
}
function writeDumpReport(fileName, dumpData) {
  if (import_utils.ifInBrowser) {
    console.log("will not write report in browser");
    return null;
  }
  const midscenePkgInfo = (0, import_fs.getRunningPkgInfo)(__dirname);
  if (!midscenePkgInfo) {
    console.warn("midscenePkgInfo not found, will not write report");
    return null;
  }
  const reportPath = (0, import_node_path.join)(getLogDirByType("report"), `${fileName}.html`);
  const reportContent = reportHTMLContent(dumpData);
  (0, import_node_fs.writeFileSync)(reportPath, reportContent);
  return reportPath;
}
function writeLogFile(opts) {
  if (import_utils.ifInBrowser) {
    return "/mock/report.html";
  }
  const { fileName, fileExt, fileContent, type = "dump" } = opts;
  const targetDir = getLogDirByType(type);
  if (!logEnvReady) {
    (0, import_node_assert.default)(targetDir, "logDir should be set before writing dump file");
    const gitIgnorePath = (0, import_node_path.join)(targetDir, "../../.gitignore");
    let gitIgnoreContent = "";
    if ((0, import_node_fs.existsSync)(gitIgnorePath)) {
      gitIgnoreContent = (0, import_node_fs.readFileSync)(gitIgnorePath, "utf-8");
    }
    const logDirName = (0, import_node_path.basename)(logDir);
    if (!gitIgnoreContent.includes(`${logDirName}/`)) {
      (0, import_node_fs.writeFileSync)(
        gitIgnorePath,
        `${gitIgnoreContent}
# Midscene.js dump files
${logDirName}/report
${logDirName}/dump
${logDirName}/tmp
`,
        "utf-8"
      );
    }
    logEnvReady = true;
  }
  const filePath = (0, import_node_path.join)(targetDir, `${fileName}.${fileExt}`);
  const outputResourceDir = (0, import_node_path.dirname)(filePath);
  if (!(0, import_node_fs.existsSync)(outputResourceDir)) {
    (0, import_node_fs.mkdirSync)(outputResourceDir, { recursive: true });
  }
  (0, import_node_fs.writeFileSync)(filePath, fileContent);
  if (opts == null ? void 0 : opts.generateReport) {
    return writeDumpReport(fileName, fileContent);
  }
  return filePath;
}
function getTmpDir() {
  if (import_utils.ifInBrowser) {
    return null;
  }
  const runningPkgInfo = (0, import_fs.getRunningPkgInfo)();
  if (!runningPkgInfo) {
    return null;
  }
  const { name } = runningPkgInfo;
  const path = (0, import_node_path.join)((0, import_node_os.tmpdir)(), name);
  (0, import_node_fs.mkdirSync)(path, { recursive: true });
  return path;
}
function getTmpFile(fileExtWithoutDot) {
  if (import_utils.ifInBrowser) {
    return null;
  }
  const tmpDir = getTmpDir();
  const filename = `${(0, import_utils.uuid)()}.${fileExtWithoutDot}`;
  return (0, import_node_path.join)(tmpDir, filename);
}
function overlapped(container, target) {
  return container.left < target.left + target.width && container.left + container.width > target.left && container.top < target.top + target.height && container.top + container.height > target.top;
}
async function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
function replacerForPageObject(key, value) {
  var _a, _b;
  if (value && ((_a = value.constructor) == null ? void 0 : _a.name) === "Page") {
    return "[Page object]";
  }
  if (value && ((_b = value.constructor) == null ? void 0 : _b.name) === "Browser") {
    return "[Browser object]";
  }
  return value;
}
function stringifyDumpData(data, indents) {
  return JSON.stringify(data, replacerForPageObject, indents);
}
function getVersion() {
  return "0.8.8";
}
function debugLog(...message) {
  const debugMode = getAIConfig(MIDSCENE_DEBUG_MODE);
  if (debugMode) {
    console.log("[Midscene]", ...message);
  }
}
var lastReportedRepoUrl = "";
function uploadTestInfoToServer({ testUrl }) {
  let repoUrl = "";
  let userEmail = "";
  const extraConfig = getAIConfigInJson(MIDSCENE_OPENAI_INIT_CONFIG_JSON);
  const serverUrl = extraConfig == null ? void 0 : extraConfig.REPORT_SERVER_URL;
  try {
    repoUrl = (0, import_node_child_process.execSync)("git config --get remote.origin.url").toString().trim();
    userEmail = (0, import_node_child_process.execSync)("git config --get user.email").toString().trim();
  } catch (error) {
    debugLog("Failed to get git info:", error);
  }
  if (serverUrl && (repoUrl && repoUrl !== lastReportedRepoUrl || !repoUrl && testUrl)) {
    debugLog("Uploading test info to server", {
      serverUrl,
      repoUrl,
      testUrl,
      userEmail
    });
    fetch(serverUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        repo_url: repoUrl,
        test_url: testUrl,
        user_email: userEmail
      })
    }).then((response) => response.json()).then((data) => {
      debugLog("Successfully uploaded test info to server:", data);
    }).catch(
      (error) => debugLog("Failed to upload test info to server:", error)
    );
    lastReportedRepoUrl = repoUrl;
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  getLogDir,
  getLogDirByType,
  getTmpDir,
  getTmpFile,
  getVersion,
  groupedActionDumpFileExt,
  insightDumpFileExt,
  overlapped,
  replacerForPageObject,
  reportHTMLContent,
  setLogDir,
  sleep,
  stringifyDumpData,
  uploadTestInfoToServer,
  writeDumpReport,
  writeLogFile
});
