;
{
  try {
    let e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
    n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "6ca9f71f-567c-458c-b4e7-62f3406f43a8", e._sentryDebugIdIdentifier = "sentry-dbid-6ca9f71f-567c-458c-b4e7-62f3406f43a8");
  } catch (e) {
  }
}
;
import { ab as cloneObject, a3 as createLogger, bb as isString, $ as httpPost } from "./StoreProvider-CqQrndhS.js";
import { i as isValueObscured } from "./MaskedInput-DgjlsFWR.js";
import { g as getProp, d as deleteProp } from "./utils-DNSfZiio.js";
import { A as AdyenKycSdkError } from "./mapExistingFile-DOPjFNWj.js";
const omitObscuredFieldsIfUnchanged = (obscuredFields, dataSubmitted, savedData) => {
  if (!dataSubmitted) {
    return;
  }
  const filtered = cloneObject(dataSubmitted);
  obscuredFields.forEach((obscuredField) => {
    const prevValue = savedData ? getProp(savedData, obscuredField) : void 0;
    const newValue = getProp(dataSubmitted, obscuredField);
    if (prevValue === newValue && isValueObscured(newValue)) {
      deleteProp(obscuredField, filtered);
    }
  });
  return filtered;
};
const removeElementSiblings = (element) => {
  const parent = element.parentNode;
  if (!parent) return;
  let child = parent.firstChild;
  while (child) {
    if (child !== element) parent.removeChild(child);
    child = child.nextSibling;
  }
};
const RELEVANT_MESSAGE_TYPES = ["account_verification_report_id", "error"];
const TERMINAL_DATA_PROPS = ["accounts", "error", "reference"];
const MOUNT_TIMEOUT = 10 * 1e3;
const TINK_VENDOR = "Tink";
const logger = createLogger();
const isObjectData = (data) => typeof data === "object" && !Array.isArray(data) && data !== null;
const isTerminalMessageData = (data) => isObjectData(data) && Object.entries(data).some(([prop]) => TERMINAL_DATA_PROPS.includes(prop));
const parseMessageJson = (message) => {
  try {
    const messageData = JSON.parse(message);
    if (!RELEVANT_MESSAGE_TYPES.includes(messageData.type)) return "invalid";
    return messageData;
  } catch {
    return "invalid";
  }
};
const isValidErrorResponse = (responseData) => isObjectData(responseData) && "error" in responseData && "errorMessage" in responseData;
const isVerifiedAccountsData = (responseData) => isObjectData(responseData) && "accounts" in responseData;
const callbackErrorHandler = async (response) => {
  try {
    await response;
  } catch (ex) {
    logger.error(ex);
  }
  return {
    error: "UNKNOWN_ERROR",
    message: `We couldn't complete the account check. Please try again later or provide account details manually.`
  };
};
let activeWidget;
class IFrameWidget {
  vendor;
  iframeUrl;
  iframeElement;
  iframeWindow;
  listener;
  mountInProgress = false;
  sdkToken;
  iframeUrlState;
  constructor(iframeElement, url, vendor, sdkToken) {
    try {
      this.iframeUrl = new URL(url);
    } catch (err) {
      throw new AdyenKycSdkError("WIDGET_URL_MALFORMED", err);
    }
    this.iframeElement = iframeElement;
    this.iframeWindow = iframeElement.contentWindow;
    this.vendor = vendor;
    this.sdkToken = sdkToken;
  }
  removeMessageEventListener() {
    if (!this.listener) return;
    window.removeEventListener("message", this.listener);
    this.listener = void 0;
  }
  async handleMessage({
    data,
    origin,
    source
  }) {
    if (source !== this.iframeWindow || origin !== this.iframeUrl.origin) return;
    if (this.vendor !== TINK_VENDOR && isTerminalMessageData(data)) {
      if (Object.getOwnPropertyNames(data).includes("error")) {
        throw data;
      }
      return data;
    }
    if (!isString(data)) return;
    const jsonData = parseMessageJson(data);
    if (jsonData === "invalid") return;
    const httpOptions = {
      errorHandler: callbackErrorHandler,
      baseUrl: "",
      sdkToken: this.sdkToken
    };
    const redirectURI = this.iframeUrl.searchParams.get("redirect_uri");
    if (!redirectURI) {
      throw new AdyenKycSdkError("No redirect_uri present");
    }
    const redirectUrl = new URL(redirectURI);
    const redirectQueryParams = redirectUrl.searchParams;
    redirectUrl.pathname = redirectUrl.pathname.replace(
      RegExp(`(${this.vendor})$`, "i"),
      "$1/json"
    );
    redirectQueryParams.set("state", this.iframeUrlState);
    switch (jsonData.type) {
      case "account_verification_report_id":
        redirectQueryParams.set("account_verification_report_id", jsonData.data);
        try {
          const responseData = await httpPost({
            ...httpOptions,
            path: redirectUrl.href
          });
          if (isVerifiedAccountsData(responseData)) return responseData;
          throw responseData;
        } catch (reason) {
          throw new AdyenKycSdkError("WIDGET_ACCOUNT_COMMIT_FAILURE", reason);
        }
      case "error": {
        let { message } = jsonData.error;
        const { status: error, reason, trackingId, type } = jsonData.error;
        redirectQueryParams.set("error", error);
        redirectQueryParams.set("message", message);
        redirectQueryParams.set("error_type", type);
        redirectQueryParams.set("error_reason", reason);
        redirectQueryParams.set("tracking_id", trackingId);
        try {
          const responseData = await httpPost({ ...httpOptions, path: redirectUrl.href });
          if (isValidErrorResponse(responseData)) {
            message = responseData.errorMessage;
          }
        } catch (ex) {
          logger.error(ex);
        }
        throw new AdyenKycSdkError(reason, jsonData.error);
      }
    }
  }
  unmount() {
    if (this.mountInProgress) {
      throw new AdyenKycSdkError("Cannot unmount widget, mounting is still in progress");
    }
    this.removeMessageEventListener();
    removeElementSiblings(this.iframeElement);
    activeWidget = null;
  }
  async mount() {
    if (activeWidget) {
      throw new AdyenKycSdkError(
        `You can only have one ${this.constructor.name} mounted at a time`
      );
    }
    activeWidget = this;
    if (this.mountInProgress) {
      throw new AdyenKycSdkError("Cannot mount widget, mounting is already in progress");
    }
    this.mountInProgress = true;
    try {
      await new Promise((resolve, reject) => {
        const timeoutId = setTimeout(() => {
          this.mountInProgress = false;
          reject(new AdyenKycSdkError("WIDGET_TIMEOUT"));
        }, MOUNT_TIMEOUT);
        const cancelTimeout = () => {
          if (timeoutId) clearTimeout(timeoutId);
        };
        this.iframeElement.addEventListener("load", () => {
          cancelTimeout();
          this.mountInProgress = false;
          resolve();
        });
        requestAnimationFrame(() => {
          try {
            if (this.vendor === TINK_VENDOR) {
              this.iframeUrl.searchParams.set("iframe", "true");
              this.iframeUrlState = decodeURIComponent(
                this.iframeUrl.searchParams.get("state") ?? ""
              );
              this.iframeUrl.searchParams.delete("state");
            }
            this.iframeElement.setAttribute("src", this.iframeUrl.href);
          } catch (ex) {
            cancelTimeout();
            this.mountInProgress = false;
            reject(ex);
          }
        });
      });
    } catch (err) {
      throw new AdyenKycSdkError("WIDGET_LAUNCH_FAILED", err);
    }
  }
  waitForResponse = async () => new Promise((resolve, reject) => {
    this.listener = async (message) => {
      try {
        const result = await this.handleMessage(message);
        if (!result) return;
        resolve(result);
      } catch (err) {
        reject(err);
      }
    };
    window.addEventListener("message", this.listener);
  });
  async mountAndWaitForResponse() {
    await this.mount();
    try {
      return await this.waitForResponse();
    } finally {
      this.removeMessageEventListener();
    }
  }
}
export {
  IFrameWidget as I,
  omitObscuredFieldsIfUnchanged as o
};
