import.meta.env = {"VITE_NAME":"TBC","VITE_ACTIVITY_TOKEN_NAME":"USR","VITE_TOKEN_NAME":"USR","VITE_ACTIVITY_CONTRACT":"TBCBce8HYvxEdXRefTF2LvqKi8YqpTAMwsmy4","VITE_CONTRACT_ADDRS":"TBCBce8HYvxEdXRefTF2LvqKi8YqpTAMwsmy4","VITE_BASE_API":"http://47.239.227.165:8080","VITE_DATASTATICS_URL":"ws://47.239.227.165:15555/ws","VITE_WALLET_URL":"ws://47.239.227.165:20000/ws","VITE_MINER_URL":"ws://47.239.227.165:9090/ws","VITE_COIN_TYPE":"0x800002dd","VITE_ENV":"DEV","BASE_URL":"/","MODE":"development","DEV":true,"PROD":false,"SSR":false};import __vite__cjsImport0_buffer from "/vendor/.vite-deps-buffer_.js__v--b862c10f.js"; const Buffer = __vite__cjsImport0_buffer["Buffer"];
import __vite__cjsImport1_sql_js from "/vendor/.vite-deps-sql__js.js__v--b862c10f.js"; const initSqlJs = __vite__cjsImport1_sql_js.__esModule ? __vite__cjsImport1_sql_js.default : __vite__cjsImport1_sql_js;
import sqlWasm from "/src/plus/sql-wasm.wasm__import_url.js";
import {
  checkMsgBase,
  checkSendMsg,
  responseOk,
  transToErrMsg
} from "/src/plus/message.ts.js";
let signData;
const messageOrigin = "chrome_extensions_contentScript";
chrome.storage.local.get("signData").then((store2) => {
  signData = store2.signData;
});
const localPost = async (msg) => {
  try {
    const verify = await verifyToken(msg);
    if (verify) {
      msg.messageOrigin = messageOrigin;
      window.postMessage(msg);
    }
  } catch (error) {
  }
};
let sqlDB;
function initSql(initData) {
  return initSqlJs({
    locateFile: () => chrome.runtime.getURL(sqlWasm)
  }).then(function(SQL) {
    if (initData) {
      sqlDB = new SQL.Database(initData);
    } else {
      sqlDB = new SQL.Database();
    }
  });
}
function saveSql() {
  if (!sqlDB) {
    localPost(transToErrMsg("runSql", "CONTENT", new Error("5")));
    return Promise.reject(false);
  }
  return new Promise((resolve, reject) => {
    const data = sqlDB.export();
    const buffer = Buffer.from(data);
    chrome.runtime.sendMessage(
      {
        from: "CONTENT",
        to: "BACKGROUND",
        func: "setSqlDb",
        message: {
          buffer
        }
      },
      () => {
        resolve(true);
      }
    );
  });
}
function debounce(func, wait) {
  let timeout;
  return function(...args) {
    const context = this;
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      func.apply(context, args);
    }, wait);
  };
}
const debounceSaveSql = debounce(saveSql, 500);
function callSql(fnName, statement, uid) {
  if (!sqlDB) {
    localPost(transToErrMsg("runSql", "CONTENT", new Error("5"), "," + uid));
    return;
  }
  try {
    return sqlDB[fnName](statement);
  } catch (error) {
    localPost(
      transToErrMsg(
        "runSql",
        "CONTENT",
        new Error("8"),
        "," + uid + "," + error.message
      )
    );
  }
}
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (typeof request !== "object")
    return;
  try {
    checkMsgBase("CONTENT", request);
  } catch (error) {
    console.error(error);
    return;
  }
  const { func, token, from, to, message } = request;
  if (to === "BACKGROUND") {
    if (from === "POPUP") {
      chrome.runtime.sendMessage({ ...request, from: "CONTENT" }, (res) => {
        sendResponse(res);
      });
    } else {
      chrome.runtime.sendMessage(request, (res) => {
        sendResponse(res);
      });
    }
    return true;
  } else if (to === "CONTENT") {
    chrome.runtime.sendMessage(request, (res) => sendResponse(res));
    return true;
  } else if (to === "PAGE") {
    if (func === "authorize") {
      setTimeout(
        () => {
          chrome.storage.local.remove("currentActionToPath");
        },
        5 * 60 * 1e3
      );
    }
    if (func === "authTransfer") {
      setTimeout(
        () => {
          chrome.storage.local.remove("authTransferPath");
          chrome.storage.local.remove("authTransferData");
        },
        1 * 60 * 1e3
      );
    }
    if (func === "noPermission") {
      signData = null;
      chrome.storage.local.remove("signData");
    }
    if (func === "createSign") {
      if (!message)
        return;
      const jsonData = JSON.parse(message.jsonString);
      const tokenData = {
        ...jsonData
      };
      const string = JSON.stringify(tokenData);
      const token2 = Buffer.from(string).toString("base64");
      tokenData.token = token2;
      signData = tokenData;
      chrome.storage.local.set({
        signData: tokenData
      });
      const jsonString = JSON.stringify(tokenData);
      localPost({ ...responseOk(func, from, { message: { jsonString } }) });
      localPost({
        ...responseOk("authorize", from, { message: { jsonString } })
      });
    } else {
      localPost(request);
    }
    sendResponse({ request, from: to, to: from });
  }
});
const biPre = import.meta.env.VITE_NAME;
let superTokens = ["iCom official website", biPre + " official website"];
let currentToken;
async function verifyToken(data) {
  const { func, token, from, to, message } = data;
  if (!currentToken)
    currentToken = token;
  let isFree = [
    "isInstalled",
    "openPopup",
    "authorize",
    "authorizeOpen",
    "linkWallet",
    "pullActivityTx",
    "pullActivityRecharge",
    "networkAccounts",
    "sendToWsWallet",
    "pullActivityApprove",
    "authorizeSign",
    "authorizeKey",
    "getZeroAddress"
  ].includes(func);
  if (isFree)
    return true;
  if (superTokens.includes(currentToken))
    return true;
  if (to === "PAGE") {
    let state = false;
    if (typeof signData === "object") {
      if ("address" in signData) {
        state = true;
      }
    }
    return state;
  }
  if (from === "PAGE") {
    if (!token)
      throw new Error("2");
    try {
      let state = false;
      const text = Buffer.from(token, "base64").toString();
      const currentSignData = JSON.parse(text);
      const { account } = await chrome.storage.local.get("account");
      if (typeof signData === "object") {
        state = [currentSignData.address === account.address].every(Boolean);
      }
      if (!state)
        throw new Error("1");
    } catch (error) {
      throw new Error("1");
    }
  }
  return true;
}
window.addEventListener("message", async ({ data }) => {
  if (typeof data !== "object")
    return;
  if (data.messageOrigin && data.messageOrigin === messageOrigin) {
    return;
  }
  try {
    checkMsgBase("CONTENT", data);
  } catch (error) {
    const obj = transToErrMsg(data.func, data.to, error);
    if (obj) {
      if (!data.func) {
        data.func = "notFunc";
      }
      localPost(obj);
    }
  }
  try {
    const { func, token, from, to, message } = data;
    checkSendMsg(data);
    if (to === "CONTENT" && func == "getZeroAddress") {
      chrome.storage.local.get("currentaddrCoin").then((res) => {
        let zeroAddress = res.currentaddrCoin;
        localPost(
          responseOk("getZeroAddress", to, { message: { zeroAddress } })
        );
      });
    } else if (from === "PAGE") {
      const verify = await verifyToken(data);
      if (verify) {
        if (to === "POPUP") {
          chrome.runtime.sendMessage(data, (res) => {
            if (func === "openPopup") {
              localPost(res);
            }
          });
        } else if (to === "BACKGROUND") {
          chrome.runtime.sendMessage(data, (res) => localPost(res));
        } else if (to === "CONTENT") {
          if (func === "saveSql") {
            saveSql();
          } else if (func === "initSql") {
            chrome.runtime.sendMessage({ ...data, to: "BACKGROUND" }, (res) => {
              let buffer;
              try {
                buffer = Buffer.from(res);
              } catch (error) {
                buffer = void 0;
              }
              initSql(buffer).then(() => {
                localPost(responseOk("initSql", to));
              }).catch((err) => {
                localPost(transToErrMsg("initSql", to, new Error("5")));
              });
            });
          } else if (func === "runSql" && message) {
            const { fnName, sql, uid } = JSON.parse(message.jsonString);
            if (fnName === "prepare") {
              const stmt = callSql(fnName, sql, uid);
              if (stmt) {
                stmt.bind({});
                const sqlRes = [];
                while (stmt.step()) {
                  let row = stmt.getAsObject();
                  sqlRes.push(row);
                }
                stmt.free();
                const jsonString = JSON.stringify({
                  sqlRes,
                  fnName,
                  uid
                });
                localPost(
                  responseOk("runSql", to, { message: { jsonString } })
                );
              }
            } else {
              callSql(fnName, sql, uid);
              const jsonString = JSON.stringify({
                fnName,
                uid
              });
              localPost(responseOk("runSql", to, { message: { jsonString } }));
            }
          } else {
            localPost(responseOk(func, to));
          }
        }
      }
    }
  } catch (error) {
    const obj = transToErrMsg(
      data.func,
      data.to,
      error,
      data.message?.jsonString
    );
    if (obj) {
      if (!data.func) {
        data.func = "notFunc";
      }
      localPost(obj);
    }
  }
});
