@tonder.io/ionic-lite-sdk 0.0.68 → 0.0.69-beta.TEC-192.ee4f7cd

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,11 @@
1
1
  import { ErrorResponse } from "./errorResponse";
2
2
  import { BaseInlineCheckout } from "./BaseInlineCheckout";
3
3
  import { APM, IInlineLiteCheckoutOptions } from "../types/commons";
4
- import { ICustomerCardsResponse, IMountCardFieldsRequest, ISaveCardRequest, ISaveCardResponse } from "../types/card";
4
+ import { ICustomerCardsResponse, IMountCardFieldsRequest, IRevealCardFieldsRequest, ISaveCardResponse } from "../types/card";
5
5
  import { IPaymentMethod } from "../types/paymentMethod";
6
6
  import { CreateOrderResponse, CreatePaymentResponse, CustomerRegisterResponse, GetBusinessResponse, RegisterCustomerCardResponse, StartCheckoutResponse } from "../types/responses";
7
7
  import { CreateOrderRequest, CreatePaymentRequest, RegisterCustomerCardRequest, StartCheckoutFullRequest, StartCheckoutIdRequest, StartCheckoutRequest, TokensRequest } from "../types/requests";
8
- import { ICardFields, IStartCheckoutResponse } from "../types/checkout";
8
+ import { IStartCheckoutResponse } from "../types/checkout";
9
9
  import { ILiteCheckout } from "../types/liteInlineCheckout";
10
10
  declare global {
11
11
  interface Window {
@@ -18,15 +18,35 @@ export declare class LiteCheckout extends BaseInlineCheckout implements ILiteChe
18
18
  private readonly events;
19
19
  private mountedElementsByContext;
20
20
  private customerCardsCache;
21
+ private lastCollectedTokens;
21
22
  constructor({ apiKey, mode, returnUrl, callBack, apiKeyTonder, baseUrlTonder, customization, collectorIds, events }: IInlineLiteCheckoutOptions);
22
23
  injectCheckout(): Promise<void>;
23
24
  getCustomerCards(): Promise<ICustomerCardsResponse>;
24
- saveCustomerCard(card: ISaveCardRequest): Promise<ISaveCardResponse>;
25
+ saveCustomerCard(): Promise<ISaveCardResponse>;
25
26
  removeCustomerCard(skyflowId: string): Promise<string>;
26
27
  getCustomerPaymentMethods(): Promise<IPaymentMethod[]>;
27
28
  mountCardFields(event: IMountCardFieldsRequest): Promise<void>;
28
29
  private getContainerByCardId;
29
30
  private collectCardTokens;
31
+ /**
32
+ * Collects card tokens from Skyflow Elements mounted for a new card (the 'create' context).
33
+ * Requires that `mountCardFields()` was called without a `card_id` beforehand.
34
+ */
35
+ private collectCreateCardTokens;
36
+ /**
37
+ * Reveals card data collected in the last `saveCustomerCard()` or `payment()` call
38
+ * (with a new card) in developer-provided `<div>` containers using Skyflow Reveal Elements.
39
+ *
40
+ * Must be called **after** a successful `saveCustomerCard()` or `payment()` that processed
41
+ * a new card (i.e., without a saved-card `skyflow_id`). Skyflow Reveal Elements render the
42
+ * actual (or masked) values inside secure iframes without exposing them to the application.
43
+ *
44
+ * Default container IDs: `#reveal_<field>` (e.g. `#reveal_card_number`).
45
+ * Default redaction: `MASKED` for card_number, `REDACTED` for cvv, `PLAIN_TEXT` for others.
46
+ *
47
+ * @param request - Fields to reveal and optional per-field styles/redaction/altText.
48
+ */
49
+ revealCardFields(request: IRevealCardFieldsRequest): Promise<void>;
30
50
  unmountCardFields(context?: string): void;
31
51
  /**
32
52
  * Internal helper to unmount elements from a specific context
@@ -39,7 +59,7 @@ export declare class LiteCheckout extends BaseInlineCheckout implements ILiteChe
39
59
  getSkyflowTokens({ vault_id, vault_url, data, }: TokensRequest): Promise<any | ErrorResponse>;
40
60
  _setCartTotal(total: string): void;
41
61
  _checkout({ card, payment_method, isSandbox, returnUrl: returnUrlData }: {
42
- card?: ICardFields | string;
62
+ card?: string;
43
63
  payment_method?: string;
44
64
  isSandbox?: boolean;
45
65
  returnUrl?: string;
@@ -2,15 +2,14 @@ import Skyflow from "skyflow-js";
2
2
  import CollectContainer from "skyflow-js/types/core/external/collect/collect-container";
3
3
  import CollectElement from "skyflow-js/types/core/external/collect/collect-element";
4
4
  import { TokensSkyflowRequest } from "../types/requests";
5
- import { IMountCardFieldsRequest } from "../types/card";
5
+ import { IMountCardFieldsRequest, IRevealCardFieldsRequest } from "../types/card";
6
6
  import { IEvents, ILiteCustomizationOptions } from "../types/commons";
7
7
  /**
8
- * [DEPRECATION WARNING]
9
- * This function should be deprecated in favor of using mountSkyflowFields for security,
10
- * to prevent users from creating their own inputs.
8
+ * @deprecated This function is deprecated and will be removed in a future release.
9
+ * Use `mountCardFields()` to render Skyflow Elements and collect card data securely.
11
10
  */
12
11
  export declare function getSkyflowTokens({ baseUrl, apiKey, vault_id, vault_url, data, }: TokensSkyflowRequest): Promise<any>;
13
- export declare function initSkyflowInstance({ baseUrl, apiKey, vault_id, vault_url, }: TokensSkyflowRequest): Promise<Skyflow>;
12
+ export declare function initSkyflowInstance({ baseUrl, apiKey, vault_id, vault_url, mode, }: TokensSkyflowRequest): Promise<Skyflow>;
14
13
  export declare function mountSkyflowFields(event: {
15
14
  skyflowInstance: Skyflow;
16
15
  data: IMountCardFieldsRequest;
@@ -20,3 +19,8 @@ export declare function mountSkyflowFields(event: {
20
19
  elements: CollectElement[];
21
20
  container: CollectContainer;
22
21
  }>;
22
+ export declare function mountRevealFields(event: {
23
+ skyflowInstance: Skyflow;
24
+ tokens: Record<string, string>;
25
+ request: IRevealCardFieldsRequest;
26
+ }): Promise<void>;
package/dist/index.d.ts CHANGED
@@ -3,4 +3,5 @@ import { BaseInlineCheckout } from './classes/BaseInlineCheckout';
3
3
  import { SdkTelemetryClient } from './helpers/SdkTelemetryClient';
4
4
  import { AppError } from './shared/utils/appError';
5
5
  import { validateCVV, validateCardNumber, validateExpirationMonth, validateCardholderName, validateExpirationYear } from './helpers/validations';
6
+ export type { IRevealCardFieldsRequest, IRevealCardField, IRevealElementStyles, IRevealElementInputStyles, RevealableCardField, } from './types/card';
6
7
  export { LiteCheckout, BaseInlineCheckout, SdkTelemetryClient, AppError, validateCVV, validateCardNumber, validateCardholderName, validateExpirationMonth, validateExpirationYear };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{get as e}from"lodash";import t from"skyflow-js";function r(e,t,r,o){return new(r||(r=Promise))((function(n,i){function s(e){try{d(o.next(e))}catch(e){i(e)}}function a(e){try{d(o.throw(e))}catch(e){i(e)}}function d(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}d((o=o.apply(e,t||[])).next())}))}function o(e,t,r,o){if("a"===r&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?o:"a"===r?o.call(e):o?o.value:t.get(e)}function n(e,t,r,o,n){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?n.call(e,r):n?n.value=r:t.set(e,r),r}function i(e,t,o){return r(this,void 0,void 0,(function*(){const r=yield fetch(`${e}/api/v1/payments/business/${t}`,{headers:{Authorization:`Token ${t}`},signal:o});return yield r.json()}))}var s;"function"==typeof SuppressedError&&SuppressedError,function(e){e.INIT_ERROR="INIT_ERROR",e.CREATE_ERROR="CREATE_ERROR",e.REMOVE_SDK_ERROR="REMOVE_SDK_ERROR",e.INVALID_TYPE="INVALID_TYPE",e.STATE_ERROR="STATE_ERROR",e.FETCH_BUSINESS_ERROR="FETCH_BUSINESS_ERROR",e.INVALID_CONFIG="INVALID_CONFIG",e.MERCHANT_CREDENTIAL_REQUIRED="MERCHANT_CREDENTIAL_REQUIRED",e.INVALID_PAYMENT_REQUEST="INVALID_PAYMENT_REQUEST",e.INVALID_PAYMENT_REQUEST_CARD_PM="INVALID_PAYMENT_REQUEST_CARD_PM",e.TYPE_SDK_REQUIRED="TYPE_SDK_REQUIRED",e.ENVIRONMENT_REQUIRED="ENVIRONMENT_REQUIRED",e.FETCH_CARDS_ERROR="FETCH_CARDS_ERROR",e.FETCH_TRANSACTION_ERROR="FETCH_TRANSACTION_ERROR",e.CUSTOMER_AUTH_TOKEN_NOT_VALID="CUSTOMER_AUTH_TOKEN_NOT_VALID",e.SAVE_CARD_ERROR="SAVE_CARD_ERROR",e.REMOVE_CARD_ERROR="REMOVE_CARD_ERROR",e.SUMMARY_CARD_ERROR="SUMMARY_CARD_ERROR",e.CREATE_PAYMENT_ERROR="CREATE_PAYMENT_ERROR",e.PAYMENT_PROCESS_ERROR="PAYMENT_PROCESS_ERROR",e.INVALID_CARD_DATA="INVALID_CARD_DATA",e.SAVE_CARD_PROCESS_ERROR="SAVE_CARD_PROCESS_ERROR",e.START_CHECKOUT_ERROR="START_CHECKOUT_ERROR",e.CREATE_ORDER_ERROR="CREATE_ORDER_ERROR",e.BUSINESS_ID_REQUIRED="BUSINESS_ID_REQUIRED",e.CLIENT_ID_REQUIRED="CLIENT_ID_REQUIRED",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INVALID_ITEMS="INVALID_ITEMS",e.CUSTOMER_OPERATION_ERROR="CUSTOMER_OPERATION_ERROR",e.INVALID_EMAIL="INVALID_EMAIL",e.FETCH_PAYMENT_METHODS_ERROR="FETCH_PAYMENT_METHODS_ERROR",e.INVALID_VAULT_TOKEN="INVALID_VAULT_TOKEN",e.VAULT_TOKEN_ERROR="VAULT_TOKEN_ERROR",e.SECURE_TOKEN_ERROR="SECURE_TOKEN_ERROR",e.SECURE_TOKEN_INVALID="SECURE_TOKEN_INVALID",e.INVALID_SECRET_API_KEY="INVALID_SECRET_API_KEY",e.REMOVE_CARD="REMOVE_CARD",e.SKYFLOW_NOT_INITIALIZED="SKYFLOW_NOT_INITIALIZED",e.ERROR_LOAD_PAYMENT_FORM="ERROR_LOAD_PAYMENT_FORM",e.ERROR_LOAD_ENROLLMENT_FORM="ERROR_LOAD_ENROLLMENT_FORM",e.MOUNT_COLLECT_ERROR="MOUNT_COLLECT_ERROR",e.CARD_ON_FILE_DECLINED="CARD_ON_FILE_DECLINED",e.CARD_SAVED_SUCCESSFULLY="CARD_SAVED_SUCCESSFULLY",e.CARD_REMOVED_SUCCESSFULLY="CARD_REMOVED_SUCCESSFULLY",e.REQUEST_ABORTED="REQUEST_ABORTED",e.REQUEST_FAILED="REQUEST_FAILED",e.UNKNOWN_ERROR="UNKNOWN_ERROR",e.THREEDS_REDIRECTION_ERROR="THREEDS_REDIRECTION_ERROR"}(s||(s={}));const a={[s.INIT_ERROR]:"Error initializing the SDK.",[s.INVALID_TYPE]:"SDK Type invalid.",[s.STATE_ERROR]:"Error updating SDK state.",[s.FETCH_BUSINESS_ERROR]:"Error retrieving merchant information.",[s.INVALID_CONFIG]:"Required configuration options.",[s.MERCHANT_CREDENTIAL_REQUIRED]:"Merchant credential required.",[s.INVALID_PAYMENT_REQUEST]:"The payment data must be of type: :::interface:::.",[s.INVALID_PAYMENT_REQUEST_CARD_PM]:"The fields card and payment_method cannot be provided together.",[s.TYPE_SDK_REQUIRED]:"SDK type required.",[s.ENVIRONMENT_REQUIRED]:"Environment required.",[s.FETCH_CARDS_ERROR]:"Error retrieving cards.",[s.CUSTOMER_AUTH_TOKEN_NOT_VALID]:"The customer's auth token is invalid. Please verify that the customer's data was provided when creating the SDK (sdk.create) and try again.",[s.SAVE_CARD_ERROR]:"Error saving the card.",[s.REMOVE_CARD_ERROR]:"Error deleting the card.",[s.CREATE_PAYMENT_ERROR]:"Error creating the payment.",[s.PAYMENT_PROCESS_ERROR]:"There was an issue processing the payment.",[s.CARD_SAVED_SUCCESSFULLY]:"Card saved successfully.",[s.CARD_REMOVED_SUCCESSFULLY]:"Card deleted successfully.",[s.SAVE_CARD_PROCESS_ERROR]:"Error processing card data.",[s.START_CHECKOUT_ERROR]:"Error processing the payment.",[s.CREATE_ORDER_ERROR]:"Error creating the order.",[s.BUSINESS_ID_REQUIRED]:"Business ID is required.",[s.CLIENT_ID_REQUIRED]:"Client ID is required.",[s.INVALID_AMOUNT]:"Invalid amount.",[s.INVALID_ITEMS]:"Invalid items.",[s.CUSTOMER_OPERATION_ERROR]:"Error registering or fetching customer",[s.INVALID_EMAIL]:"Invalid email.",[s.FETCH_PAYMENT_METHODS_ERROR]:"Error retrieving active payment methods.",[s.INVALID_VAULT_TOKEN]:"An invalid vault token response was received.",[s.VAULT_TOKEN_ERROR]:"Error retrieving the vault token.",[s.SECURE_TOKEN_ERROR]:"Error getting secure token.",[s.SECURE_TOKEN_INVALID]:"Invalid secure token.",[s.INVALID_SECRET_API_KEY]:"SECRET API KEY is required.",[s.REMOVE_CARD]:"Card deleted successfully",[s.SKYFLOW_NOT_INITIALIZED]:"Skyflow not initialized.",[s.ERROR_LOAD_PAYMENT_FORM]:"There was an issue loading the payment form.",[s.INVALID_CARD_DATA]:"Invalid card data.",[s.ERROR_LOAD_ENROLLMENT_FORM]:"There was an issue loading the card form.",[s.MOUNT_COLLECT_ERROR]:"Mount failed. Make sure all inputs are complete and valid.",[s.CARD_ON_FILE_DECLINED]:"Transaction declined. Please verify your card details.",[s.REQUEST_ABORTED]:"Requests canceled.",[s.REQUEST_FAILED]:"Request failed.",[s.UNKNOWN_ERROR]:"An unexpected error occurred.",[s.CREATE_ERROR]:"Error creating the SDK.",[s.FETCH_TRANSACTION_ERROR]:"Error retrieving the transaction.",[s.THREEDS_REDIRECTION_ERROR]:"Ocurrió un error durante la redirección de 3DS.",[s.REMOVE_SDK_ERROR]:"Ocurrió un error removiendo la instancia del SDK."};s.INIT_ERROR,s.STATE_ERROR,s.FETCH_BUSINESS_ERROR,s.INVALID_CONFIG,s.TYPE_SDK_REQUIRED,s.ENVIRONMENT_REQUIRED,s.FETCH_CARDS_ERROR,s.SAVE_CARD_ERROR,s.REMOVE_CARD_ERROR,s.CREATE_PAYMENT_ERROR,s.START_CHECKOUT_ERROR,s.CREATE_ORDER_ERROR,s.BUSINESS_ID_REQUIRED,s.CLIENT_ID_REQUIRED,s.INVALID_AMOUNT,s.INVALID_ITEMS,s.CUSTOMER_OPERATION_ERROR,s.INVALID_EMAIL,s.FETCH_PAYMENT_METHODS_ERROR,s.INVALID_VAULT_TOKEN,s.VAULT_TOKEN_ERROR,s.SECURE_TOKEN_ERROR,s.INVALID_SECRET_API_KEY,s.CUSTOMER_AUTH_TOKEN_NOT_VALID,s.SECURE_TOKEN_INVALID,s.REMOVE_CARD,s.SKYFLOW_NOT_INITIALIZED,s.INVALID_TYPE,s.PAYMENT_PROCESS_ERROR,s.INVALID_PAYMENT_REQUEST,s.INVALID_PAYMENT_REQUEST_CARD_PM,s.SAVE_CARD_PROCESS_ERROR,s.ERROR_LOAD_PAYMENT_FORM,s.INVALID_CARD_DATA,s.ERROR_LOAD_ENROLLMENT_FORM,s.MOUNT_COLLECT_ERROR,s.CARD_ON_FILE_DECLINED,s.CARD_SAVED_SUCCESSFULLY,s.CARD_REMOVED_SUCCESSFULLY,s.REQUEST_ABORTED,s.REQUEST_FAILED,s.UNKNOWN_ERROR,s.CREATE_ERROR,s.FETCH_TRANSACTION_ERROR,s.THREEDS_REDIRECTION_ERROR,s.REMOVE_SDK_ERROR;class d extends Error{constructor(e){var t,r;const o=e.message||a[e.code]||"Unknown error";super(o),this.name="TonderError",this.code=e.code,this.details={code:(null===(t=e.details)||void 0===t?void 0:t.code)||e.code,message:(null===(r=e.details)||void 0===r?void 0:r.message)||o}}}const l=()=>({javascript_enabled:!0,time_zone:(new Date).getTimezoneOffset(),language:navigator.language||"en-US",color_depth:window.screen?window.screen.colorDepth:null,screen_width:window.screen?window.screen.width*window.devicePixelRatio||window.screen.width:null,screen_height:window.screen?window.screen.height*window.devicePixelRatio||window.screen.height:null,user_agent:navigator.userAgent}),c=e=>{var t;return e&&"business"in e?null===(t=null==e?void 0:e.business)||void 0===t?void 0:t.pk:""},u="__tonderLockErrorCode__";function h(e){return"object"==typeof e&&null!==e}class _ extends Error{constructor(e){var t,r;const o=_.resolveStatusCode(e.statusCode,e.originalError),n=_.resolveMessage(e.errorCode,e.message),i=_.resolveSystemError(null===(t=e.details)||void 0===t?void 0:t.systemError,e.originalError);super(n),this.status="error",Object.setPrototypeOf(this,new.target.prototype),this.name="TonderError",this.code=e.errorCode,this.statusCode=o,this.originalError=e.originalError,this.details={code:e.errorCode,statusCode:o,systemError:i},e.lockErrorCode&&Object.defineProperty(this,u,{value:!0,enumerable:!1,configurable:!0}),null===(r=Error.captureStackTrace)||void 0===r||r.call(Error,this,_)}static isRecord(e){return"object"==typeof e&&null!==e}static parseStatusCode(e){const t=Number(e);return Number.isFinite(t)?t<100||t>599?500:Math.trunc(t):500}static resolveStatusCode(e,t){const r=[e];if(_.isRecord(t)){r.push(t.statusCode,t.status);const e=_.isRecord(t.body)?t.body:null;e&&r.push(e.statusCode,e.status)}for(const e of r)if(_.isHttpStatusCode(e))return Math.trunc(Number(e));return 500}static resolveMessage(e,t){return t||(a[e]||a[s.UNKNOWN_ERROR]||"An unexpected error occurred.")}static isHttpStatusCode(e){const t=Number(e);return Number.isFinite(t)&&t>=100&&t<=599}static normalizeSystemError(e){if("string"!=typeof e)return null;return e.trim()||null}static resolveSystemError(e,t){const r=[e];if(_.isRecord(t)){const e=_.isRecord(t.details)?t.details:null,o=_.isRecord(t.body)?t.body:null,n=o&&_.isRecord(o.details)?o.details:null;r.push(t.systemError,t.code,null==e?void 0:e.systemError,null==e?void 0:e.code,null==o?void 0:o.systemError,null==o?void 0:o.code,null==n?void 0:n.systemError,null==n?void 0:n.code)}for(const e of r){const t=_.normalizeSystemError(e);if(t)return t}return"APP_INTERNAL_001"}}function E(e){return h(e)&&!0===e[u]}function p(e){return e instanceof _&&void 0!==e.originalError?e.originalError:e}function m(e,t){var r;if(!(null==e?void 0:e.errorCode))throw new Error("buildPublicAppError requires errorCode");const o=null===(r=e.details)||void 0===r?void 0:r.systemError,n=!!e.message||void 0!==e.statusCode||void 0!==o;return!function(e){return h(e)&&"TonderError"===e.name&&"string"==typeof e.code}(t)||(e.lockErrorCode&&function(e){Object.defineProperty(e,u,{value:!0,enumerable:!1,configurable:!0})}(t),n||e.errorCode!==t.code&&!E(t))?new _({errorCode:e.errorCode,message:e.message,statusCode:e.statusCode,details:void 0!==o?{systemError:o}:void 0,originalError:p(t),lockErrorCode:e.lockErrorCode||E(t)}):t}function R(e){var t,o;return r(this,void 0,void 0,(function*(){const n=yield function(e){return r(this,void 0,void 0,(function*(){try{return yield e.clone().json()}catch(e){}try{return(yield e.text())||void 0}catch(e){return}}))}(e.response),i={status:e.response.status};return e.response.statusText&&(i.statusText=e.response.statusText),void 0!==n&&(i.body=n),new _({errorCode:e.errorCode,message:e.message,statusCode:null!==(t=e.statusCode)&&void 0!==t?t:e.response.status,details:void 0!==(null===(o=e.details)||void 0===o?void 0:o.systemError)?{systemError:e.details.systemError}:void 0,originalError:i,lockErrorCode:e.lockErrorCode})}))}function y(e,t){return(null==e?void 0:e.response)?R(e):m(e,t)}class v{constructor({payload:e=null,apiKey:t,baseUrl:r,redirectOnComplete:o,tdsIframeId:n,tonderPayButtonId:i,callBack:s}){this.localStorageKey="verify_transaction_status_url",this.setPayload=e=>{this.payload=e},this.baseUrl=r,this.apiKey=t,this.payload=e,this.tdsIframeId=n,this.tonderPayButtonId=i,this.redirectOnComplete=o,this.callBack=s}setStorageItem(e){return localStorage.setItem(this.localStorageKey,JSON.stringify(e))}getStorageItem(){return localStorage.getItem(this.localStorageKey)}removeStorageItem(){return localStorage.removeItem(this.localStorageKey)}saveVerifyTransactionUrl(){var e,t,r,o,n,i;const s=null===(r=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===r?void 0:r.verify_transaction_status_url;if(s)this.saveUrlWithExpiration(s);else{const e=null===(i=null===(n=null===(o=this.payload)||void 0===o?void 0:o.next_action)||void 0===n?void 0:n.iframe_resources)||void 0===i?void 0:i.verify_transaction_status_url;e?this.saveUrlWithExpiration(e):console.log("No verify_transaction_status_url found")}}saveUrlWithExpiration(e){try{const t={url:e,expires:(new Date).getTime()+12e5};this.setStorageItem(t)}catch(e){console.log("error: ",e)}}getUrlWithExpiration(){const e=this.getStorageItem();if(e){const t=JSON.parse(e);if(!t)return;return(new Date).getTime()>t.expires?(this.removeVerifyTransactionUrl(),null):t.url}return null}removeVerifyTransactionUrl(){return this.removeStorageItem()}getVerifyTransactionUrl(){return this.getStorageItem()}loadIframe(){var e,t,r;if(null===(r=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===r?void 0:r.iframe)return new Promise(((e,t)=>{var r,o,n;const i=null===(n=null===(o=null===(r=this.payload)||void 0===r?void 0:r.next_action)||void 0===o?void 0:o.iframe_resources)||void 0===n?void 0:n.iframe;if(i){this.saveVerifyTransactionUrl();const r=document.createElement("div");r.innerHTML=i,document.body.appendChild(r);const o=document.createElement("script");o.textContent='document.getElementById("tdsMmethodForm").submit();',r.appendChild(o);const n=document.getElementById("tdsMmethodTgtFrame");n?n.onload=()=>e(!0):(console.log("No redirection found"),t(!1))}else console.log("No redirection found"),t(!1)}))}getRedirectUrl(){var e,t,r;return null===(r=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===r?void 0:r.url}redirectToChallenge(){const e=this.getRedirectUrl();if(e)if(this.saveVerifyTransactionUrl(),this.redirectOnComplete)window.location=e;else{const t=document.querySelector(`#${this.tdsIframeId}`);if(t){t.setAttribute("src",e),t.setAttribute("style","display: block");const o=this,n=e=>r(this,void 0,void 0,(function*(){const e=()=>{try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}t&&t.setAttribute("style","display: none"),o.callBack&&o.callBack(o.payload),t.removeEventListener("load",n)},i=t=>r(this,void 0,void 0,(function*(){const n=yield new Promise(((e,r)=>e(t)));if(n){if((e=>"Pending"!==(null==e?void 0:e.transaction_status))(n))return e();{const e=setTimeout((()=>r(this,void 0,void 0,(function*(){clearTimeout(e),yield i(o.requestTransactionStatus())}))),7e3)}}}));yield i(o.requestTransactionStatus())}));t.addEventListener("load",n)}else console.log("No iframe found")}else this.callBack&&this.callBack(this.payload)}requestTransactionStatus(){return r(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration(),t=e.startsWith("https://")?e:`${this.baseUrl}${e}`,r=yield fetch(t,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});if(200!==r.status)return console.error("La verificación de la transacción falló."),null;return yield r.json()}))}getURLParameters(){const e={},t=new URLSearchParams(window.location.search);for(const[r,o]of t)e[r]=o;return e}handleSuccessTransaction(e){return this.removeVerifyTransactionUrl(),e}handleDeclinedTransaction(e){return this.removeVerifyTransactionUrl(),e}handle3dsChallenge(e){return r(this,void 0,void 0,(function*(){const t=document.createElement("form");t.name="frm",t.method="POST",t.action=e.redirect_post_url;const r=document.createElement("input");r.type="hidden",r.name=e.creq,r.value=e.creq,t.appendChild(r);const o=document.createElement("input");o.type="hidden",o.name=e.term_url,o.value=e.TermUrl,t.appendChild(o),document.body.appendChild(t),t.submit(),yield this.verifyTransactionStatus()}))}handleTransactionResponse(e){return r(this,void 0,void 0,(function*(){const t=yield e.json();return"Pending"===t.status&&t.redirect_post_url?yield this.handle3dsChallenge(t):["Success","Authorized"].includes(t.status)?this.handleSuccessTransaction(t):(this.handleDeclinedTransaction(e),t)}))}verifyTransactionStatus(){return r(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration();if(e){const t=e.startsWith("https://")?e:`${this.baseUrl}${e}`;try{const e=yield fetch(t,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});return 200!==e.status?(console.error("La verificación de la transacción falló."),this.removeVerifyTransactionUrl(),e):yield this.handleTransactionResponse(e)}catch(e){console.error("Error al verificar la transacción:",e),this.removeVerifyTransactionUrl()}}else console.log("No verify_transaction_status_url found")}))}}const f=Object.freeze({production:"https://app.tonder.io",sandbox:"https://sandbox.tonder.io",stage:"https://stage.tonder.io",development:"http://localhost:8000"});function A(e,t,o){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/checkout-router/`,n=o,i=yield fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(Object.assign(Object.assign({},n),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}))});if(i.ok)return yield i.json();throw yield y({response:i,errorCode:s.START_CHECKOUT_ERROR})}))}function C(e,t,o=!0,n=null){return r(this,void 0,void 0,(function*(){let r=yield window.OpenPay;return r.setId(e),r.setApiKey(t),r.setSandboxMode(o),yield r.deviceData.setup({signal:n})}))}const O=Object.freeze({production:"https://api.tonder.io",sandbox:"https://api-stage.tonder.io",stage:"https://api-stage.tonder.io",development:"https://api-stage.tonder.io"}),T=Object.freeze({TELEMETRY:"/telemetry/v1/events",ACQ_SUBSCRIPTION_TOKEN:"/acq-kushki/subscription/token",ACQ_SUBSCRIPTION_CREATE:"/acq-kushki/subscription/create"});function g(e="stage"){return`${O[e]}${T.TELEMETRY}`}const I="https://cdn.kushkipagos.com/kushki.min.js",S=s.CARD_ON_FILE_DECLINED;let N=!1,D=null;class b{constructor(e){var t;this.acquirerInstance=null,this.isTestEnvironment=null===(t=e.isTestEnvironment)||void 0===t||t;const r=this.isTestEnvironment?"stage":"production";this.apiUrl=function(e="stage"){return O[e]}(r),this.merchantId=e.merchantId,this.apiKey=e.apiKey}initialize(){return r(this,void 0,void 0,(function*(){yield function(){return r(this,void 0,void 0,(function*(){return N?Promise.resolve():D||(D=new Promise(((e,t)=>{if(document.querySelector(`script[src="${I}"]`))return N=!0,void e();const r=document.createElement("script");r.src=I,r.async=!0,r.onload=()=>{N=!0,e()},r.onerror=()=>{D=null,t(y({errorCode:S,lockErrorCode:!0,details:{step:"load_acquirer_script",message:"Failed to load acquirer script"}}))},document.head.appendChild(r)})),D)}))}(),this.acquirerInstance=function(e,t){if(!window.Kushki)throw y({errorCode:S,lockErrorCode:!0,details:{step:"create_acquirer_instance",message:"Acquirer script not loaded. Call initialize() first."}});return new window.Kushki({merchantId:e,inTestEnvironment:t})}(this.merchantId,this.isTestEnvironment)}))}getAcquirerInstance(){if(!this.acquirerInstance)throw y({errorCode:S,lockErrorCode:!0,details:{step:"get_acquirer_instance",message:"CardOnFile not initialized. Call initialize() first."}});return this.acquirerInstance}getJwt(e){return r(this,void 0,void 0,(function*(){const t=this.getAcquirerInstance();return new Promise(((r,o)=>{t.requestSecureInit({card:{number:e}},(e=>{if("code"in e&&e.code)return void o(y({errorCode:S,lockErrorCode:!0,details:{step:"get_jwt",acquirerResponse:e}}));const t=e;t.jwt?r(t.jwt):o(y({errorCode:S,lockErrorCode:!0,details:{step:"get_jwt",message:"No JWT returned from acquirer",acquirerResponse:t}}))}))}))}))}generateToken(e){return r(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}${T.ACQ_SUBSCRIPTION_TOKEN}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`},body:JSON.stringify(e)});if(!t.ok)throw yield y({response:t,errorCode:S,lockErrorCode:!0,details:{step:"generate_token"}});return t.json()}))}createSubscription(e){return r(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}${T.ACQ_SUBSCRIPTION_CREATE}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`},body:JSON.stringify(e)});if(!t.ok)throw yield y({response:t,errorCode:S,lockErrorCode:!0,details:{step:"create_subscription"}});return t.json()}))}validate3DS(e,t){return r(this,void 0,void 0,(function*(){const r=this.getAcquirerInstance();return new Promise(((o,n)=>{r.requestValidate3DS({secureId:e,security:t},(e=>{const t=e;t.code&&"3DS000"!==t.code?n(y({errorCode:S,lockErrorCode:!0,details:{step:"validate_3ds",message:"3DS validation failed",acquirerResponse:t}})):!1!==t.isValid?o(!0):n(y({errorCode:S,lockErrorCode:!0,details:{step:"validate_3ds",message:"3DS validation failed",acquirerResponse:t}}))}))}))}))}process(e){var t,o;return r(this,void 0,void 0,(function*(){const r=yield this.getJwt(e.cardBin),n=yield this.generateToken({card:e.cardTokens,currency:e.currency,jwt:r}),i=n.secureId||(null===(t=n.details)||void 0===t?void 0:t.secureId),s=n.security||(null===(o=n.details)||void 0===o?void 0:o.security);if(!i||!s)throw y({errorCode:S,lockErrorCode:!0,details:{step:"process",message:"Missing secureId or security in token response",tokenResponse:n}});return yield this.validate3DS(i,s),this.createSubscription({token:n.token,contactDetails:e.contactDetails,metadata:{customerId:e.customerId},currency:e.currency})}))}}class M{constructor(e){this.REQUEST_TIMEOUT_MS=5e3,this.MAX_MESSAGE_LENGTH=500,this.config=e}captureException(e,t){try{const r=this.buildEvent(e,t||{});this.sendEvent(r)}catch(e){}}extractErrorInfo(e){try{if(e instanceof Error)return{name:e.name||"Error",message:this.truncate(e.message||"Unknown error",this.MAX_MESSAGE_LENGTH),stack:e.stack||void 0};const t=this.safeStringify(e);return{name:"NonErrorException",message:this.truncate(t,this.MAX_MESSAGE_LENGTH),stack:void 0}}catch(e){return{name:"SerializationError",message:"Failed to serialize error",stack:void 0}}}safeStringify(e){try{const t=new WeakSet;return JSON.stringify(e,((e,r)=>{if("object"==typeof r&&null!==r){if(t.has(r))return"[Circular]";t.add(r)}return r}))}catch(t){return String(e)}}buildEvent(e,t){const r=this.extractErrorInfo(e),o=Object.assign({},t.metadata||{});void 0===o.error&&(o.error=e),"undefined"!=typeof window&&(o.url=window.location.href);const n={platform:this.config.platform,platform_version:this.config.platform_version,env:this.config.mode,feature:t.feature||"unknown",level:"error",message:r.message,name:r.name,metadata:o};return t.tenant_id&&(n.tenant_id=t.tenant_id),t.request_id&&(n.request_id=t.request_id),t.process_id&&(n.process_id=t.process_id),t.user_id&&(n.user_id=t.user_id),r.stack&&(n.stack=r.stack),t.error_code&&(n.error_code=t.error_code),t.http_status&&(n.http_status=t.http_status),n}truncate(e,t){return e.length<=t?e:e.substring(0,t)+"..."}sendEvent(e){this.sendHttpRequest(e).then((()=>{})).catch((()=>{}))}sendHttpRequest(e){return r(this,void 0,void 0,(function*(){try{const t=JSON.stringify(e),r=new AbortController,o=setTimeout((()=>r.abort()),this.REQUEST_TIMEOUT_MS);try{const e=yield fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.config.apiKey}`},body:t,keepalive:!0,signal:r.signal});return clearTimeout(o),e.ok}catch(e){return clearTimeout(o),!1}}catch(e){return!1}}))}}const k=Object.freeze({name:"@tonder.io/ionic-lite-sdk",version:"0.0.68"});var U,L,P,w,j,V,K,F,x,B,Y,$,H;class z{constructor({mode:e="stage",customization:t,apiKey:r,apiKeyTonder:o,returnUrl:n,tdsIframeId:i,callBack:s=(()=>{}),baseUrlTonder:a,tonderPayButtonId:d,sdkInfo:l}){U.add(this),this.baseUrl="",this.cartTotal="0",this.secureToken="",this.customization={redirectOnComplete:!0},this.metadata={},this.order_reference=null,this.card={},this.currency="",this.cardOnFileInstance=null,L.set(this,void 0),P.set(this,void 0),this.apiKeyTonder=o||r||"",this.returnUrl=n,this.callBack=s,this.mode=e,this.customer={},this.baseUrl=a||f[this.mode]||f.stage,this.abortController=new AbortController,this.requestId=this.generateRequestId(),this.customization=Object.assign(Object.assign({},this.customization),t||{}),this.process3ds=new v({apiKey:r,baseUrl:this.baseUrl,redirectOnComplete:this.customization.redirectOnComplete,tdsIframeId:i,tonderPayButtonId:d,callBack:s}),this.tdsIframeId=i;const c=l||k;this.telemetry=new M({endpoint:g(this.mode),apiKey:this.apiKeyTonder,platform:c.name,platform_version:c.version,mode:this.mode||"stage"})}configureCheckout(e){"secureToken"in e&&o(this,U,"m",V).call(this,e.secureToken),o(this,U,"m",w).call(this,e)}getCustomerId(){var e,t;return null===(t=null===(e=o(this,P,"f"))||void 0===e?void 0:e.id)||void 0===t?void 0:t.toString()}reportSdkError(e,t){var r,o,n,i;try{const s=this.getCustomerId(),a=e instanceof _&&void 0!==e.originalError?e.originalError:e,d=Object.assign(Object.assign({},(null==t?void 0:t.metadata)||{}),void 0===(null===(r=null==t?void 0:t.metadata)||void 0===r?void 0:r.error)?{error:a}:{}),l=Object.assign(Object.assign({tenant_id:null===(i=null===(n=null===(o=this.merchantData)||void 0===o?void 0:o.business)||void 0===n?void 0:n.pk)||void 0===i?void 0:i.toString(),user_id:s},t||{}),{metadata:d,request_id:this.requestId});l.user_id||delete l.user_id,l.feature=(null==t?void 0:t.feature)||"unknown",this.telemetry.captureException(e,l)}catch(e){}}generateRequestId(){return`req_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}verify3dsTransaction(){return r(this,void 0,void 0,(function*(){const e=yield this.process3ds.verifyTransactionStatus(),t=yield o(this,U,"m",Y).call(this,e);return this.process3ds.setPayload(t),this._handle3dsRedirect(t)}))}payment(e){return new Promise(((t,n)=>r(this,void 0,void 0,(function*(){var r,i;let a;try{o(this,U,"m",w).call(this,e),a=yield this._checkout(e),this.process3ds.setPayload(a);if(yield this._handle3dsRedirect(a)){try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}this.callBack&&this.callBack(a),t(a)}}catch(t){this.reportSdkError(t,{feature:"payment",process_id:(null==a?void 0:a.payment_id)||(null===(r=null==a?void 0:a.payment)||void 0===r?void 0:r.id)||(null===(i=null==a?void 0:a.payment)||void 0===i?void 0:i.pk),metadata:{step:"payment",request:e,response:a}}),n(y({errorCode:s.PAYMENT_PROCESS_ERROR},t))}}))))}getSecureToken(e){return r(this,void 0,void 0,(function*(){try{return yield function(e,t,o=null){return r(this,void 0,void 0,(function*(){const r=yield fetch(`${e}/api/secure-token/`,{method:"POST",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:o});if(r.ok)return yield r.json();throw yield y({response:r,errorCode:s.SECURE_TOKEN_ERROR})}))}(this.baseUrl,e)}catch(e){throw this.reportSdkError(e,{feature:"secure-token",metadata:{step:"getSecureToken"}}),y({errorCode:s.SECURE_TOKEN_ERROR},e)}}))}_initializeCheckout(){return r(this,void 0,void 0,(function*(){const e=yield this._fetchMerchantData();e&&e.mercado_pago&&e.mercado_pago.active&&function(){try{const e=document.createElement("script");e.src="https://www.mercadopago.com/v2/security.js",e.setAttribute("view",""),e.onload=()=>{},e.onerror=e=>{console.error("Error loading Mercado Pago script:",e)},document.head.appendChild(e)}catch(e){console.error("Error attempting to inject Mercado Pago script:",e)}}(),this._hasCardOnFileKeys()&&(yield this._initializeCardOnFile())}))}_checkout(e){return r(this,void 0,void 0,(function*(){throw new Error("The #checkout method should be implement in child classes.")}))}_setCartTotal(e){throw new Error("The #setCartTotal method should be implement in child classes.")}_getCustomer(e=null){return r(this,void 0,void 0,(function*(){return o(this,P,"f")||n(this,P,yield function(e,t,o,n=null){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/customer/`,i={email:o.email,first_name:null==o?void 0:o.firstName,last_name:null==o?void 0:o.lastName,phone:null==o?void 0:o.phone},a=yield fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},signal:n,body:JSON.stringify(i)});if(a.ok)return yield a.json();throw yield y({response:a,errorCode:s.CUSTOMER_OPERATION_ERROR})}))}(this.baseUrl,this.apiKeyTonder,this.customer,e),"f"),o(this,P,"f")}))}_handleCheckout({card:t,payment_method:n,customer:i,isSandbox:a,enable_card_on_file:d,returnUrl:c}){return r(this,void 0,void 0,(function*(){const{openpay_keys:u,reference:h,business:_}=this.merchantData,E=Number(this.cartTotal);let p,m,R;try{let v;!v&&u.merchant_id&&u.public_key&&!n&&(v=yield C(u.merchant_id,u.public_key,a,this.abortController.signal));const{id:f,auth_token:O}=i;p={business:this.apiKeyTonder,client:O,billing_address_id:null,shipping_address_id:null,amount:E,status:"A",reference:h,is_oneclick:!0,items:this.cartItems,currency:this.currency,metadata:this.metadata};const T=yield function(e,t,o){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/orders/`,n=o,i=yield fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(n)});if(i.ok)return yield i.json();throw yield y({response:i,errorCode:s.CREATE_ORDER_ERROR})}))}(this.baseUrl,this.apiKeyTonder,p),g=(new Date).toISOString();m={business_pk:_.pk,client_id:f,amount:E,date:g,order_id:T.id,customer_order_reference:this.order_reference?this.order_reference:h,items:this.cartItems,currency:this.currency,metadata:this.metadata};const I=yield function(e,t,o){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/business/${o.business_pk}/payments/`,n=o,i=yield fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(n)});if(i.ok)return yield i.json();throw yield y({response:i,errorCode:s.CREATE_PAYMENT_ERROR})}))}(this.baseUrl,this.apiKeyTonder,m);R=Object.assign(Object.assign(Object.assign(Object.assign({name:e(this.customer,"firstName",e(this.customer,"name","")),last_name:e(this.customer,"lastName",e(this.customer,"lastname","")),email_client:e(this.customer,"email",""),phone_number:e(this.customer,"phone",""),return_url:c||this.returnUrl,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:E,title_ship:"shipping",description:"transaction",device_session_id:v||null,token_id:"",order_id:T.id,business_id:_.pk,payment_id:I.pk,source:"sdk",items:this.cartItems,metadata:this.metadata,browser_info:l(),currency:this.currency},n?{payment_method:n}:{card:t}),{apm_config:o(this,L,"f")}),this.customer&&"identification"in this.customer?{identification:this.customer.identification}:{}),void 0!==d?{enable_card_on_file:d}:{});const S=yield A(this.baseUrl,this.apiKeyTonder,R);return S||!1}catch(e){throw this.reportSdkError(e,{feature:"payment",process_id:null==R?void 0:R.payment_id,metadata:{step:"_handleCheckout",orderItems:p,paymentItems:m,routerItems:R}}),e}}))}_fetchMerchantData(){return r(this,void 0,void 0,(function*(){try{return this.merchantData||(this.merchantData=yield i(this.baseUrl,this.apiKeyTonder,this.abortController.signal)),this.merchantData}catch(e){return this.reportSdkError(e,{feature:"fetch-merchant-data",metadata:{step:"_fetchMerchantData"}}),this.merchantData}}))}_getCustomerCards(e,t){return r(this,void 0,void 0,(function*(){return yield function(e,t,o,n,i=null){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/business/${n}/cards/`,a=yield fetch(r,{method:"GET",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":t},signal:i});if(a.ok)return yield a.json();if(401===a.status)return{user_id:0,cards:[]};throw yield y({response:a,errorCode:s.FETCH_CARDS_ERROR})}))}(this.baseUrl,e,this.secureToken,t)}))}_saveCustomerCard(e,t,o,n=!1){return r(this,void 0,void 0,(function*(){return yield function(e,t,o,n,i,a=!1){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/business/${n}/cards/`,d=yield fetch(r,{method:"POST",headers:Object.assign({Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":t},a?{"X-App-Origin":"sdk/ionic"}:{}),body:JSON.stringify(i)});if(d.ok)return yield d.json();throw yield y({response:d,errorCode:s.SAVE_CARD_ERROR})}))}(this.baseUrl,e,this.secureToken,t,o,n)}))}_removeCustomerCard(e,t,o){return r(this,void 0,void 0,(function*(){return yield function(e,t,o,n="",i){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/business/${i}/cards/${n}`,d=yield fetch(r,{method:"DELETE",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":t}});if(204===d.status)return a[s.CARD_REMOVED_SUCCESSFULLY];if(d.ok&&"json"in d)return yield d.json();throw yield y({response:d,errorCode:s.REMOVE_CARD_ERROR})}))}(this.baseUrl,e,this.secureToken,o,t)}))}_fetchCustomerPaymentMethods(){return r(this,void 0,void 0,(function*(){return yield function(e,t,o={status:"active",pagesize:"10000"},n=null){return r(this,void 0,void 0,(function*(){const r=new URLSearchParams(o).toString(),i=yield fetch(`${e}/api/v1/payment_methods?${r}`,{method:"GET",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:n});if(i.ok)return yield i.json();throw yield y({response:i,errorCode:s.FETCH_PAYMENT_METHODS_ERROR})}))}(this.baseUrl,this.apiKeyTonder)}))}_hasCardOnFileKeys(){var e,t;return!!(null===(t=null===(e=this.merchantData)||void 0===e?void 0:e.cardonfile_keys)||void 0===t?void 0:t.public_key)}_initializeCardOnFile(){var e;return r(this,void 0,void 0,(function*(){return this.cardOnFileInstance||(this.cardOnFileInstance=new b({merchantId:null===(e=this.merchantData)||void 0===e?void 0:e.cardonfile_keys.public_key,apiKey:this.apiKeyTonder,isTestEnvironment:"production"!==this.mode}),yield this.cardOnFileInstance.initialize()),this.cardOnFileInstance}))}_handle3dsRedirect(e){var t,o;return r(this,void 0,void 0,(function*(){if(e&&"next_action"in e?null===(o=null===(t=null==e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===o?void 0:o.iframe:null)this.process3ds.loadIframe().then((()=>{this.process3ds.verifyTransactionStatus()})).catch((t=>{console.log("Error loading iframe:",t),this.reportSdkError(t,{feature:"3ds-verification",metadata:{step:"_handle3dsRedirect",response:e}})}));else{if(!this.process3ds.getRedirectUrl())return e;this.process3ds.redirectToChallenge()}}))}}function q(e,t,o=null){return r(this,void 0,void 0,(function*(){const r=yield fetch(`${e}/api/v1/vault-token/`,{method:"GET",headers:{Authorization:`Token ${t}`},signal:o});if(r.ok){return(yield r.json()).token}throw yield y({response:r,errorCode:s.VAULT_TOKEN_ERROR})}))}L=new WeakMap,P=new WeakMap,U=new WeakSet,w=function(e){var t,r;!e||e&&0===Object.keys(e).length||(o(this,U,"m",j).call(this,e.customer),this._setCartTotal((null===(t=e.cart)||void 0===t?void 0:t.total)||0),o(this,U,"m",K).call(this,(null===(r=e.cart)||void 0===r?void 0:r.items)||[]),o(this,U,"m",F).call(this,e),o(this,U,"m",x).call(this,e),o(this,U,"m",B).call(this,e),o(this,U,"m",$).call(this,e))},j=function(e){e&&(this.customer=e)},V=function(e){this.secureToken=e},K=function(e){this.cartItems=e},F=function(e){this.metadata=null==e?void 0:e.metadata,this.order_reference=null==e?void 0:e.order_reference},x=function(e){this.currency=null==e?void 0:e.currency},B=function(e){this.card=null==e?void 0:e.card},Y=function(e){var t,o,n,i,s;return r(this,void 0,void 0,(function*(){if("Hard"===(null===(t=null==e?void 0:e.decline)||void 0===t?void 0:t.error_type)||(null===(o=null==e?void 0:e.checkout)||void 0===o?void 0:o.is_route_finished)||(null==e?void 0:e.is_route_finished)||["Pending"].includes(null==e?void 0:e.transaction_status))return e;if(["Success","Authorized"].includes(null==e?void 0:e.transaction_status))return e;if(e){const t={checkout_id:(null===(n=e.checkout)||void 0===n?void 0:n.id)||(null==e?void 0:e.checkout_id)};try{return yield A(this.baseUrl,this.apiKeyTonder,t)}catch(t){this.reportSdkError(t,{feature:"payment",process_id:(null==e?void 0:e.payment_id)||(null===(i=null==e?void 0:e.payment)||void 0===i?void 0:i.id)||(null===(s=null==e?void 0:e.payment)||void 0===s?void 0:s.pk),metadata:{step:"#resumeCheckout",response:e}})}return e}}))},$=function(e){n(this,L,null==e?void 0:e.apm_config,"f")},function(e){e.CARD_NUMBER="card_number",e.CVV="cvv",e.EXPIRATION_MONTH="expiration_month",e.EXPIRATION_YEAR="expiration_year",e.CARDHOLDER_NAME="cardholder_name"}(H||(H={}));const Q={type:t.ValidationRuleType.LENGTH_MATCH_RULE,params:{max:70}},W=RegExp("^(?!s*$).+"),X={type:t.ValidationRuleType.REGEX_MATCH_RULE,params:{regex:W,error:"El campo es requerido"}},J="Titular de la tarjeta",G="Número de tarjeta",Z="CVC/CVV",ee="Mes",te="Año",re="Fecha de expiración",oe="Nombre como aparece en la tarjeta",ne="1234 1234 1234 1234",ie="3-4 dígitos",se="MM",ae="AA",de={base:{border:"1px solid #e0e0e0",padding:"10px 7px",borderRadius:"5px",color:"#1d1d1d",marginTop:"2px",backgroundColor:"white",fontFamily:'"Inter", sans-serif',fontSize:"16px","&::placeholder":{color:"#ccc"}},complete:{color:"#4caf50"},invalid:{border:"1px solid #f44336"},empty:{},focus:{},global:{"@import":'url("https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;700&display=swap")'}},le={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif'}},ce={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif',color:"#f44336"}};function ue({baseUrl:e,apiKey:o,vault_id:n,vault_url:i,data:a}){return r(this,void 0,void 0,(function*(){const d=t.init({vaultID:n,vaultURL:i,getBearerToken:()=>r(this,void 0,void 0,(function*(){return yield q(e,o)})),options:{logLevel:t.LogLevel.ERROR,env:t.Env.DEV}}).container(t.ContainerType.COLLECT),l=yield function(e,o){return r(this,void 0,void 0,(function*(){const n=yield function(e,o){return r(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(e).map((e=>r(this,void 0,void 0,(function*(){return{element:yield o.create({table:"cards",column:e,type:t.ElementType.INPUT_FIELD}),key:e}})))))}))}(e,o);return n?n.map((t=>new Promise((r=>{var o;const n=document.createElement("div");n.hidden=!0,n.id=`id-${t.key}`,null===(o=document.querySelector("body"))||void 0===o||o.appendChild(n),setTimeout((()=>{t.element.mount(`#id-${t.key}`),setInterval((()=>{if(t.element.isMounted()){const o=e[t.key];return t.element.setValue(o),r(t.element.isMounted())}}),120)}),120)})))):[]}))}(a,d);if((yield Promise.all(l)).some((e=>!e)))throw y({errorCode:s.SAVE_CARD_PROCESS_ERROR,details:{step:"get_skyflow_tokens"}});try{const e=yield d.collect();if(e)return e.records[0].fields;throw y({errorCode:s.SAVE_CARD_PROCESS_ERROR,details:{step:"get_skyflow_tokens"}})}catch(e){throw y({errorCode:s.SAVE_CARD_PROCESS_ERROR},e)}}))}function he(e){const{element:r,fieldMessage:o="",errorStyles:n={},requiredMessage:i="Campo requerido",invalidMessage:s="Campo no válido",events:a}=e;"on"in r&&(r.on(t.EventName.CHANGE,(e=>{Ee({eventName:"onChange",data:e,events:a}),_e({element:r,errorStyles:n,color:"transparent"})})),r.on(t.EventName.BLUR,(e=>{if(Ee({eventName:"onBlur",data:e,events:a}),!e.isValid){const t=e.isEmpty?i:""!=o?`El campo ${o} no es válido`:s;r.setError(t)}_e({element:r,errorStyles:n})})),r.on(t.EventName.FOCUS,(e=>{Ee({eventName:"onFocus",data:e,events:a}),_e({element:r,errorStyles:n,color:"transparent"}),r.resetError()})))}function _e(e){const{element:t,errorStyles:r={},color:o=""}=e;Object.keys(r).length>0&&t.update({errorTextStyles:Object.assign(Object.assign({},r),{base:Object.assign(Object.assign({},r.base&&Object.assign({},r.base)),""!=o&&{color:o})})})}const Ee=t=>{const{eventName:r,data:o,events:n}=t;if(n&&r in n){const t=n[r];"function"==typeof t&&t({elementType:e(o,"elementType",""),isEmpty:e(o,"isEmpty",""),isFocused:e(o,"isFocused",""),isValid:e(o,"isValid","")})}};function pe(e){return r(this,void 0,void 0,(function*(){const{element:t,containerId:r,retries:o=2,delay:n=30}=e;for(let e=0;e<=o;e++){if(document.querySelector(r))return void t.mount(r);e<o&&(yield new Promise((e=>setTimeout(e,n))))}console.warn(`[mountCardFields] Container ${r} was not found after ${o+1} attempts`)}))}const me=Object.freeze({SORIANA:"SORIANA",OXXO:"OXXO",OXXOPAY:"OXXOPAY",SPEI:"SPEI",CODI:"CODI",MERCADOPAGO:"MERCADOPAGO",PAYPAL:"PAYPAL",COMERCIALMEXICANA:"COMERCIALMEXICANA",BANCOMER:"BANCOMER",WALMART:"WALMART",BODEGA:"BODEGA",SAMSCLUB:"SAMSCLUB",SUPERAMA:"SUPERAMA",CALIMAX:"CALIMAX",EXTRA:"EXTRA",CIRCULOK:"CIRCULOK",SEVEN11:"7ELEVEN",TELECOMM:"TELECOMM",BANORTE:"BANORTE",BENAVIDES:"BENAVIDES",DELAHORRO:"DELAHORRO",ELASTURIANO:"ELASTURIANO",WALDOS:"WALDOS",ALSUPER:"ALSUPER",KIOSKO:"KIOSKO",STAMARIA:"STAMARIA",LAMASBARATA:"LAMASBARATA",FARMROMA:"FARMROMA",FARMUNION:"FARMUNION",FARMATODO:"FARMATODO",SFDEASIS:"SFDEASIS",FARM911:"FARM911",FARMECONOMICAS:"FARMECONOMICAS",FARMMEDICITY:"FARMMEDICITY",RIANXEIRA:"RIANXEIRA",WESTERNUNION:"WESTERNUNION",ZONAPAGO:"ZONAPAGO",CAJALOSANDES:"CAJALOSANDES",CAJAPAITA:"CAJAPAITA",CAJASANTA:"CAJASANTA",CAJASULLANA:"CAJASULLANA",CAJATRUJILLO:"CAJATRUJILLO",EDPYME:"EDPYME",KASNET:"KASNET",NORANDINO:"NORANDINO",QAPAQ:"QAPAQ",RAIZ:"RAIZ",PAYSER:"PAYSER",WUNION:"WUNION",BANCOCONTINENTAL:"BANCOCONTINENTAL",GMONEY:"GMONEY",GOPAY:"GOPAY",WU:"WU",PUNTOSHEY:"PUNTOSHEY",AMPM:"AMPM",JUMBOMARKET:"JUMBOMARKET",SMELPUEBLO:"SMELPUEBLO",BAM:"BAM",REFACIL:"REFACIL",ACYVALORES:"ACYVALORES"}),Re={[me.SORIANA]:{label:"Soriana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/soriana.png"},[me.OXXO]:{label:"Oxxo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxo.png"},[me.CODI]:{label:"CoDi",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/codi.png"},[me.MERCADOPAGO]:{label:"Mercado Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/mercadopago.png"},[me.OXXOPAY]:{label:"Oxxo Pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxopay.png"},[me.SPEI]:{label:"SPEI",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/spei.png"},[me.PAYPAL]:{label:"Paypal",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/paypal.png"},[me.COMERCIALMEXICANA]:{label:"Comercial Mexicana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/comercial_exicana.png"},[me.BANCOMER]:{label:"Bancomer",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bancomer.png"},[me.WALMART]:{label:"Walmart",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/walmart.png"},[me.BODEGA]:{label:"Bodega Aurrera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bodega_aurrera.png"},[me.SAMSCLUB]:{label:"Sam´s Club",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/sams_club.png"},[me.SUPERAMA]:{label:"Superama",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/superama.png"},[me.CALIMAX]:{label:"Calimax",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/calimax.png"},[me.EXTRA]:{label:"Tiendas Extra",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/tiendas_extra.png"},[me.CIRCULOK]:{label:"Círculo K",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/circulo_k.png"},[me.SEVEN11]:{label:"7 Eleven",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/7_eleven.png"},[me.TELECOMM]:{label:"Telecomm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/telecomm.png"},[me.BANORTE]:{label:"Banorte",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/banorte.png"},[me.BENAVIDES]:{label:"Farmacias Benavides",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_benavides.png"},[me.DELAHORRO]:{label:"Farmacias del Ahorro",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_ahorro.png"},[me.ELASTURIANO]:{label:"El Asturiano",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/asturiano.png"},[me.WALDOS]:{label:"Waldos",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/waldos.png"},[me.ALSUPER]:{label:"Alsuper",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/al_super.png"},[me.KIOSKO]:{label:"Kiosko",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/kiosko.png"},[me.STAMARIA]:{label:"Farmacias Santa María",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_santa_maria.png"},[me.LAMASBARATA]:{label:"Farmacias la más barata",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_barata.png"},[me.FARMROMA]:{label:"Farmacias Roma",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_roma.png"},[me.FARMUNION]:{label:"Pago en Farmacias Unión",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_union.png"},[me.FARMATODO]:{label:"Pago en Farmacias Farmatodo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_farmatodo.png\t"},[me.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_san_francisco.png"},[me.FARM911]:{label:"Farmacias 911",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.FARMECONOMICAS]:{label:"Farmacias Economicas",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.FARMMEDICITY]:{label:"Farmacias Medicity",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.RIANXEIRA]:{label:"Rianxeira",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.WESTERNUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.ZONAPAGO]:{label:"Zona Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.CAJALOSANDES]:{label:"Caja Los Andes",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.CAJAPAITA]:{label:"Caja Paita",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.CAJASANTA]:{label:"Caja Santa",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.CAJASULLANA]:{label:"Caja Sullana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.CAJATRUJILLO]:{label:"Caja Trujillo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.EDPYME]:{label:"Edpyme",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.KASNET]:{label:"KasNet",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.NORANDINO]:{label:"Norandino",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.QAPAQ]:{label:"Qapaq",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.RAIZ]:{label:"Raiz",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.PAYSER]:{label:"Paysera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.WUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.BANCOCONTINENTAL]:{label:"Banco Continental",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.GMONEY]:{label:"Go money",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.GOPAY]:{label:"Go pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.WU]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.PUNTOSHEY]:{label:"Puntoshey",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.AMPM]:{label:"Ampm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.JUMBOMARKET]:{label:"Jumbomarket",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.SMELPUEBLO]:{label:"Smelpueblo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.BAM]:{label:"Bam",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.REFACIL]:{label:"Refacil",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[me.ACYVALORES]:{label:"Acyvalores",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"}},ye=e=>{const t=e.toUpperCase().trim().replace(/\s+/g,"");return Re[t]||{icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",label:""}};class ve extends z{constructor({apiKey:e,mode:t,returnUrl:r,callBack:o,apiKeyTonder:n,baseUrlTonder:i,customization:s,collectorIds:a,events:d}){super({mode:t,apiKey:e,returnUrl:r,callBack:o,apiKeyTonder:n,baseUrlTonder:i,customization:s,tdsIframeId:a&&"tdsIframe"in a?null==a?void 0:a.tdsIframe:"tdsIframe",sdkInfo:k}),this.activeAPMs=[],this.mountedElementsByContext=new Map,this.customerCardsCache=null,this.skyflowInstance=null,this.events=d||{}}injectCheckout(){return r(this,void 0,void 0,(function*(){yield this._initializeCheckout()}))}getCustomerCards(){return r(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:e}=yield this._getCustomer(),t=yield this._getCustomerCards(e,this.merchantData.business.pk);return this.customerCardsCache=t,Object.assign(Object.assign({},t),{cards:t.cards.map((e=>{return Object.assign(Object.assign({},e),{fields:Object.assign(Object.assign({},e.fields),{subscription_id:this._hasCardOnFileKeys()?e.fields.subscription_id:void 0}),icon:(t=e.fields.card_scheme,"Visa"===t?"https://d35a75syrgujp0.cloudfront.net/cards/visa.png":"Mastercard"===t?"https://d35a75syrgujp0.cloudfront.net/cards/mastercard.png":"American Express"===t?"https://d35a75syrgujp0.cloudfront.net/cards/american_express.png":"https://d35a75syrgujp0.cloudfront.net/cards/default_card.png")});var t}))})}catch(e){throw this.reportSdkError(e,{feature:"get-cards",process_id:this.getCustomerId(),metadata:{step:"getCustomerCards"}}),y({errorCode:s.FETCH_CARDS_ERROR},e)}}))}saveCustomerCard(e){return r(this,void 0,void 0,(function*(){let t=null;try{yield this._fetchMerchantData();const r=yield this._getCustomer(),{auth_token:o,first_name:n="",last_name:i="",email:a=""}=r,{vault_id:d,vault_url:l,business:c}=this.merchantData,u=this._hasCardOnFileKeys(),h={card_number:e.card_number.replace(/\s+/g,""),expiration_month:e.expiration_month.replace(/\s+/g,""),expiration_year:e.expiration_year.replace(/\s+/g,""),cvv:e.cvv.replace(/\s+/g,""),cardholder_name:e.cardholder_name.replace(/\s+/g,"")},_=yield ue({vault_id:d,vault_url:l,data:h,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder}),E=yield this._saveCustomerCard(o,null==c?void 0:c.pk,_,u);if(t=E.skyflow_id,u){const e=E.card_bin;if(!e)throw new Error("Card BIN not returned from save card");const t=yield this._initializeCardOnFile();let r;try{r=yield t.process({cardTokens:{name:_.cardholder_name,number:_.card_number,expiryMonth:_.expiration_month,expiryYear:_.expiration_year,cvv:_.cvv},cardBin:e,contactDetails:{firstName:n||"",lastName:i||"",email:a||""},customerId:o,currency:this.currency||"MXN"})}catch(e){throw y({errorCode:s.CARD_ON_FILE_DECLINED,lockErrorCode:!0},e)}const d={skyflow_id:_.skyflow_id,subscription_id:r.subscriptionId};yield this._saveCustomerCard(o,null==c?void 0:c.pk,d)}return E}catch(e){throw t&&(yield this.removeCustomerCard(t)),this.reportSdkError(e,{feature:"save-card",process_id:t||this.getCustomerId(),metadata:{step:"saveCustomerCard"}}),y({errorCode:s.SAVE_CARD_ERROR},e)}}))}removeCustomerCard(e){return r(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:t}=yield this._getCustomer(),{business:r}=this.merchantData;return yield this._removeCustomerCard(t,null==r?void 0:r.pk,e)}catch(t){throw this.reportSdkError(t,{feature:"remove-card",process_id:e,metadata:{step:"removeCustomerCard"}}),y({errorCode:s.REMOVE_CARD_ERROR},t)}}))}getCustomerPaymentMethods(){return r(this,void 0,void 0,(function*(){try{const e=yield this._fetchCustomerPaymentMethods();return(e&&"results"in e&&e.results.length>0?e.results:[]).filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},ye(e.payment_method)))).sort(((e,t)=>e.priority-t.priority))}catch(e){throw this.reportSdkError(e,{feature:"get-payment-methods",metadata:{step:"getCustomerPaymentMethods"}}),y({errorCode:s.FETCH_PAYMENT_METHODS_ERROR},e)}}))}mountCardFields(e){var o;return r(this,void 0,void 0,(function*(){const n=e.card_id?`update:${e.card_id}`:"create",i=null!==(o=e.unmount_context)&&void 0!==o?o:"all";"none"!==i&&("current"===i?this.unmountCardFields(n):this.unmountCardFields(i)),yield this.createSkyflowInstance();const s=yield function(e){var o,n,i,s,a,d,l,c,u,h,_,E,p,m,R,y,v;return r(this,void 0,void 0,(function*(){const{skyflowInstance:r,data:f,customization:A,events:C}=e,O=r.container(t.ContainerType.COLLECT),T=[],g={[H.CVV]:t.ElementType.CVV,[H.CARD_NUMBER]:t.ElementType.CARD_NUMBER,[H.EXPIRATION_MONTH]:t.ElementType.EXPIRATION_MONTH,[H.EXPIRATION_YEAR]:t.ElementType.EXPIRATION_YEAR,[H.CARDHOLDER_NAME]:t.ElementType.CARDHOLDER_NAME},I={[H.CVV]:[X],[H.CARD_NUMBER]:[X],[H.EXPIRATION_MONTH]:[X],[H.EXPIRATION_YEAR]:[X],[H.CARDHOLDER_NAME]:[Q,X]},S={errorStyles:(null===(n=null===(o=null==A?void 0:A.styles)||void 0===o?void 0:o.cardForm)||void 0===n?void 0:n.errorStyles)||ce,inputStyles:(null===(s=null===(i=null==A?void 0:A.styles)||void 0===i?void 0:i.cardForm)||void 0===s?void 0:s.inputStyles)||de,labelStyles:(null===(d=null===(a=null==A?void 0:A.styles)||void 0===a?void 0:a.cardForm)||void 0===d?void 0:d.labelStyles)||le},N={name:(null===(l=null==A?void 0:A.labels)||void 0===l?void 0:l.name)||J,card_number:(null===(c=null==A?void 0:A.labels)||void 0===c?void 0:c.card_number)||G,cvv:(null===(u=null==A?void 0:A.labels)||void 0===u?void 0:u.cvv)||Z,expiration_date:(null===(h=null==A?void 0:A.labels)||void 0===h?void 0:h.expiry_date)||re,expiration_month:(null===(_=null==A?void 0:A.labels)||void 0===_?void 0:_.expiration_month)||ee,expiration_year:(null===(E=null==A?void 0:A.labels)||void 0===E?void 0:E.expiration_year)||te},D={name:(null===(p=null==A?void 0:A.placeholders)||void 0===p?void 0:p.name)||oe,card_number:(null===(m=null==A?void 0:A.placeholders)||void 0===m?void 0:m.card_number)||ne,cvv:(null===(R=null==A?void 0:A.placeholders)||void 0===R?void 0:R.cvv)||ie,expiration_month:(null===(y=null==A?void 0:A.placeholders)||void 0===y?void 0:y.expiration_month)||se,expiration_year:(null===(v=null==A?void 0:A.placeholders)||void 0===v?void 0:v.expiration_year)||ae},b={[H.CVV]:null==C?void 0:C.cvvEvents,[H.CARD_NUMBER]:null==C?void 0:C.cardNumberEvents,[H.EXPIRATION_MONTH]:null==C?void 0:C.monthEvents,[H.EXPIRATION_YEAR]:null==C?void 0:C.yearEvents,[H.CARDHOLDER_NAME]:null==C?void 0:C.cardHolderEvents};if("fields"in f&&Array.isArray(f.fields))if(f.fields.length>0&&"string"==typeof f.fields[0])for(const e of f.fields){const t=O.create(Object.assign(Object.assign(Object.assign({table:"cards",column:e,type:g[e],validations:I[e]},S),{label:N[e],placeholder:D[e]}),f.card_id?{skyflowID:f.card_id}:{}));he({element:t,errorStyles:S.errorStyles,fieldMessage:[H.CVV,H.EXPIRATION_MONTH,H.EXPIRATION_YEAR].includes(e)?"":N[e],events:b[e]});const r=`#collect_${String(e)}`+(f.card_id?`_${f.card_id}`:"");yield pe({element:t,containerId:r}),T.push({element:t,containerId:r})}else for(const e of f.fields){const t=e.field,r=O.create(Object.assign(Object.assign(Object.assign({table:"cards",column:t,type:g[t],validations:I[t]},S),{label:N[t],placeholder:D[t]}),f.card_id?{skyflowID:f.card_id}:{})),o=e.container_id||`#collect_${String(t)}`+(f.card_id?`_${f.card_id}`:"");yield pe({element:r,containerId:o}),T.push({element:r,containerId:o})}return{elements:T.map((e=>e.element)),container:O}}))}({skyflowInstance:this.skyflowInstance,data:e,customization:this.customization,events:this.events});this.mountedElementsByContext.set(n,{elements:s.elements||[],container:s})}))}getContainerByCardId(e){var t;const r=`update:${e}`,o=this.mountedElementsByContext.get(r);return(null===(t=null==o?void 0:o.container)||void 0===t?void 0:t.container)||null}collectCardTokens(e){var t,o,n;return r(this,void 0,void 0,(function*(){const r=this.getContainerByCardId(e);if(!r)return null;try{const e=yield r.collect();return(null===(o=null===(t=null==e?void 0:e.records)||void 0===t?void 0:t[0])||void 0===o?void 0:o.fields)||null}catch(t){const r=null===(n=null==t?void 0:t.error)||void 0===n?void 0:n.description;throw this.reportSdkError(t,{feature:"collect-card-tokens",process_id:e,metadata:{step:"collectCardTokens"}}),new d({code:s.MOUNT_COLLECT_ERROR,details:{message:r}})}}))}unmountCardFields(e="all"){"all"===e?(this.mountedElementsByContext.forEach(((e,t)=>{this.unmountContext(t)})),this.mountedElementsByContext.clear()):(this.unmountContext(e),this.mountedElementsByContext.delete(e))}unmountContext(e){const t=this.mountedElementsByContext.get(e);if(!t)return;const{elements:r}=t;r&&r.length>0&&r.forEach((t=>{try{t&&"function"==typeof t.unmount&&t.unmount()}catch(t){console.warn(`Error unmounting Skyflow element from context '${e}':`,t),this.reportSdkError(t,{feature:"unmount-card-fields",metadata:{step:"unmountContext",context:e}})}}))}getBusiness(){return r(this,void 0,void 0,(function*(){try{return yield i(this.baseUrl,this.apiKeyTonder,this.abortController.signal)}catch(e){throw this.reportSdkError(e,{feature:"get-business",metadata:{step:"getBusiness"}}),y({errorCode:s.FETCH_BUSINESS_ERROR},e)}}))}createSkyflowInstance(){return r(this,void 0,void 0,(function*(){if(this.skyflowInstance)return this.skyflowInstance;yield this._fetchMerchantData();const{vault_id:e,vault_url:o}=this.merchantData;this.skyflowInstance=yield function({baseUrl:e,apiKey:o,vault_id:n,vault_url:i}){return r(this,void 0,void 0,(function*(){return t.init({vaultID:n,vaultURL:i,getBearerToken:()=>r(this,void 0,void 0,(function*(){return yield q(e,o)})),options:{logLevel:t.LogLevel.ERROR,env:t.Env.DEV}})}))}({vault_id:e,vault_url:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}getOpenpayDeviceSessionID(e,t,o){return r(this,void 0,void 0,(function*(){try{return yield C(e,t,o)}catch(e){throw this.reportSdkError(e,{feature:"get-openpay-device-session",metadata:{step:"getOpenpayDeviceSessionID"}}),y({errorCode:s.START_CHECKOUT_ERROR},e)}}))}getSkyflowTokens({vault_id:e,vault_url:t,data:o}){return r(this,void 0,void 0,(function*(){return yield ue({vault_id:e,vault_url:t,data:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}_setCartTotal(e){this.cartTotal=e}_checkout({card:e,payment_method:t,isSandbox:o,returnUrl:n}){var i,a;return r(this,void 0,void 0,(function*(){yield this._fetchMerchantData();const d=yield this._getCustomer(this.abortController.signal),{vault_id:l,vault_url:c,business:u}=this.merchantData,{auth_token:h,first_name:_="",last_name:E="",email:p=""}=d,m=this._hasCardOnFileKeys();let R,v=null,f=null,A=null,C=!1;const O=()=>r(this,void 0,void 0,(function*(){var e,t;(null===(t=null===(e=this.customerCardsCache)||void 0===e?void 0:e.cards)||void 0===t?void 0:t.length)||(this.customerCardsCache=yield this._getCustomerCards(h,this.merchantData.business.pk))}));if(!t){if("string"==typeof e)if(f=e,R={skyflow_id:e},m){yield O();const t=null===(a=null===(i=this.customerCardsCache)||void 0===i?void 0:i.cards)||void 0===a?void 0:a.find((t=>t.fields.skyflow_id===e));if(!t)throw new Error("Card not found for card-on-file processing");const r=!!t.fields.subscription_id;r||(yield this.collectCardTokens(e)),r&&(v={subscriptionId:t.fields.subscription_id})}else yield this.collectCardTokens(e);else{const t=Object.assign(Object.assign({},e),{card_number:e.card_number.replace(/\s+/g,""),expiration_month:e.expiration_month.replace(/\s+/g,""),expiration_year:e.expiration_year.replace(/\s+/g,""),cvv:e.cvv.replace(/\s+/g,""),cardholder_name:e.cardholder_name.replace(/\s+/g,"")});R=yield ue({vault_id:l,vault_url:c,data:t,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder}),f=R.skyflow_id,m&&(A={name:R.cardholder_name,number:R.card_number,expiryMonth:R.expiration_month,expiryYear:R.expiration_year,cvv:R.cvv},C=!0)}if(C){if(!f||!A)throw new Error("Missing card data for card-on-file processing");let e=null;try{const t=yield this._saveCustomerCard(h,null==u?void 0:u.pk,{skyflow_id:f},!0);e=t.skyflow_id;const r=t.card_bin;if(!r)throw new Error("Card BIN not returned from save card");const o=yield this._initializeCardOnFile();let n;try{n=yield o.process({cardTokens:A,cardBin:r,contactDetails:{firstName:_||"",lastName:E||"",email:p||""},customerId:h,currency:this.currency||"MXN"})}catch(e){throw y({errorCode:s.CARD_ON_FILE_DECLINED,lockErrorCode:!0},e)}v={subscriptionId:n.subscriptionId},yield this._saveCustomerCard(h,null==u?void 0:u.pk,{skyflow_id:f,subscription_id:v.subscriptionId})}catch(t){throw e&&(yield this.removeCustomerCard(e)),this.reportSdkError(t,{feature:"payment",process_id:e||this.getCustomerId(),metadata:{step:"card_on_file"}}),t}}}return yield this._handleCheckout({card:R,payment_method:t,customer:d,isSandbox:o,returnUrl:n,enable_card_on_file:!!(null==v?void 0:v.subscriptionId)&&m})}))}customerRegister(e){return r(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/customer/`,r={email:e},o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},signal:this.abortController.signal,body:JSON.stringify(r)});if(o.ok)return yield o.json();throw yield y({response:o,errorCode:s.CUSTOMER_OPERATION_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"customer-register",metadata:{step:"customerRegister"}}),y({errorCode:s.CUSTOMER_OPERATION_ERROR},e)}}))}createOrder(e){return r(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/orders/`,r=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(r)});if(o.ok)return yield o.json();throw yield y({response:o,errorCode:s.CREATE_ORDER_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"create-order",metadata:{step:"createOrder"}}),y({errorCode:s.CREATE_ORDER_ERROR},e)}}))}createPayment(e){return r(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/business/${e.business_pk}/payments/`,r=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(r)});if(o.ok)return yield o.json();throw yield y({response:o,errorCode:s.CREATE_PAYMENT_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"create-payment",metadata:{step:"createPayment"}}),y({errorCode:s.CREATE_PAYMENT_ERROR},e)}}))}startCheckoutRouter(e){return r(this,void 0,void 0,(function*(){const t=yield A(this.baseUrl,this.apiKeyTonder,e);if(yield this.init3DSRedirect(t))return t}))}init3DSRedirect(e){return r(this,void 0,void 0,(function*(){return this.process3ds.setPayload(e),yield this._handle3dsRedirect(e)}))}startCheckoutRouterFull(e){return r(this,void 0,void 0,(function*(){try{const{order:t,total:r,customer:o,skyflowTokens:n,return_url:i,isSandbox:a,metadata:d,currency:c,payment_method:u}=e,h=yield this._fetchMerchantData(),_=yield this.customerRegister(o.email);if(!(_&&"auth_token"in _&&h&&"reference"in h))throw y({errorCode:s.START_CHECKOUT_ERROR,details:{message:"Merchant or customer reposne errors",merchantResult:h,customerResult:_}});{const e={business:this.apiKeyTonder,client:_.auth_token,billing_address_id:null,shipping_address_id:null,amount:r,reference:h.reference,is_oneclick:!0,items:t.items},E=yield this.createOrder(e),p=(new Date).toISOString();if(!("id"in E&&"id"in _&&"business"in h))throw y({errorCode:s.START_CHECKOUT_ERROR,details:{message:"Order response errors",orderResult:E}});{const e={business_pk:h.business.pk,amount:r,date:p,order_id:E.id,client_id:_.id},t=yield this.createPayment(e);let s;const{openpay_keys:m,business:R}=h;m.merchant_id&&m.public_key&&(s=yield C(m.merchant_id,m.public_key,a));const y=Object.assign(Object.assign({name:o.name,last_name:o.lastname,email_client:o.email,phone_number:o.phone,return_url:i,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:r,title_ship:"shipping",description:"transaction",device_session_id:s||null,token_id:"",order_id:"id"in E&&E.id,business_id:R.pk,payment_id:"pk"in t&&t.pk,source:"sdk",metadata:d,browser_info:l(),currency:c},u?{payment_method:u}:{card:n}),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}),v=yield A(this.baseUrl,this.apiKeyTonder,y);if(yield this.init3DSRedirect(v))return v}}}catch(e){throw this.reportSdkError(e,{feature:"start-checkout-router-full",metadata:{step:"startCheckoutRouterFull"}}),y({errorCode:s.START_CHECKOUT_ERROR},e)}}))}registerCustomerCard(e,t,o){return r(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const r=yield fetch(`${this.baseUrl}/api/v1/business/${c(this.merchantData)}/cards/`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"User-token":t,"Content-Type":"application/json"},body:JSON.stringify(Object.assign({},o))});if(r.ok)return yield r.json();throw yield y({response:r,errorCode:s.SAVE_CARD_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"register-customer-card",metadata:{step:"registerCustomerCard"}}),y({errorCode:s.SAVE_CARD_ERROR},e)}}))}deleteCustomerCard(e,t=""){return r(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const r=yield fetch(`${this.baseUrl}/api/v1/business/${c(this.merchantData)}/cards/${t}`,{method:"DELETE",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.abortController.signal});if(r.ok)return!0;throw yield y({response:r,errorCode:s.REMOVE_CARD_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"delete-customer-card",process_id:t,metadata:{step:"deleteCustomerCard"}}),y({errorCode:s.REMOVE_CARD_ERROR},e)}}))}getActiveAPMs(){return r(this,void 0,void 0,(function*(){try{const e=yield function(e,t,o="?status=active&page_size=10000&country=México",n=null){return r(this,void 0,void 0,(function*(){const r=yield fetch(`${e}/api/v1/payment_methods${o}`,{method:"GET",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:n});if(r.ok)return yield r.json();throw yield y({response:r,errorCode:s.FETCH_PAYMENT_METHODS_ERROR})}))}(this.baseUrl,this.apiKeyTonder),t=e&&e.results&&e.results.length>0?e.results:[];return this.activeAPMs=t.filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},ye(e.payment_method)))).sort(((e,t)=>e.priority-t.priority)),this.activeAPMs}catch(e){return console.error("Error getting APMS",e),[]}}))}}function fe(e){return/^\d{12,19}$/.test(e)&&ge(e)}function Ae(e){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(e)}function Ce(e){return/^\d{3,4}$/.test(e)}function Oe(e){return/^(0[1-9]|1[0-2])$/.test(e)}function Te(e){if(!/^\d{2}$/.test(e))return!1;const t=(new Date).getFullYear()%100;return parseInt(e,10)>=t}const ge=e=>{const t=`${e}`.split("").reverse().map((e=>Number.parseInt(e))),r=t.shift();let o=t.reduce(((e,t,r)=>r%2!=0?e+t:e+((t*=2)>9?t-9:t)),0);return o+=r,o%10==0};export{_ as AppError,z as BaseInlineCheckout,ve as LiteCheckout,M as SdkTelemetryClient,Ce as validateCVV,fe as validateCardNumber,Ae as validateCardholderName,Oe as validateExpirationMonth,Te as validateExpirationYear};
1
+ import{get as e}from"lodash";import t from"skyflow-js";function r(e,t,r,o){return new(r||(r=Promise))((function(n,i){function s(e){try{d(o.next(e))}catch(e){i(e)}}function a(e){try{d(o.throw(e))}catch(e){i(e)}}function d(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}d((o=o.apply(e,t||[])).next())}))}function o(e,t,r,o){if("a"===r&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?o:"a"===r?o.call(e):o?o.value:t.get(e)}function n(e,t,r,o,n){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?n.call(e,r):n?n.value=r:t.set(e,r),r}function i(e,t,o){return r(this,void 0,void 0,(function*(){const r=yield fetch(`${e}/api/v1/payments/business/${t}`,{headers:{Authorization:`Token ${t}`},signal:o});return yield r.json()}))}var s;"function"==typeof SuppressedError&&SuppressedError,function(e){e.INIT_ERROR="INIT_ERROR",e.CREATE_ERROR="CREATE_ERROR",e.REMOVE_SDK_ERROR="REMOVE_SDK_ERROR",e.INVALID_TYPE="INVALID_TYPE",e.STATE_ERROR="STATE_ERROR",e.FETCH_BUSINESS_ERROR="FETCH_BUSINESS_ERROR",e.INVALID_CONFIG="INVALID_CONFIG",e.MERCHANT_CREDENTIAL_REQUIRED="MERCHANT_CREDENTIAL_REQUIRED",e.INVALID_PAYMENT_REQUEST="INVALID_PAYMENT_REQUEST",e.INVALID_PAYMENT_REQUEST_CARD_PM="INVALID_PAYMENT_REQUEST_CARD_PM",e.TYPE_SDK_REQUIRED="TYPE_SDK_REQUIRED",e.ENVIRONMENT_REQUIRED="ENVIRONMENT_REQUIRED",e.FETCH_CARDS_ERROR="FETCH_CARDS_ERROR",e.FETCH_TRANSACTION_ERROR="FETCH_TRANSACTION_ERROR",e.CUSTOMER_AUTH_TOKEN_NOT_VALID="CUSTOMER_AUTH_TOKEN_NOT_VALID",e.SAVE_CARD_ERROR="SAVE_CARD_ERROR",e.REMOVE_CARD_ERROR="REMOVE_CARD_ERROR",e.SUMMARY_CARD_ERROR="SUMMARY_CARD_ERROR",e.CREATE_PAYMENT_ERROR="CREATE_PAYMENT_ERROR",e.PAYMENT_PROCESS_ERROR="PAYMENT_PROCESS_ERROR",e.INVALID_CARD_DATA="INVALID_CARD_DATA",e.SAVE_CARD_PROCESS_ERROR="SAVE_CARD_PROCESS_ERROR",e.START_CHECKOUT_ERROR="START_CHECKOUT_ERROR",e.CREATE_ORDER_ERROR="CREATE_ORDER_ERROR",e.BUSINESS_ID_REQUIRED="BUSINESS_ID_REQUIRED",e.CLIENT_ID_REQUIRED="CLIENT_ID_REQUIRED",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INVALID_ITEMS="INVALID_ITEMS",e.CUSTOMER_OPERATION_ERROR="CUSTOMER_OPERATION_ERROR",e.INVALID_EMAIL="INVALID_EMAIL",e.FETCH_PAYMENT_METHODS_ERROR="FETCH_PAYMENT_METHODS_ERROR",e.INVALID_VAULT_TOKEN="INVALID_VAULT_TOKEN",e.VAULT_TOKEN_ERROR="VAULT_TOKEN_ERROR",e.SECURE_TOKEN_ERROR="SECURE_TOKEN_ERROR",e.SECURE_TOKEN_INVALID="SECURE_TOKEN_INVALID",e.INVALID_SECRET_API_KEY="INVALID_SECRET_API_KEY",e.REMOVE_CARD="REMOVE_CARD",e.SKYFLOW_NOT_INITIALIZED="SKYFLOW_NOT_INITIALIZED",e.ERROR_LOAD_PAYMENT_FORM="ERROR_LOAD_PAYMENT_FORM",e.ERROR_LOAD_ENROLLMENT_FORM="ERROR_LOAD_ENROLLMENT_FORM",e.MOUNT_COLLECT_ERROR="MOUNT_COLLECT_ERROR",e.CARD_ON_FILE_DECLINED="CARD_ON_FILE_DECLINED",e.CARD_SAVED_SUCCESSFULLY="CARD_SAVED_SUCCESSFULLY",e.CARD_REMOVED_SUCCESSFULLY="CARD_REMOVED_SUCCESSFULLY",e.REQUEST_ABORTED="REQUEST_ABORTED",e.REQUEST_FAILED="REQUEST_FAILED",e.UNKNOWN_ERROR="UNKNOWN_ERROR",e.THREEDS_REDIRECTION_ERROR="THREEDS_REDIRECTION_ERROR"}(s||(s={}));const a={[s.INIT_ERROR]:"Error initializing the SDK.",[s.INVALID_TYPE]:"SDK Type invalid.",[s.STATE_ERROR]:"Error updating SDK state.",[s.FETCH_BUSINESS_ERROR]:"Error retrieving merchant information.",[s.INVALID_CONFIG]:"Required configuration options.",[s.MERCHANT_CREDENTIAL_REQUIRED]:"Merchant credential required.",[s.INVALID_PAYMENT_REQUEST]:"The payment data must be of type: :::interface:::.",[s.INVALID_PAYMENT_REQUEST_CARD_PM]:"The fields card and payment_method cannot be provided together.",[s.TYPE_SDK_REQUIRED]:"SDK type required.",[s.ENVIRONMENT_REQUIRED]:"Environment required.",[s.FETCH_CARDS_ERROR]:"Error retrieving cards.",[s.CUSTOMER_AUTH_TOKEN_NOT_VALID]:"The customer's auth token is invalid. Please verify that the customer's data was provided when creating the SDK (sdk.create) and try again.",[s.SAVE_CARD_ERROR]:"Error saving the card.",[s.REMOVE_CARD_ERROR]:"Error deleting the card.",[s.CREATE_PAYMENT_ERROR]:"Error creating the payment.",[s.PAYMENT_PROCESS_ERROR]:"There was an issue processing the payment.",[s.CARD_SAVED_SUCCESSFULLY]:"Card saved successfully.",[s.CARD_REMOVED_SUCCESSFULLY]:"Card deleted successfully.",[s.SAVE_CARD_PROCESS_ERROR]:"Error processing card data.",[s.START_CHECKOUT_ERROR]:"Error processing the payment.",[s.CREATE_ORDER_ERROR]:"Error creating the order.",[s.BUSINESS_ID_REQUIRED]:"Business ID is required.",[s.CLIENT_ID_REQUIRED]:"Client ID is required.",[s.INVALID_AMOUNT]:"Invalid amount.",[s.INVALID_ITEMS]:"Invalid items.",[s.CUSTOMER_OPERATION_ERROR]:"Error registering or fetching customer",[s.INVALID_EMAIL]:"Invalid email.",[s.FETCH_PAYMENT_METHODS_ERROR]:"Error retrieving active payment methods.",[s.INVALID_VAULT_TOKEN]:"An invalid vault token response was received.",[s.VAULT_TOKEN_ERROR]:"Error retrieving the vault token.",[s.SECURE_TOKEN_ERROR]:"Error getting secure token.",[s.SECURE_TOKEN_INVALID]:"Invalid secure token.",[s.INVALID_SECRET_API_KEY]:"SECRET API KEY is required.",[s.REMOVE_CARD]:"Card deleted successfully",[s.SKYFLOW_NOT_INITIALIZED]:"Skyflow not initialized.",[s.ERROR_LOAD_PAYMENT_FORM]:"There was an issue loading the payment form.",[s.INVALID_CARD_DATA]:"Invalid card data.",[s.ERROR_LOAD_ENROLLMENT_FORM]:"There was an issue loading the card form.",[s.MOUNT_COLLECT_ERROR]:"Mount failed. Make sure all inputs are complete and valid.",[s.CARD_ON_FILE_DECLINED]:"Transaction declined. Please verify your card details.",[s.REQUEST_ABORTED]:"Requests canceled.",[s.REQUEST_FAILED]:"Request failed.",[s.UNKNOWN_ERROR]:"An unexpected error occurred.",[s.CREATE_ERROR]:"Error creating the SDK.",[s.FETCH_TRANSACTION_ERROR]:"Error retrieving the transaction.",[s.THREEDS_REDIRECTION_ERROR]:"Ocurrió un error durante la redirección de 3DS.",[s.REMOVE_SDK_ERROR]:"Ocurrió un error removiendo la instancia del SDK."};s.INIT_ERROR,s.STATE_ERROR,s.FETCH_BUSINESS_ERROR,s.INVALID_CONFIG,s.TYPE_SDK_REQUIRED,s.ENVIRONMENT_REQUIRED,s.FETCH_CARDS_ERROR,s.SAVE_CARD_ERROR,s.REMOVE_CARD_ERROR,s.CREATE_PAYMENT_ERROR,s.START_CHECKOUT_ERROR,s.CREATE_ORDER_ERROR,s.BUSINESS_ID_REQUIRED,s.CLIENT_ID_REQUIRED,s.INVALID_AMOUNT,s.INVALID_ITEMS,s.CUSTOMER_OPERATION_ERROR,s.INVALID_EMAIL,s.FETCH_PAYMENT_METHODS_ERROR,s.INVALID_VAULT_TOKEN,s.VAULT_TOKEN_ERROR,s.SECURE_TOKEN_ERROR,s.INVALID_SECRET_API_KEY,s.CUSTOMER_AUTH_TOKEN_NOT_VALID,s.SECURE_TOKEN_INVALID,s.REMOVE_CARD,s.SKYFLOW_NOT_INITIALIZED,s.INVALID_TYPE,s.PAYMENT_PROCESS_ERROR,s.INVALID_PAYMENT_REQUEST,s.INVALID_PAYMENT_REQUEST_CARD_PM,s.SAVE_CARD_PROCESS_ERROR,s.ERROR_LOAD_PAYMENT_FORM,s.INVALID_CARD_DATA,s.ERROR_LOAD_ENROLLMENT_FORM,s.MOUNT_COLLECT_ERROR,s.CARD_ON_FILE_DECLINED,s.CARD_SAVED_SUCCESSFULLY,s.CARD_REMOVED_SUCCESSFULLY,s.REQUEST_ABORTED,s.REQUEST_FAILED,s.UNKNOWN_ERROR,s.CREATE_ERROR,s.FETCH_TRANSACTION_ERROR,s.THREEDS_REDIRECTION_ERROR,s.REMOVE_SDK_ERROR;class d extends Error{constructor(e){var t,r;const o=e.message||a[e.code]||"Unknown error";super(o),this.name="TonderError",this.code=e.code,this.details={code:(null===(t=e.details)||void 0===t?void 0:t.code)||e.code,message:(null===(r=e.details)||void 0===r?void 0:r.message)||o}}}const l=()=>({javascript_enabled:!0,time_zone:(new Date).getTimezoneOffset(),language:navigator.language||"en-US",color_depth:window.screen?window.screen.colorDepth:null,screen_width:window.screen?window.screen.width*window.devicePixelRatio||window.screen.width:null,screen_height:window.screen?window.screen.height*window.devicePixelRatio||window.screen.height:null,user_agent:navigator.userAgent}),c=e=>{var t;return e&&"business"in e?null===(t=null==e?void 0:e.business)||void 0===t?void 0:t.pk:""},u="__tonderLockErrorCode__";function h(e){return"object"==typeof e&&null!==e}class E extends Error{constructor(e){var t,r;const o=E.resolveStatusCode(e.statusCode,e.originalError),n=E.resolveMessage(e.errorCode,e.message),i=E.resolveSystemError(null===(t=e.details)||void 0===t?void 0:t.systemError,e.originalError);super(n),this.status="error",Object.setPrototypeOf(this,new.target.prototype),this.name="TonderError",this.code=e.errorCode,this.statusCode=o,this.originalError=e.originalError,this.details={code:e.errorCode,statusCode:o,systemError:i},e.lockErrorCode&&Object.defineProperty(this,u,{value:!0,enumerable:!1,configurable:!0}),null===(r=Error.captureStackTrace)||void 0===r||r.call(Error,this,E)}static isRecord(e){return"object"==typeof e&&null!==e}static parseStatusCode(e){const t=Number(e);return Number.isFinite(t)?t<100||t>599?500:Math.trunc(t):500}static resolveStatusCode(e,t){const r=[e];if(E.isRecord(t)){r.push(t.statusCode,t.status);const e=E.isRecord(t.body)?t.body:null;e&&r.push(e.statusCode,e.status)}for(const e of r)if(E.isHttpStatusCode(e))return Math.trunc(Number(e));return 500}static resolveMessage(e,t){return t||(a[e]||a[s.UNKNOWN_ERROR]||"An unexpected error occurred.")}static isHttpStatusCode(e){const t=Number(e);return Number.isFinite(t)&&t>=100&&t<=599}static normalizeSystemError(e){if("string"!=typeof e)return null;return e.trim()||null}static resolveSystemError(e,t){const r=[e];if(E.isRecord(t)){const e=E.isRecord(t.details)?t.details:null,o=E.isRecord(t.body)?t.body:null,n=o&&E.isRecord(o.details)?o.details:null;r.push(t.systemError,t.code,null==e?void 0:e.systemError,null==e?void 0:e.code,null==o?void 0:o.systemError,null==o?void 0:o.code,null==n?void 0:n.systemError,null==n?void 0:n.code)}for(const e of r){const t=E.normalizeSystemError(e);if(t)return t}return"APP_INTERNAL_001"}}function _(e){return h(e)&&!0===e[u]}function p(e){return e instanceof E&&void 0!==e.originalError?e.originalError:e}function R(e,t){var r;if(!(null==e?void 0:e.errorCode))throw new Error("buildPublicAppError requires errorCode");const o=null===(r=e.details)||void 0===r?void 0:r.systemError,n=!!e.message||void 0!==e.statusCode||void 0!==o;return!function(e){return h(e)&&"TonderError"===e.name&&"string"==typeof e.code}(t)||(e.lockErrorCode&&function(e){Object.defineProperty(e,u,{value:!0,enumerable:!1,configurable:!0})}(t),n||e.errorCode!==t.code&&!_(t))?new E({errorCode:e.errorCode,message:e.message,statusCode:e.statusCode,details:void 0!==o?{systemError:o}:void 0,originalError:p(t),lockErrorCode:e.lockErrorCode||_(t)}):t}function m(e){var t,o;return r(this,void 0,void 0,(function*(){const n=yield function(e){return r(this,void 0,void 0,(function*(){try{return yield e.clone().json()}catch(e){}try{return(yield e.text())||void 0}catch(e){return}}))}(e.response),i={status:e.response.status};return e.response.statusText&&(i.statusText=e.response.statusText),void 0!==n&&(i.body=n),new E({errorCode:e.errorCode,message:e.message,statusCode:null!==(t=e.statusCode)&&void 0!==t?t:e.response.status,details:void 0!==(null===(o=e.details)||void 0===o?void 0:o.systemError)?{systemError:e.details.systemError}:void 0,originalError:i,lockErrorCode:e.lockErrorCode})}))}function y(e,t){return(null==e?void 0:e.response)?m(e):R(e,t)}class v{constructor({payload:e=null,apiKey:t,baseUrl:r,redirectOnComplete:o,tdsIframeId:n,tonderPayButtonId:i,callBack:s}){this.localStorageKey="verify_transaction_status_url",this.setPayload=e=>{this.payload=e},this.baseUrl=r,this.apiKey=t,this.payload=e,this.tdsIframeId=n,this.tonderPayButtonId=i,this.redirectOnComplete=o,this.callBack=s}setStorageItem(e){return localStorage.setItem(this.localStorageKey,JSON.stringify(e))}getStorageItem(){return localStorage.getItem(this.localStorageKey)}removeStorageItem(){return localStorage.removeItem(this.localStorageKey)}saveVerifyTransactionUrl(){var e,t,r,o,n,i;const s=null===(r=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===r?void 0:r.verify_transaction_status_url;if(s)this.saveUrlWithExpiration(s);else{const e=null===(i=null===(n=null===(o=this.payload)||void 0===o?void 0:o.next_action)||void 0===n?void 0:n.iframe_resources)||void 0===i?void 0:i.verify_transaction_status_url;e?this.saveUrlWithExpiration(e):console.log("No verify_transaction_status_url found")}}saveUrlWithExpiration(e){try{const t={url:e,expires:(new Date).getTime()+12e5};this.setStorageItem(t)}catch(e){console.log("error: ",e)}}getUrlWithExpiration(){const e=this.getStorageItem();if(e){const t=JSON.parse(e);if(!t)return;return(new Date).getTime()>t.expires?(this.removeVerifyTransactionUrl(),null):t.url}return null}removeVerifyTransactionUrl(){return this.removeStorageItem()}getVerifyTransactionUrl(){return this.getStorageItem()}loadIframe(){var e,t,r;if(null===(r=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===r?void 0:r.iframe)return new Promise(((e,t)=>{var r,o,n;const i=null===(n=null===(o=null===(r=this.payload)||void 0===r?void 0:r.next_action)||void 0===o?void 0:o.iframe_resources)||void 0===n?void 0:n.iframe;if(i){this.saveVerifyTransactionUrl();const r=document.createElement("div");r.innerHTML=i,document.body.appendChild(r);const o=document.createElement("script");o.textContent='document.getElementById("tdsMmethodForm").submit();',r.appendChild(o);const n=document.getElementById("tdsMmethodTgtFrame");n?n.onload=()=>e(!0):(console.log("No redirection found"),t(!1))}else console.log("No redirection found"),t(!1)}))}getRedirectUrl(){var e,t,r;return null===(r=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===r?void 0:r.url}redirectToChallenge(){const e=this.getRedirectUrl();if(e)if(this.saveVerifyTransactionUrl(),this.redirectOnComplete)window.location=e;else{const t=document.querySelector(`#${this.tdsIframeId}`);if(t){t.setAttribute("src",e),t.setAttribute("style","display: block");const o=this,n=e=>r(this,void 0,void 0,(function*(){const e=()=>{try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}t&&t.setAttribute("style","display: none"),o.callBack&&o.callBack(o.payload),t.removeEventListener("load",n)},i=t=>r(this,void 0,void 0,(function*(){const n=yield new Promise(((e,r)=>e(t)));if(n){if((e=>"Pending"!==(null==e?void 0:e.transaction_status))(n))return e();{const e=setTimeout((()=>r(this,void 0,void 0,(function*(){clearTimeout(e),yield i(o.requestTransactionStatus())}))),7e3)}}}));yield i(o.requestTransactionStatus())}));t.addEventListener("load",n)}else console.log("No iframe found")}else this.callBack&&this.callBack(this.payload)}requestTransactionStatus(){return r(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration(),t=e.startsWith("https://")?e:`${this.baseUrl}${e}`,r=yield fetch(t,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});if(200!==r.status)return console.error("La verificación de la transacción falló."),null;return yield r.json()}))}getURLParameters(){const e={},t=new URLSearchParams(window.location.search);for(const[r,o]of t)e[r]=o;return e}handleSuccessTransaction(e){return this.removeVerifyTransactionUrl(),e}handleDeclinedTransaction(e){return this.removeVerifyTransactionUrl(),e}handle3dsChallenge(e){return r(this,void 0,void 0,(function*(){const t=document.createElement("form");t.name="frm",t.method="POST",t.action=e.redirect_post_url;const r=document.createElement("input");r.type="hidden",r.name=e.creq,r.value=e.creq,t.appendChild(r);const o=document.createElement("input");o.type="hidden",o.name=e.term_url,o.value=e.TermUrl,t.appendChild(o),document.body.appendChild(t),t.submit(),yield this.verifyTransactionStatus()}))}handleTransactionResponse(e){return r(this,void 0,void 0,(function*(){const t=yield e.json();return"Pending"===t.status&&t.redirect_post_url?yield this.handle3dsChallenge(t):["Success","Authorized"].includes(t.status)?this.handleSuccessTransaction(t):(this.handleDeclinedTransaction(e),t)}))}verifyTransactionStatus(){return r(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration();if(e){const t=e.startsWith("https://")?e:`${this.baseUrl}${e}`;try{const e=yield fetch(t,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});return 200!==e.status?(console.error("La verificación de la transacción falló."),this.removeVerifyTransactionUrl(),e):yield this.handleTransactionResponse(e)}catch(e){console.error("Error al verificar la transacción:",e),this.removeVerifyTransactionUrl()}}else console.log("No verify_transaction_status_url found")}))}}const f=Object.freeze({production:"https://app.tonder.io",sandbox:"https://sandbox.tonder.io",stage:"https://stage.tonder.io",development:"http://localhost:8000"});function C(e,t,o){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/checkout-router/`,n=o,i=yield fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(Object.assign(Object.assign({},n),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}))});if(i.ok)return yield i.json();throw yield y({response:i,errorCode:s.START_CHECKOUT_ERROR})}))}function A(e,t,o=!0,n=null){return r(this,void 0,void 0,(function*(){let r=yield window.OpenPay;return r.setId(e),r.setApiKey(t),r.setSandboxMode(o),yield r.deviceData.setup({signal:n})}))}const O=Object.freeze({production:"https://api.tonder.io",sandbox:"https://api-stage.tonder.io",stage:"https://api-stage.tonder.io",development:"https://api-stage.tonder.io"}),T=Object.freeze({TELEMETRY:"/telemetry/v1/events",ACQ_SUBSCRIPTION_TOKEN:"/acq-kushki/subscription/token",ACQ_SUBSCRIPTION_CREATE:"/acq-kushki/subscription/create"});function g(e="stage"){return`${O[e]}${T.TELEMETRY}`}const S="https://cdn.kushkipagos.com/kushki.min.js",I=s.CARD_ON_FILE_DECLINED;let N=!1,D=null;class b{constructor(e){var t;this.acquirerInstance=null,this.isTestEnvironment=null===(t=e.isTestEnvironment)||void 0===t||t;const r=this.isTestEnvironment?"stage":"production";this.apiUrl=function(e="stage"){return O[e]}(r),this.merchantId=e.merchantId,this.apiKey=e.apiKey}initialize(){return r(this,void 0,void 0,(function*(){yield function(){return r(this,void 0,void 0,(function*(){return N?Promise.resolve():D||(D=new Promise(((e,t)=>{if(document.querySelector(`script[src="${S}"]`))return N=!0,void e();const r=document.createElement("script");r.src=S,r.async=!0,r.onload=()=>{N=!0,e()},r.onerror=()=>{D=null,t(y({errorCode:I,lockErrorCode:!0,details:{step:"load_acquirer_script",message:"Failed to load acquirer script"}}))},document.head.appendChild(r)})),D)}))}(),this.acquirerInstance=function(e,t){if(!window.Kushki)throw y({errorCode:I,lockErrorCode:!0,details:{step:"create_acquirer_instance",message:"Acquirer script not loaded. Call initialize() first."}});return new window.Kushki({merchantId:e,inTestEnvironment:t})}(this.merchantId,this.isTestEnvironment)}))}getAcquirerInstance(){if(!this.acquirerInstance)throw y({errorCode:I,lockErrorCode:!0,details:{step:"get_acquirer_instance",message:"CardOnFile not initialized. Call initialize() first."}});return this.acquirerInstance}getJwt(e){return r(this,void 0,void 0,(function*(){const t=this.getAcquirerInstance();return new Promise(((r,o)=>{t.requestSecureInit({card:{number:e}},(e=>{if("code"in e&&e.code)return void o(y({errorCode:I,lockErrorCode:!0,details:{step:"get_jwt",acquirerResponse:e}}));const t=e;t.jwt?r(t.jwt):o(y({errorCode:I,lockErrorCode:!0,details:{step:"get_jwt",message:"No JWT returned from acquirer",acquirerResponse:t}}))}))}))}))}generateToken(e){return r(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}${T.ACQ_SUBSCRIPTION_TOKEN}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`},body:JSON.stringify(e)});if(!t.ok)throw yield y({response:t,errorCode:I,lockErrorCode:!0,details:{step:"generate_token"}});return t.json()}))}createSubscription(e){return r(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}${T.ACQ_SUBSCRIPTION_CREATE}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`},body:JSON.stringify(e)});if(!t.ok)throw yield y({response:t,errorCode:I,lockErrorCode:!0,details:{step:"create_subscription"}});return t.json()}))}validate3DS(e,t){return r(this,void 0,void 0,(function*(){const r=this.getAcquirerInstance();return new Promise(((o,n)=>{r.requestValidate3DS({secureId:e,security:t},(e=>{const t=e;t.code&&"3DS000"!==t.code?n(y({errorCode:I,lockErrorCode:!0,details:{step:"validate_3ds",message:"3DS validation failed",acquirerResponse:t}})):!1!==t.isValid?o(!0):n(y({errorCode:I,lockErrorCode:!0,details:{step:"validate_3ds",message:"3DS validation failed",acquirerResponse:t}}))}))}))}))}process(e){var t,o;return r(this,void 0,void 0,(function*(){const r=yield this.getJwt(e.cardBin),n=yield this.generateToken({card:e.cardTokens,currency:e.currency,jwt:r}),i=n.secureId||(null===(t=n.details)||void 0===t?void 0:t.secureId),s=n.security||(null===(o=n.details)||void 0===o?void 0:o.security);if(!i||!s)throw y({errorCode:I,lockErrorCode:!0,details:{step:"process",message:"Missing secureId or security in token response",tokenResponse:n}});return yield this.validate3DS(i,s),this.createSubscription({token:n.token,contactDetails:e.contactDetails,metadata:{customerId:e.customerId},currency:e.currency})}))}}class M{constructor(e){this.REQUEST_TIMEOUT_MS=5e3,this.MAX_MESSAGE_LENGTH=500,this.config=e}captureException(e,t){try{const r=this.buildEvent(e,t||{});this.sendEvent(r)}catch(e){}}extractErrorInfo(e){try{if(e instanceof Error)return{name:e.name||"Error",message:this.truncate(e.message||"Unknown error",this.MAX_MESSAGE_LENGTH),stack:e.stack||void 0};const t=this.safeStringify(e);return{name:"NonErrorException",message:this.truncate(t,this.MAX_MESSAGE_LENGTH),stack:void 0}}catch(e){return{name:"SerializationError",message:"Failed to serialize error",stack:void 0}}}safeStringify(e){try{const t=new WeakSet;return JSON.stringify(e,((e,r)=>{if("object"==typeof r&&null!==r){if(t.has(r))return"[Circular]";t.add(r)}return r}))}catch(t){return String(e)}}buildEvent(e,t){const r=this.extractErrorInfo(e),o=Object.assign({},t.metadata||{});void 0===o.error&&(o.error=e),"undefined"!=typeof window&&(o.url=window.location.href);const n={platform:this.config.platform,platform_version:this.config.platform_version,env:this.config.mode,feature:t.feature||"unknown",level:"error",message:r.message,name:r.name,metadata:o};return t.tenant_id&&(n.tenant_id=t.tenant_id),t.request_id&&(n.request_id=t.request_id),t.process_id&&(n.process_id=t.process_id),t.user_id&&(n.user_id=t.user_id),r.stack&&(n.stack=r.stack),t.error_code&&(n.error_code=t.error_code),t.http_status&&(n.http_status=t.http_status),n}truncate(e,t){return e.length<=t?e:e.substring(0,t)+"..."}sendEvent(e){this.sendHttpRequest(e).then((()=>{})).catch((()=>{}))}sendHttpRequest(e){return r(this,void 0,void 0,(function*(){try{const t=JSON.stringify(e),r=new AbortController,o=setTimeout((()=>r.abort()),this.REQUEST_TIMEOUT_MS);try{const e=yield fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.config.apiKey}`},body:t,keepalive:!0,signal:r.signal});return clearTimeout(o),e.ok}catch(e){return clearTimeout(o),!1}}catch(e){return!1}}))}}const k=Object.freeze({name:"@tonder.io/ionic-lite-sdk",version:"0.0.69"});var U,L,w,P,j,V,F,K,x,B,Y,$,H;class z{constructor({mode:e="stage",customization:t,apiKey:r,apiKeyTonder:o,returnUrl:n,tdsIframeId:i,callBack:s=(()=>{}),baseUrlTonder:a,tonderPayButtonId:d,sdkInfo:l}){U.add(this),this.baseUrl="",this.cartTotal="0",this.secureToken="",this.customization={redirectOnComplete:!0},this.metadata={},this.order_reference=null,this.card={},this.currency="",this.cardOnFileInstance=null,L.set(this,void 0),w.set(this,void 0),this.apiKeyTonder=o||r||"",this.returnUrl=n,this.callBack=s,this.mode=e,this.customer={},this.baseUrl=a||f[this.mode]||f.stage,this.abortController=new AbortController,this.requestId=this.generateRequestId(),this.customization=Object.assign(Object.assign({},this.customization),t||{}),this.process3ds=new v({apiKey:r,baseUrl:this.baseUrl,redirectOnComplete:this.customization.redirectOnComplete,tdsIframeId:i,tonderPayButtonId:d,callBack:s}),this.tdsIframeId=i;const c=l||k;this.telemetry=new M({endpoint:g(this.mode),apiKey:this.apiKeyTonder,platform:c.name,platform_version:c.version,mode:this.mode||"stage"})}configureCheckout(e){"secureToken"in e&&o(this,U,"m",V).call(this,e.secureToken),o(this,U,"m",P).call(this,e)}getCustomerId(){var e,t;return null===(t=null===(e=o(this,w,"f"))||void 0===e?void 0:e.id)||void 0===t?void 0:t.toString()}reportSdkError(e,t){var r,o,n,i;try{const s=this.getCustomerId(),a=e instanceof E&&void 0!==e.originalError?e.originalError:e,d=Object.assign(Object.assign({},(null==t?void 0:t.metadata)||{}),void 0===(null===(r=null==t?void 0:t.metadata)||void 0===r?void 0:r.error)?{error:a}:{}),l=Object.assign(Object.assign({tenant_id:null===(i=null===(n=null===(o=this.merchantData)||void 0===o?void 0:o.business)||void 0===n?void 0:n.pk)||void 0===i?void 0:i.toString(),user_id:s},t||{}),{metadata:d,request_id:this.requestId});l.user_id||delete l.user_id,l.feature=(null==t?void 0:t.feature)||"unknown",this.telemetry.captureException(e,l)}catch(e){}}generateRequestId(){return`req_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}verify3dsTransaction(){return r(this,void 0,void 0,(function*(){const e=yield this.process3ds.verifyTransactionStatus(),t=yield o(this,U,"m",Y).call(this,e);return this.process3ds.setPayload(t),this._handle3dsRedirect(t)}))}payment(e){return new Promise(((t,n)=>r(this,void 0,void 0,(function*(){var r,i;let a;try{o(this,U,"m",P).call(this,e),a=yield this._checkout(e),this.process3ds.setPayload(a);if(yield this._handle3dsRedirect(a)){try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}this.callBack&&this.callBack(a),t(a)}}catch(t){this.reportSdkError(t,{feature:"payment",process_id:(null==a?void 0:a.payment_id)||(null===(r=null==a?void 0:a.payment)||void 0===r?void 0:r.id)||(null===(i=null==a?void 0:a.payment)||void 0===i?void 0:i.pk),metadata:{step:"payment",request:e,response:a}}),n(y({errorCode:s.PAYMENT_PROCESS_ERROR},t))}}))))}getSecureToken(e){return r(this,void 0,void 0,(function*(){try{return yield function(e,t,o=null){return r(this,void 0,void 0,(function*(){const r=yield fetch(`${e}/api/secure-token/`,{method:"POST",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:o});if(r.ok)return yield r.json();throw yield y({response:r,errorCode:s.SECURE_TOKEN_ERROR})}))}(this.baseUrl,e)}catch(e){throw this.reportSdkError(e,{feature:"secure-token",metadata:{step:"getSecureToken"}}),y({errorCode:s.SECURE_TOKEN_ERROR},e)}}))}_initializeCheckout(){return r(this,void 0,void 0,(function*(){const e=yield this._fetchMerchantData();e&&e.mercado_pago&&e.mercado_pago.active&&function(){try{const e=document.createElement("script");e.src="https://www.mercadopago.com/v2/security.js",e.setAttribute("view",""),e.onload=()=>{},e.onerror=e=>{console.error("Error loading Mercado Pago script:",e)},document.head.appendChild(e)}catch(e){console.error("Error attempting to inject Mercado Pago script:",e)}}(),this._hasCardOnFileKeys()&&(yield this._initializeCardOnFile())}))}_checkout(e){return r(this,void 0,void 0,(function*(){throw new Error("The #checkout method should be implement in child classes.")}))}_setCartTotal(e){throw new Error("The #setCartTotal method should be implement in child classes.")}_getCustomer(e=null){return r(this,void 0,void 0,(function*(){return o(this,w,"f")||n(this,w,yield function(e,t,o,n=null){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/customer/`,i={email:o.email,first_name:null==o?void 0:o.firstName,last_name:null==o?void 0:o.lastName,phone:null==o?void 0:o.phone},a=yield fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},signal:n,body:JSON.stringify(i)});if(a.ok)return yield a.json();throw yield y({response:a,errorCode:s.CUSTOMER_OPERATION_ERROR})}))}(this.baseUrl,this.apiKeyTonder,this.customer,e),"f"),o(this,w,"f")}))}_handleCheckout({card:t,payment_method:n,customer:i,isSandbox:a,enable_card_on_file:d,returnUrl:c}){return r(this,void 0,void 0,(function*(){const{openpay_keys:u,reference:h,business:E}=this.merchantData,_=Number(this.cartTotal);let p,R,m;try{let v;!v&&u.merchant_id&&u.public_key&&!n&&(v=yield A(u.merchant_id,u.public_key,a,this.abortController.signal));const{id:f,auth_token:O}=i;p={business:this.apiKeyTonder,client:O,billing_address_id:null,shipping_address_id:null,amount:_,status:"A",reference:h,is_oneclick:!0,items:this.cartItems,currency:this.currency,metadata:this.metadata};const T=yield function(e,t,o){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/orders/`,n=o,i=yield fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(n)});if(i.ok)return yield i.json();throw yield y({response:i,errorCode:s.CREATE_ORDER_ERROR})}))}(this.baseUrl,this.apiKeyTonder,p),g=(new Date).toISOString();R={business_pk:E.pk,client_id:f,amount:_,date:g,order_id:T.id,customer_order_reference:this.order_reference?this.order_reference:h,items:this.cartItems,currency:this.currency,metadata:this.metadata};const S=yield function(e,t,o){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/business/${o.business_pk}/payments/`,n=o,i=yield fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${t}`},body:JSON.stringify(n)});if(i.ok)return yield i.json();throw yield y({response:i,errorCode:s.CREATE_PAYMENT_ERROR})}))}(this.baseUrl,this.apiKeyTonder,R);m=Object.assign(Object.assign(Object.assign(Object.assign({name:e(this.customer,"firstName",e(this.customer,"name","")),last_name:e(this.customer,"lastName",e(this.customer,"lastname","")),email_client:e(this.customer,"email",""),phone_number:e(this.customer,"phone",""),return_url:c||this.returnUrl,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:_,title_ship:"shipping",description:"transaction",device_session_id:v||null,token_id:"",order_id:T.id,business_id:E.pk,payment_id:S.pk,source:"sdk",items:this.cartItems,metadata:this.metadata,browser_info:l(),currency:this.currency},n?{payment_method:n}:{card:t}),{apm_config:o(this,L,"f")}),this.customer&&"identification"in this.customer?{identification:this.customer.identification}:{}),void 0!==d?{enable_card_on_file:d}:{});const I=yield C(this.baseUrl,this.apiKeyTonder,m);return I||!1}catch(e){throw this.reportSdkError(e,{feature:"payment",process_id:null==m?void 0:m.payment_id,metadata:{step:"_handleCheckout",orderItems:p,paymentItems:R,routerItems:m}}),e}}))}_fetchMerchantData(){return r(this,void 0,void 0,(function*(){try{return this.merchantData||(this.merchantData=yield i(this.baseUrl,this.apiKeyTonder,this.abortController.signal)),this.merchantData}catch(e){return this.reportSdkError(e,{feature:"fetch-merchant-data",metadata:{step:"_fetchMerchantData"}}),this.merchantData}}))}_getCustomerCards(e,t){return r(this,void 0,void 0,(function*(){return yield function(e,t,o,n,i=null){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/business/${n}/cards/`,a=yield fetch(r,{method:"GET",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":t},signal:i});if(a.ok)return yield a.json();if(401===a.status)return{user_id:0,cards:[]};throw yield y({response:a,errorCode:s.FETCH_CARDS_ERROR})}))}(this.baseUrl,e,this.secureToken,t)}))}_saveCustomerCard(e,t,o,n=!1){return r(this,void 0,void 0,(function*(){return yield function(e,t,o,n,i,a=!1){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/business/${n}/cards/`,d=yield fetch(r,{method:"POST",headers:Object.assign({Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":t},a?{"X-App-Origin":"sdk/ionic"}:{}),body:JSON.stringify(i)});if(d.ok)return yield d.json();throw yield y({response:d,errorCode:s.SAVE_CARD_ERROR})}))}(this.baseUrl,e,this.secureToken,t,o,n)}))}_removeCustomerCard(e,t,o){return r(this,void 0,void 0,(function*(){return yield function(e,t,o,n="",i){return r(this,void 0,void 0,(function*(){const r=`${e}/api/v1/business/${i}/cards/${n}`,d=yield fetch(r,{method:"DELETE",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":t}});if(204===d.status)return a[s.CARD_REMOVED_SUCCESSFULLY];if(d.ok&&"json"in d)return yield d.json();throw yield y({response:d,errorCode:s.REMOVE_CARD_ERROR})}))}(this.baseUrl,e,this.secureToken,o,t)}))}_fetchCustomerPaymentMethods(){return r(this,void 0,void 0,(function*(){return yield function(e,t,o={status:"active",pagesize:"10000"},n=null){return r(this,void 0,void 0,(function*(){const r=new URLSearchParams(o).toString(),i=yield fetch(`${e}/api/v1/payment_methods?${r}`,{method:"GET",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:n});if(i.ok)return yield i.json();throw yield y({response:i,errorCode:s.FETCH_PAYMENT_METHODS_ERROR})}))}(this.baseUrl,this.apiKeyTonder)}))}_hasCardOnFileKeys(){var e,t;return!!(null===(t=null===(e=this.merchantData)||void 0===e?void 0:e.cardonfile_keys)||void 0===t?void 0:t.public_key)}_initializeCardOnFile(){var e;return r(this,void 0,void 0,(function*(){return this.cardOnFileInstance||(this.cardOnFileInstance=new b({merchantId:null===(e=this.merchantData)||void 0===e?void 0:e.cardonfile_keys.public_key,apiKey:this.apiKeyTonder,isTestEnvironment:"production"!==this.mode}),yield this.cardOnFileInstance.initialize()),this.cardOnFileInstance}))}_handle3dsRedirect(e){var t,o;return r(this,void 0,void 0,(function*(){if(e&&"next_action"in e?null===(o=null===(t=null==e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===o?void 0:o.iframe:null)this.process3ds.loadIframe().then((()=>{this.process3ds.verifyTransactionStatus()})).catch((t=>{console.log("Error loading iframe:",t),this.reportSdkError(t,{feature:"3ds-verification",metadata:{step:"_handle3dsRedirect",response:e}})}));else{if(!this.process3ds.getRedirectUrl())return e;this.process3ds.redirectToChallenge()}}))}}function q(e,t,o=null){return r(this,void 0,void 0,(function*(){const r=yield fetch(`${e}/api/v1/vault-token/`,{method:"GET",headers:{Authorization:`Token ${t}`},signal:o});if(r.ok){return(yield r.json()).token}throw yield y({response:r,errorCode:s.VAULT_TOKEN_ERROR})}))}L=new WeakMap,w=new WeakMap,U=new WeakSet,P=function(e){var t,r;!e||e&&0===Object.keys(e).length||(o(this,U,"m",j).call(this,e.customer),this._setCartTotal((null===(t=e.cart)||void 0===t?void 0:t.total)||0),o(this,U,"m",F).call(this,(null===(r=e.cart)||void 0===r?void 0:r.items)||[]),o(this,U,"m",K).call(this,e),o(this,U,"m",x).call(this,e),o(this,U,"m",B).call(this,e),o(this,U,"m",$).call(this,e))},j=function(e){e&&(this.customer=e)},V=function(e){this.secureToken=e},F=function(e){this.cartItems=e},K=function(e){this.metadata=null==e?void 0:e.metadata,this.order_reference=null==e?void 0:e.order_reference},x=function(e){this.currency=null==e?void 0:e.currency},B=function(e){this.card=null==e?void 0:e.card},Y=function(e){var t,o,n,i,s;return r(this,void 0,void 0,(function*(){if("Hard"===(null===(t=null==e?void 0:e.decline)||void 0===t?void 0:t.error_type)||(null===(o=null==e?void 0:e.checkout)||void 0===o?void 0:o.is_route_finished)||(null==e?void 0:e.is_route_finished)||["Pending"].includes(null==e?void 0:e.transaction_status))return e;if(["Success","Authorized"].includes(null==e?void 0:e.transaction_status))return e;if(e){const t={checkout_id:(null===(n=e.checkout)||void 0===n?void 0:n.id)||(null==e?void 0:e.checkout_id)};try{return yield C(this.baseUrl,this.apiKeyTonder,t)}catch(t){this.reportSdkError(t,{feature:"payment",process_id:(null==e?void 0:e.payment_id)||(null===(i=null==e?void 0:e.payment)||void 0===i?void 0:i.id)||(null===(s=null==e?void 0:e.payment)||void 0===s?void 0:s.pk),metadata:{step:"#resumeCheckout",response:e}})}return e}}))},$=function(e){n(this,L,null==e?void 0:e.apm_config,"f")},function(e){e.CARD_NUMBER="card_number",e.CVV="cvv",e.EXPIRATION_MONTH="expiration_month",e.EXPIRATION_YEAR="expiration_year",e.CARDHOLDER_NAME="cardholder_name"}(H||(H={}));const X={type:t.ValidationRuleType.LENGTH_MATCH_RULE,params:{max:70}},Q=RegExp("^(?!s*$).+"),W={type:t.ValidationRuleType.REGEX_MATCH_RULE,params:{regex:Q,error:"El campo es requerido"}},J="Titular de la tarjeta",G="Número de tarjeta",Z="CVC/CVV",ee="Mes",te="Año",re="Fecha de expiración",oe="Nombre como aparece en la tarjeta",ne="1234 1234 1234 1234",ie="3-4 dígitos",se="MM",ae="AA",de={base:{border:"1px solid #e0e0e0",padding:"10px 7px",borderRadius:"5px",color:"#1d1d1d",marginTop:"2px",backgroundColor:"white",fontFamily:'"Inter", sans-serif',fontSize:"16px","&::placeholder":{color:"#ccc"}},complete:{color:"#4caf50"},invalid:{border:"1px solid #f44336"},empty:{},focus:{},global:{"@import":'url("https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;700&display=swap")'}},le={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif'}},ce={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif',color:"#f44336"}};function ue({baseUrl:e,apiKey:o,vault_id:n,vault_url:i,data:a}){return r(this,void 0,void 0,(function*(){const d=t.init({vaultID:n,vaultURL:i,getBearerToken:()=>r(this,void 0,void 0,(function*(){return yield q(e,o)})),options:{logLevel:t.LogLevel.ERROR,env:t.Env.DEV}}).container(t.ContainerType.COLLECT),l=yield function(e,o){return r(this,void 0,void 0,(function*(){const n=yield function(e,o){return r(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(e).map((e=>r(this,void 0,void 0,(function*(){return{element:yield o.create({table:"cards",column:e,type:t.ElementType.INPUT_FIELD}),key:e}})))))}))}(e,o);return n?n.map((t=>new Promise((r=>{var o;const n=document.createElement("div");n.hidden=!0,n.id=`id-${t.key}`,null===(o=document.querySelector("body"))||void 0===o||o.appendChild(n),setTimeout((()=>{t.element.mount(`#id-${t.key}`),setInterval((()=>{if(t.element.isMounted()){const o=e[t.key];return t.element.setValue(o),r(t.element.isMounted())}}),120)}),120)})))):[]}))}(a,d);if((yield Promise.all(l)).some((e=>!e)))throw y({errorCode:s.SAVE_CARD_PROCESS_ERROR,details:{step:"get_skyflow_tokens"}});try{const e=yield d.collect();if(e)return e.records[0].fields;throw y({errorCode:s.SAVE_CARD_PROCESS_ERROR,details:{step:"get_skyflow_tokens"}})}catch(e){throw y({errorCode:s.SAVE_CARD_PROCESS_ERROR},e)}}))}function he(e){const{element:r,fieldMessage:o="",errorStyles:n={},requiredMessage:i="Campo requerido",invalidMessage:s="Campo no válido",events:a}=e;"on"in r&&(r.on(t.EventName.CHANGE,(e=>{_e({eventName:"onChange",data:e,events:a}),Ee({element:r,errorStyles:n,color:"transparent"})})),r.on(t.EventName.BLUR,(e=>{if(_e({eventName:"onBlur",data:e,events:a}),!e.isValid){const t=e.isEmpty?i:""!=o?`El campo ${o} no es válido`:s;r.setError(t)}Ee({element:r,errorStyles:n})})),r.on(t.EventName.FOCUS,(e=>{_e({eventName:"onFocus",data:e,events:a}),Ee({element:r,errorStyles:n,color:"transparent"}),r.resetError()})))}function Ee(e){const{element:t,errorStyles:r={},color:o=""}=e;Object.keys(r).length>0&&t.update({errorTextStyles:Object.assign(Object.assign({},r),{base:Object.assign(Object.assign({},r.base&&Object.assign({},r.base)),""!=o&&{color:o})})})}const _e=t=>{const{eventName:r,data:o,events:n}=t;if(n&&r in n){const t=n[r];"function"==typeof t&&t({elementType:e(o,"elementType",""),isEmpty:e(o,"isEmpty",!1),isFocused:e(o,"isFocused",!1),isValid:e(o,"isValid",!1),value:e(o,"value","")})}};function pe(e){return r(this,void 0,void 0,(function*(){const{element:t,containerId:r,retries:o=2,delay:n=30}=e;for(let e=0;e<=o;e++){if(document.querySelector(r))return void t.mount(r);e<o&&(yield new Promise((e=>setTimeout(e,n))))}console.warn(`[mountCardFields] Container ${r} was not found after ${o+1} attempts`)}))}const Re=Object.freeze({SORIANA:"SORIANA",OXXO:"OXXO",OXXOPAY:"OXXOPAY",SPEI:"SPEI",CODI:"CODI",MERCADOPAGO:"MERCADOPAGO",PAYPAL:"PAYPAL",COMERCIALMEXICANA:"COMERCIALMEXICANA",BANCOMER:"BANCOMER",WALMART:"WALMART",BODEGA:"BODEGA",SAMSCLUB:"SAMSCLUB",SUPERAMA:"SUPERAMA",CALIMAX:"CALIMAX",EXTRA:"EXTRA",CIRCULOK:"CIRCULOK",SEVEN11:"7ELEVEN",TELECOMM:"TELECOMM",BANORTE:"BANORTE",BENAVIDES:"BENAVIDES",DELAHORRO:"DELAHORRO",ELASTURIANO:"ELASTURIANO",WALDOS:"WALDOS",ALSUPER:"ALSUPER",KIOSKO:"KIOSKO",STAMARIA:"STAMARIA",LAMASBARATA:"LAMASBARATA",FARMROMA:"FARMROMA",FARMUNION:"FARMUNION",FARMATODO:"FARMATODO",SFDEASIS:"SFDEASIS",FARM911:"FARM911",FARMECONOMICAS:"FARMECONOMICAS",FARMMEDICITY:"FARMMEDICITY",RIANXEIRA:"RIANXEIRA",WESTERNUNION:"WESTERNUNION",ZONAPAGO:"ZONAPAGO",CAJALOSANDES:"CAJALOSANDES",CAJAPAITA:"CAJAPAITA",CAJASANTA:"CAJASANTA",CAJASULLANA:"CAJASULLANA",CAJATRUJILLO:"CAJATRUJILLO",EDPYME:"EDPYME",KASNET:"KASNET",NORANDINO:"NORANDINO",QAPAQ:"QAPAQ",RAIZ:"RAIZ",PAYSER:"PAYSER",WUNION:"WUNION",BANCOCONTINENTAL:"BANCOCONTINENTAL",GMONEY:"GMONEY",GOPAY:"GOPAY",WU:"WU",PUNTOSHEY:"PUNTOSHEY",AMPM:"AMPM",JUMBOMARKET:"JUMBOMARKET",SMELPUEBLO:"SMELPUEBLO",BAM:"BAM",REFACIL:"REFACIL",ACYVALORES:"ACYVALORES"}),me={[Re.SORIANA]:{label:"Soriana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/soriana.png"},[Re.OXXO]:{label:"Oxxo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxo.png"},[Re.CODI]:{label:"CoDi",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/codi.png"},[Re.MERCADOPAGO]:{label:"Mercado Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/mercadopago.png"},[Re.OXXOPAY]:{label:"Oxxo Pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/oxxopay.png"},[Re.SPEI]:{label:"SPEI",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/spei.png"},[Re.PAYPAL]:{label:"Paypal",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/paypal.png"},[Re.COMERCIALMEXICANA]:{label:"Comercial Mexicana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/comercial_exicana.png"},[Re.BANCOMER]:{label:"Bancomer",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bancomer.png"},[Re.WALMART]:{label:"Walmart",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/walmart.png"},[Re.BODEGA]:{label:"Bodega Aurrera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/bodega_aurrera.png"},[Re.SAMSCLUB]:{label:"Sam´s Club",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/sams_club.png"},[Re.SUPERAMA]:{label:"Superama",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/superama.png"},[Re.CALIMAX]:{label:"Calimax",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/calimax.png"},[Re.EXTRA]:{label:"Tiendas Extra",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/tiendas_extra.png"},[Re.CIRCULOK]:{label:"Círculo K",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/circulo_k.png"},[Re.SEVEN11]:{label:"7 Eleven",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/7_eleven.png"},[Re.TELECOMM]:{label:"Telecomm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/telecomm.png"},[Re.BANORTE]:{label:"Banorte",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/banorte.png"},[Re.BENAVIDES]:{label:"Farmacias Benavides",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_benavides.png"},[Re.DELAHORRO]:{label:"Farmacias del Ahorro",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_ahorro.png"},[Re.ELASTURIANO]:{label:"El Asturiano",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/asturiano.png"},[Re.WALDOS]:{label:"Waldos",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/waldos.png"},[Re.ALSUPER]:{label:"Alsuper",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/al_super.png"},[Re.KIOSKO]:{label:"Kiosko",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/kiosko.png"},[Re.STAMARIA]:{label:"Farmacias Santa María",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_santa_maria.png"},[Re.LAMASBARATA]:{label:"Farmacias la más barata",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_barata.png"},[Re.FARMROMA]:{label:"Farmacias Roma",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_roma.png"},[Re.FARMUNION]:{label:"Pago en Farmacias Unión",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_union.png"},[Re.FARMATODO]:{label:"Pago en Farmacias Farmatodo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_farmatodo.png\t"},[Re.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/farmacias_san_francisco.png"},[Re.FARM911]:{label:"Farmacias 911",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Re.FARMECONOMICAS]:{label:"Farmacias Economicas",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Re.FARMMEDICITY]:{label:"Farmacias Medicity",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Re.RIANXEIRA]:{label:"Rianxeira",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Re.WESTERNUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Re.ZONAPAGO]:{label:"Zona Pago",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Re.CAJALOSANDES]:{label:"Caja Los Andes",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Re.CAJAPAITA]:{label:"Caja Paita",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Re.CAJASANTA]:{label:"Caja Santa",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Re.CAJASULLANA]:{label:"Caja Sullana",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Re.CAJATRUJILLO]:{label:"Caja Trujillo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Re.EDPYME]:{label:"Edpyme",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Re.KASNET]:{label:"KasNet",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Re.NORANDINO]:{label:"Norandino",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Re.QAPAQ]:{label:"Qapaq",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Re.RAIZ]:{label:"Raiz",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Re.PAYSER]:{label:"Paysera",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Re.WUNION]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Re.BANCOCONTINENTAL]:{label:"Banco Continental",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Re.GMONEY]:{label:"Go money",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Re.GOPAY]:{label:"Go pay",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Re.WU]:{label:"Western Union",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Re.PUNTOSHEY]:{label:"Puntoshey",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Re.AMPM]:{label:"Ampm",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Re.JUMBOMARKET]:{label:"Jumbomarket",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Re.SMELPUEBLO]:{label:"Smelpueblo",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Re.BAM]:{label:"Bam",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Re.REFACIL]:{label:"Refacil",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"},[Re.ACYVALORES]:{label:"Acyvalores",icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png"}},ye=e=>{const t=e.toUpperCase().trim().replace(/\s+/g,"");return me[t]||{icon:"https://d35a75syrgujp0.cloudfront.net/payment_methods/store.png",label:""}};class ve extends z{constructor({apiKey:e,mode:t,returnUrl:r,callBack:o,apiKeyTonder:n,baseUrlTonder:i,customization:s,collectorIds:a,events:d}){super({mode:t,apiKey:e,returnUrl:r,callBack:o,apiKeyTonder:n,baseUrlTonder:i,customization:s,tdsIframeId:a&&"tdsIframe"in a?null==a?void 0:a.tdsIframe:"tdsIframe",sdkInfo:k}),this.activeAPMs=[],this.mountedElementsByContext=new Map,this.customerCardsCache=null,this.lastCollectedTokens=null,this.skyflowInstance=null,this.events=d||{}}injectCheckout(){return r(this,void 0,void 0,(function*(){yield this._initializeCheckout()}))}getCustomerCards(){return r(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:e}=yield this._getCustomer(),t=yield this._getCustomerCards(e,this.merchantData.business.pk);return this.customerCardsCache=t,Object.assign(Object.assign({},t),{cards:t.cards.map((e=>{return Object.assign(Object.assign({},e),{fields:Object.assign(Object.assign({},e.fields),{subscription_id:this._hasCardOnFileKeys()?e.fields.subscription_id:void 0}),icon:(t=e.fields.card_scheme,"Visa"===t?"https://d35a75syrgujp0.cloudfront.net/cards/visa.png":"Mastercard"===t?"https://d35a75syrgujp0.cloudfront.net/cards/mastercard.png":"American Express"===t?"https://d35a75syrgujp0.cloudfront.net/cards/american_express.png":"https://d35a75syrgujp0.cloudfront.net/cards/default_card.png")});var t}))})}catch(e){throw this.reportSdkError(e,{feature:"get-cards",process_id:this.getCustomerId(),metadata:{step:"getCustomerCards"}}),y({errorCode:s.FETCH_CARDS_ERROR},e)}}))}saveCustomerCard(){return r(this,void 0,void 0,(function*(){let e=null;try{yield this._fetchMerchantData();const t=yield this._getCustomer(),{auth_token:r,first_name:o="",last_name:n="",email:i=""}=t,{business:a}=this.merchantData,d=this._hasCardOnFileKeys(),l=yield this.collectCreateCardTokens(),c=yield this._saveCustomerCard(r,null==a?void 0:a.pk,l,d);if(e=c.skyflow_id,d){const e=c.card_bin;if(!e)throw new Error("Card BIN not returned from save card");const t=yield this._initializeCardOnFile();let d;try{d=yield t.process({cardTokens:{name:l.cardholder_name,number:l.card_number,expiryMonth:l.expiration_month,expiryYear:l.expiration_year,cvv:l.cvv},cardBin:e,contactDetails:{firstName:o||"",lastName:n||"",email:i||""},customerId:r,currency:this.currency||"MXN"})}catch(e){throw y({errorCode:s.CARD_ON_FILE_DECLINED,lockErrorCode:!0},e)}const u={skyflow_id:l.skyflow_id,subscription_id:d.subscriptionId};yield this._saveCustomerCard(r,null==a?void 0:a.pk,u)}return c}catch(t){throw e&&(yield this.removeCustomerCard(e)),this.reportSdkError(t,{feature:"save-card",process_id:e||this.getCustomerId(),metadata:{step:"saveCustomerCard"}}),y({errorCode:s.SAVE_CARD_ERROR},t)}}))}removeCustomerCard(e){return r(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:t}=yield this._getCustomer(),{business:r}=this.merchantData;return yield this._removeCustomerCard(t,null==r?void 0:r.pk,e)}catch(t){throw this.reportSdkError(t,{feature:"remove-card",process_id:e,metadata:{step:"removeCustomerCard"}}),y({errorCode:s.REMOVE_CARD_ERROR},t)}}))}getCustomerPaymentMethods(){return r(this,void 0,void 0,(function*(){try{const e=yield this._fetchCustomerPaymentMethods();return(e&&"results"in e&&e.results.length>0?e.results:[]).filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},ye(e.payment_method)))).sort(((e,t)=>e.priority-t.priority))}catch(e){throw this.reportSdkError(e,{feature:"get-payment-methods",metadata:{step:"getCustomerPaymentMethods"}}),y({errorCode:s.FETCH_PAYMENT_METHODS_ERROR},e)}}))}mountCardFields(e){var o;return r(this,void 0,void 0,(function*(){const n=e.card_id?`update:${e.card_id}`:"create",i=null!==(o=e.unmount_context)&&void 0!==o?o:"all";"none"!==i&&("current"===i?this.unmountCardFields(n):this.unmountCardFields(i)),yield this.createSkyflowInstance();const s=yield function(e){var o,n,i,s,a,d,l,c,u,h,E,_,p;return r(this,void 0,void 0,(function*(){const{skyflowInstance:r,data:R,customization:m,events:y}=e,v=r.container(t.ContainerType.COLLECT),f=[],C={[H.CVV]:t.ElementType.CVV,[H.CARD_NUMBER]:t.ElementType.CARD_NUMBER,[H.EXPIRATION_MONTH]:t.ElementType.EXPIRATION_MONTH,[H.EXPIRATION_YEAR]:t.ElementType.EXPIRATION_YEAR,[H.CARDHOLDER_NAME]:t.ElementType.CARDHOLDER_NAME},A={[H.CVV]:[W],[H.CARD_NUMBER]:[W],[H.EXPIRATION_MONTH]:[W],[H.EXPIRATION_YEAR]:[W],[H.CARDHOLDER_NAME]:[X,W]},O={[H.CARDHOLDER_NAME]:"cardholderName",[H.CARD_NUMBER]:"cardNumber",[H.CVV]:"cvv",[H.EXPIRATION_MONTH]:"expirationMonth",[H.EXPIRATION_YEAR]:"expirationYear"},T=e=>{var t,r,o,n,i,s;const a=null===(t=null==m?void 0:m.styles)||void 0===t?void 0:t[O[e]],d=null===(r=null==m?void 0:m.styles)||void 0===r?void 0:r.cardForm,l=null!==(o=null!=a?a:null==d?void 0:d.inputStyles)&&void 0!==o?o:de;return{inputStyles:e===H.CARD_NUMBER&&!1!==(null===(n=null==m?void 0:m.styles)||void 0===n?void 0:n.enableCardIcon)?Object.assign(Object.assign({},l),{base:Object.assign({paddingLeft:"15px"},null==l?void 0:l.base)}):l,labelStyles:null!==(i=null==d?void 0:d.labelStyles)&&void 0!==i?i:le,errorStyles:null!==(s=null==d?void 0:d.errorStyles)&&void 0!==s?s:ce}},g={cardholder_name:(null===(o=null==m?void 0:m.labels)||void 0===o?void 0:o.name)||J,card_number:(null===(n=null==m?void 0:m.labels)||void 0===n?void 0:n.card_number)||G,cvv:(null===(i=null==m?void 0:m.labels)||void 0===i?void 0:i.cvv)||Z,expiration_date:(null===(s=null==m?void 0:m.labels)||void 0===s?void 0:s.expiry_date)||re,expiration_month:(null===(a=null==m?void 0:m.labels)||void 0===a?void 0:a.expiration_month)||ee,expiration_year:(null===(d=null==m?void 0:m.labels)||void 0===d?void 0:d.expiration_year)||te},S={cardholder_name:(null===(l=null==m?void 0:m.placeholders)||void 0===l?void 0:l.name)||oe,card_number:(null===(c=null==m?void 0:m.placeholders)||void 0===c?void 0:c.card_number)||ne,cvv:(null===(u=null==m?void 0:m.placeholders)||void 0===u?void 0:u.cvv)||ie,expiration_month:(null===(h=null==m?void 0:m.placeholders)||void 0===h?void 0:h.expiration_month)||se,expiration_year:(null===(E=null==m?void 0:m.placeholders)||void 0===E?void 0:E.expiration_year)||ae},I={[H.CVV]:null==y?void 0:y.cvvEvents,[H.CARD_NUMBER]:null==y?void 0:y.cardNumberEvents,[H.EXPIRATION_MONTH]:null==y?void 0:y.monthEvents,[H.EXPIRATION_YEAR]:null==y?void 0:y.yearEvents,[H.CARDHOLDER_NAME]:null==y?void 0:y.cardHolderEvents};if("fields"in R&&Array.isArray(R.fields)){const e={enableCardIcon:null===(p=null===(_=null==m?void 0:m.styles)||void 0===_?void 0:_.enableCardIcon)||void 0===p||p};if(R.fields.length>0&&"string"==typeof R.fields[0])for(const t of R.fields){const r=v.create(Object.assign(Object.assign(Object.assign({table:"cards",column:t,type:C[t],validations:A[t]},T(t)),{label:g[t],placeholder:S[t]}),R.card_id?{skyflowID:R.card_id}:{}),t===H.CARD_NUMBER?e:void 0);he({element:r,errorStyles:T(t).errorStyles,fieldMessage:[H.CVV,H.EXPIRATION_MONTH,H.EXPIRATION_YEAR].includes(t)?"":g[t],events:I[t]});const o=`#collect_${String(t)}`+(R.card_id?`_${R.card_id}`:"");yield pe({element:r,containerId:o}),f.push({element:r,containerId:o})}else for(const t of R.fields){const r=t.field,o=v.create(Object.assign(Object.assign(Object.assign({table:"cards",column:r,type:C[r],validations:A[r]},T(r)),{label:g[r],placeholder:S[r]}),R.card_id?{skyflowID:R.card_id}:{}),r===H.CARD_NUMBER?e:void 0),n=t.container_id||`#collect_${String(r)}`+(R.card_id?`_${R.card_id}`:"");yield pe({element:o,containerId:n}),f.push({element:o,containerId:n})}}return{elements:f.map((e=>e.element)),container:v}}))}({skyflowInstance:this.skyflowInstance,data:e,customization:this.customization,events:this.events});this.mountedElementsByContext.set(n,{elements:s.elements||[],container:s})}))}getContainerByCardId(e){var t;const r=`update:${e}`,o=this.mountedElementsByContext.get(r);return(null===(t=null==o?void 0:o.container)||void 0===t?void 0:t.container)||null}collectCardTokens(e){var t,o,n;return r(this,void 0,void 0,(function*(){const r=this.getContainerByCardId(e);if(!r)return null;try{const e=yield r.collect();return(null===(o=null===(t=null==e?void 0:e.records)||void 0===t?void 0:t[0])||void 0===o?void 0:o.fields)||null}catch(t){const r=null===(n=null==t?void 0:t.error)||void 0===n?void 0:n.description;throw this.reportSdkError(t,{feature:"collect-card-tokens",process_id:e,metadata:{step:"collectCardTokens"}}),new d({code:s.MOUNT_COLLECT_ERROR,details:{message:r}})}}))}collectCreateCardTokens(){var e,t,o,n;return r(this,void 0,void 0,(function*(){const r=this.mountedElementsByContext.get("create"),i=null===(e=null==r?void 0:r.container)||void 0===e?void 0:e.container;if(!i)throw new d({code:s.MOUNT_COLLECT_ERROR,details:{message:"No card fields are mounted. Call mountCardFields() with the required fields before proceeding."}});try{const e=yield i.collect(),r=(null===(o=null===(t=null==e?void 0:e.records)||void 0===t?void 0:t[0])||void 0===o?void 0:o.fields)||{};return this.lastCollectedTokens=r,r}catch(e){const t=null===(n=null==e?void 0:e.error)||void 0===n?void 0:n.description;throw this.reportSdkError(e,{feature:"collect-create-card-tokens",metadata:{step:"collectCreateCardTokens"}}),new d({code:s.MOUNT_COLLECT_ERROR,details:{message:t}})}}))}revealCardFields(e){return r(this,void 0,void 0,(function*(){if(!this.lastCollectedTokens)throw y({errorCode:s.MOUNT_COLLECT_ERROR,details:{message:"No card tokens available. Call saveCustomerCard() or payment() with a new card before calling revealCardFields()."}});if(!this.skyflowInstance)throw y({errorCode:s.MOUNT_COLLECT_ERROR,details:{message:"Skyflow instance not initialized. Ensure mountCardFields() was called before saveCustomerCard() or payment()."}});yield function(e){var o,n,i,s,a,d;return r(this,void 0,void 0,(function*(){const{skyflowInstance:r,tokens:l,request:c}=e,u=r.container(t.ContainerType.REVEAL),h={[H.CARD_NUMBER]:"MASKED",[H.CARDHOLDER_NAME]:"PLAIN_TEXT",[H.EXPIRATION_MONTH]:"PLAIN_TEXT",[H.EXPIRATION_YEAR]:"PLAIN_TEXT"};for(const e of c.fields){const r="string"==typeof e,E=r?e:e.field;if(E===H.CVV){console.warn("[revealCardFields] CVV cannot be revealed (PCI DSS req. 3.2.1). Skipping.");continue}const _=l[E];if(!_){console.warn(`[revealCardFields] No token found for field "${E}", skipping.`);continue}const p=r?{}:e,R=null!==(o=p.container_id)&&void 0!==o?o:`#reveal_${E}`,m=h[E],y=null!==(n=p.styles)&&void 0!==n?n:{},v=null!==(i=c.styles)&&void 0!==i?i:{},f=u.create(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({token:_,redaction:t.RedactionType[m]},void 0!==p.altText&&{altText:p.altText}),void 0!==p.label&&{label:p.label}),y.inputStyles||v.inputStyles?{inputStyles:null!==(s=y.inputStyles)&&void 0!==s?s:v.inputStyles}:{}),y.labelStyles||v.labelStyles?{labelStyles:null!==(a=y.labelStyles)&&void 0!==a?a:v.labelStyles}:{}),y.errorTextStyles||v.errorTextStyles?{errorTextStyles:null!==(d=y.errorTextStyles)&&void 0!==d?d:v.errorTextStyles}:{}));yield pe({element:f,containerId:R})}try{yield u.reveal()}catch(e){console.warn("[revealCardFields] reveal completed with errors:",e)}}))}({skyflowInstance:this.skyflowInstance,tokens:this.lastCollectedTokens,request:e})}))}unmountCardFields(e="all"){"all"===e?(this.mountedElementsByContext.forEach(((e,t)=>{this.unmountContext(t)})),this.mountedElementsByContext.clear()):(this.unmountContext(e),this.mountedElementsByContext.delete(e))}unmountContext(e){const t=this.mountedElementsByContext.get(e);if(!t)return;const{elements:r}=t;r&&r.length>0&&r.forEach((t=>{try{t&&"function"==typeof t.unmount&&t.unmount()}catch(t){console.warn(`Error unmounting Skyflow element from context '${e}':`,t),this.reportSdkError(t,{feature:"unmount-card-fields",metadata:{step:"unmountContext",context:e}})}}))}getBusiness(){return r(this,void 0,void 0,(function*(){try{return yield i(this.baseUrl,this.apiKeyTonder,this.abortController.signal)}catch(e){throw this.reportSdkError(e,{feature:"get-business",metadata:{step:"getBusiness"}}),y({errorCode:s.FETCH_BUSINESS_ERROR},e)}}))}createSkyflowInstance(){return r(this,void 0,void 0,(function*(){if(this.skyflowInstance)return this.skyflowInstance;yield this._fetchMerchantData();const{vault_id:e,vault_url:o}=this.merchantData;this.skyflowInstance=yield function({baseUrl:e,apiKey:o,vault_id:n,vault_url:i,mode:s}){return r(this,void 0,void 0,(function*(){const a="production"===s?t.Env.PROD:t.Env.DEV;return t.init({vaultID:n,vaultURL:i,getBearerToken:()=>r(this,void 0,void 0,(function*(){return yield q(e,o)})),options:{logLevel:t.LogLevel.ERROR,env:a}})}))}({vault_id:e,vault_url:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder,mode:this.mode})}))}getOpenpayDeviceSessionID(e,t,o){return r(this,void 0,void 0,(function*(){try{return yield A(e,t,o)}catch(e){throw this.reportSdkError(e,{feature:"get-openpay-device-session",metadata:{step:"getOpenpayDeviceSessionID"}}),y({errorCode:s.START_CHECKOUT_ERROR},e)}}))}getSkyflowTokens({vault_id:e,vault_url:t,data:o}){return r(this,void 0,void 0,(function*(){return yield ue({vault_id:e,vault_url:t,data:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}_setCartTotal(e){this.cartTotal=e}_checkout({card:e,payment_method:t,isSandbox:o,returnUrl:n}){var i,a;return r(this,void 0,void 0,(function*(){yield this._fetchMerchantData();const d=yield this._getCustomer(this.abortController.signal),{business:l}=this.merchantData,{auth_token:c,first_name:u="",last_name:h="",email:E=""}=d,_=this._hasCardOnFileKeys();let p,R=null,m=null,v=null,f=!1;const C=()=>r(this,void 0,void 0,(function*(){var e,t;(null===(t=null===(e=this.customerCardsCache)||void 0===e?void 0:e.cards)||void 0===t?void 0:t.length)||(this.customerCardsCache=yield this._getCustomerCards(c,this.merchantData.business.pk))}));if(!t){if("string"==typeof e)if(m=e,p={skyflow_id:e},_){yield C();const t=null===(a=null===(i=this.customerCardsCache)||void 0===i?void 0:i.cards)||void 0===a?void 0:a.find((t=>t.fields.skyflow_id===e));if(!t)throw new Error("Card not found for card-on-file processing");const r=!!t.fields.subscription_id;r||(yield this.collectCardTokens(e)),r&&(R={subscriptionId:t.fields.subscription_id})}else yield this.collectCardTokens(e);else p=yield this.collectCreateCardTokens(),m=p.skyflow_id,_&&(v={name:p.cardholder_name,number:p.card_number,expiryMonth:p.expiration_month,expiryYear:p.expiration_year,cvv:p.cvv},f=!0);if(f){if(!m||!v)throw new Error("Missing card data for card-on-file processing");let e=null;try{const t=yield this._saveCustomerCard(c,null==l?void 0:l.pk,{skyflow_id:m},!0);e=t.skyflow_id;const r=t.card_bin;if(!r)throw new Error("Card BIN not returned from save card");const o=yield this._initializeCardOnFile();let n;try{n=yield o.process({cardTokens:v,cardBin:r,contactDetails:{firstName:u||"",lastName:h||"",email:E||""},customerId:c,currency:this.currency||"MXN"})}catch(e){throw y({errorCode:s.CARD_ON_FILE_DECLINED,lockErrorCode:!0},e)}R={subscriptionId:n.subscriptionId},yield this._saveCustomerCard(c,null==l?void 0:l.pk,{skyflow_id:m,subscription_id:R.subscriptionId})}catch(t){throw e&&(yield this.removeCustomerCard(e)),this.reportSdkError(t,{feature:"payment",process_id:e||this.getCustomerId(),metadata:{step:"card_on_file"}}),t}}}return yield this._handleCheckout({card:p,payment_method:t,customer:d,isSandbox:o,returnUrl:n,enable_card_on_file:!!(null==R?void 0:R.subscriptionId)&&_})}))}customerRegister(e){return r(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/customer/`,r={email:e},o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},signal:this.abortController.signal,body:JSON.stringify(r)});if(o.ok)return yield o.json();throw yield y({response:o,errorCode:s.CUSTOMER_OPERATION_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"customer-register",metadata:{step:"customerRegister"}}),y({errorCode:s.CUSTOMER_OPERATION_ERROR},e)}}))}createOrder(e){return r(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/orders/`,r=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(r)});if(o.ok)return yield o.json();throw yield y({response:o,errorCode:s.CREATE_ORDER_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"create-order",metadata:{step:"createOrder"}}),y({errorCode:s.CREATE_ORDER_ERROR},e)}}))}createPayment(e){return r(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/business/${e.business_pk}/payments/`,r=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(r)});if(o.ok)return yield o.json();throw yield y({response:o,errorCode:s.CREATE_PAYMENT_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"create-payment",metadata:{step:"createPayment"}}),y({errorCode:s.CREATE_PAYMENT_ERROR},e)}}))}startCheckoutRouter(e){return r(this,void 0,void 0,(function*(){const t=yield C(this.baseUrl,this.apiKeyTonder,e);if(yield this.init3DSRedirect(t))return t}))}init3DSRedirect(e){return r(this,void 0,void 0,(function*(){return this.process3ds.setPayload(e),yield this._handle3dsRedirect(e)}))}startCheckoutRouterFull(e){return r(this,void 0,void 0,(function*(){try{const{order:t,total:r,customer:o,skyflowTokens:n,return_url:i,isSandbox:a,metadata:d,currency:c,payment_method:u}=e,h=yield this._fetchMerchantData(),E=yield this.customerRegister(o.email);if(!(E&&"auth_token"in E&&h&&"reference"in h))throw y({errorCode:s.START_CHECKOUT_ERROR,details:{message:"Merchant or customer reposne errors",merchantResult:h,customerResult:E}});{const e={business:this.apiKeyTonder,client:E.auth_token,billing_address_id:null,shipping_address_id:null,amount:r,reference:h.reference,is_oneclick:!0,items:t.items},_=yield this.createOrder(e),p=(new Date).toISOString();if(!("id"in _&&"id"in E&&"business"in h))throw y({errorCode:s.START_CHECKOUT_ERROR,details:{message:"Order response errors",orderResult:_}});{const e={business_pk:h.business.pk,amount:r,date:p,order_id:_.id,client_id:E.id},t=yield this.createPayment(e);let s;const{openpay_keys:R,business:m}=h;R.merchant_id&&R.public_key&&(s=yield A(R.merchant_id,R.public_key,a));const y=Object.assign(Object.assign({name:o.name,last_name:o.lastname,email_client:o.email,phone_number:o.phone,return_url:i,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:r,title_ship:"shipping",description:"transaction",device_session_id:s||null,token_id:"",order_id:"id"in _&&_.id,business_id:m.pk,payment_id:"pk"in t&&t.pk,source:"sdk",metadata:d,browser_info:l(),currency:c},u?{payment_method:u}:{card:n}),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}),v=yield C(this.baseUrl,this.apiKeyTonder,y);if(yield this.init3DSRedirect(v))return v}}}catch(e){throw this.reportSdkError(e,{feature:"start-checkout-router-full",metadata:{step:"startCheckoutRouterFull"}}),y({errorCode:s.START_CHECKOUT_ERROR},e)}}))}registerCustomerCard(e,t,o){return r(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const r=yield fetch(`${this.baseUrl}/api/v1/business/${c(this.merchantData)}/cards/`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"User-token":t,"Content-Type":"application/json"},body:JSON.stringify(Object.assign({},o))});if(r.ok)return yield r.json();throw yield y({response:r,errorCode:s.SAVE_CARD_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"register-customer-card",metadata:{step:"registerCustomerCard"}}),y({errorCode:s.SAVE_CARD_ERROR},e)}}))}deleteCustomerCard(e,t=""){return r(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const r=yield fetch(`${this.baseUrl}/api/v1/business/${c(this.merchantData)}/cards/${t}`,{method:"DELETE",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.abortController.signal});if(r.ok)return!0;throw yield y({response:r,errorCode:s.REMOVE_CARD_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"delete-customer-card",process_id:t,metadata:{step:"deleteCustomerCard"}}),y({errorCode:s.REMOVE_CARD_ERROR},e)}}))}getActiveAPMs(){return r(this,void 0,void 0,(function*(){try{const e=yield function(e,t,o="?status=active&page_size=10000&country=México",n=null){return r(this,void 0,void 0,(function*(){const r=yield fetch(`${e}/api/v1/payment_methods${o}`,{method:"GET",headers:{Authorization:`Token ${t}`,"Content-Type":"application/json"},signal:n});if(r.ok)return yield r.json();throw yield y({response:r,errorCode:s.FETCH_PAYMENT_METHODS_ERROR})}))}(this.baseUrl,this.apiKeyTonder),t=e&&e.results&&e.results.length>0?e.results:[];return this.activeAPMs=t.filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},ye(e.payment_method)))).sort(((e,t)=>e.priority-t.priority)),this.activeAPMs}catch(e){return console.error("Error getting APMS",e),[]}}))}}function fe(e){return/^\d{12,19}$/.test(e)&&ge(e)}function Ce(e){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(e)}function Ae(e){return/^\d{3,4}$/.test(e)}function Oe(e){return/^(0[1-9]|1[0-2])$/.test(e)}function Te(e){if(!/^\d{2}$/.test(e))return!1;const t=(new Date).getFullYear()%100;return parseInt(e,10)>=t}const ge=e=>{const t=`${e}`.split("").reverse().map((e=>Number.parseInt(e))),r=t.shift();let o=t.reduce(((e,t,r)=>r%2!=0?e+t:e+((t*=2)>9?t-9:t)),0);return o+=r,o%10==0};export{E as AppError,z as BaseInlineCheckout,ve as LiteCheckout,M as SdkTelemetryClient,Ae as validateCVV,fe as validateCardNumber,Ce as validateCardholderName,Oe as validateExpirationMonth,Te as validateExpirationYear};
@@ -28,6 +28,11 @@ export interface ISaveCardSkyflowRequest {
28
28
  skyflow_id: string;
29
29
  subscription_id?: string;
30
30
  }
31
+ /**
32
+ * @deprecated Raw card fields are no longer accepted by `saveCustomerCard()`.
33
+ * Use `mountCardFields()` to render Skyflow Elements in your form and call
34
+ * `saveCustomerCard()` with no arguments.
35
+ */
31
36
  export interface ISaveCardRequest {
32
37
  card_number: string;
33
38
  cvv: string;
@@ -43,6 +48,17 @@ export declare enum CardFieldEnum {
43
48
  CARDHOLDER_NAME = "cardholder_name"
44
49
  }
45
50
  export type CardField = "cvv" | "card_number" | "expiration_month" | "expiration_year" | "cardholder_name";
51
+ /**
52
+ * Configuration for mounting Skyflow Elements into developer-provided `<div>` containers.
53
+ *
54
+ * Used in two scenarios:
55
+ * - **New card form** (no `card_id`): mount all 5 fields before calling `payment()` or
56
+ * `saveCustomerCard()`. Default container IDs are `#collect_<field>` (e.g. `#collect_card_number`).
57
+ * - **Saved-card CVV** (with `card_id`): mount only `cvv` for a specific saved card before
58
+ * calling `payment()` with the card's skyflow_id. Default container ID is `#collect_cvv_<card_id>`.
59
+ *
60
+ * Custom container IDs can be set via the `{ field, container_id }` object form of each field entry.
61
+ */
46
62
  export interface IMountCardFieldsRequest {
47
63
  fields: (CardField | {
48
64
  container_id?: string;
@@ -51,3 +67,82 @@ export interface IMountCardFieldsRequest {
51
67
  card_id?: string;
52
68
  unmount_context?: 'all' | 'current' | 'create' | string;
53
69
  }
70
+ /**
71
+ * Card fields that can be revealed via Skyflow Reveal Elements.
72
+ *
73
+ * `cvv` is intentionally excluded: PCI DSS Requirement 3.2.1 prohibits storing or
74
+ * displaying the card verification value after authorisation.
75
+ */
76
+ export type RevealableCardField = Exclude<CardField, 'cvv'>;
77
+ /**
78
+ * Styles accepted by Skyflow Reveal Elements.
79
+ * Note: Reveal elements only support `base`, `copyIcon`, and `global` style variants
80
+ * (unlike Collect elements which also support `focus`, `complete`, `invalid`, etc.).
81
+ */
82
+ export interface IRevealElementInputStyles {
83
+ base?: Record<string, any>;
84
+ copyIcon?: Record<string, any>;
85
+ global?: Record<string, any>;
86
+ }
87
+ /** Full styles object for a Skyflow Reveal Element. */
88
+ export interface IRevealElementStyles {
89
+ inputStyles?: IRevealElementInputStyles;
90
+ labelStyles?: {
91
+ base?: Record<string, any>;
92
+ global?: Record<string, any>;
93
+ };
94
+ errorTextStyles?: {
95
+ base?: Record<string, any>;
96
+ global?: Record<string, any>;
97
+ };
98
+ }
99
+ /**
100
+ * Per-field reveal configuration.
101
+ * When using the shorthand string form (e.g. `'card_number'`), defaults are applied automatically.
102
+ *
103
+ * Redaction levels are fixed by the SDK to comply with PCI DSS and cannot be overridden:
104
+ * - `card_number` → `MASKED` (shows only first-6 / last-4 digits)
105
+ * - `cardholder_name` → `PLAIN_TEXT`
106
+ * - `expiration_month` → `PLAIN_TEXT`
107
+ * - `expiration_year` → `PLAIN_TEXT`
108
+ */
109
+ export interface IRevealCardField {
110
+ /** The card field to reveal. CVV is not allowed per PCI DSS req. 3.2.1. */
111
+ field: RevealableCardField;
112
+ /**
113
+ * ID of the `<div>` container where the Reveal Element will be mounted.
114
+ * Defaults to `#reveal_<field>` (e.g. `#reveal_card_number`).
115
+ */
116
+ container_id?: string;
117
+ /**
118
+ * Placeholder text shown inside the iframe before `reveal()` is called.
119
+ * If not set, Skyflow shows the token string.
120
+ */
121
+ altText?: string;
122
+ /** Label rendered by Skyflow above the element. */
123
+ label?: string;
124
+ /** Per-field styles. Overrides `IRevealCardFieldsRequest.styles` for this field. */
125
+ styles?: IRevealElementStyles;
126
+ }
127
+ /**
128
+ * Request object for `revealCardFields()`.
129
+ *
130
+ * Call `revealCardFields()` after a successful `saveCustomerCard()` or `payment()` that
131
+ * processed a new card. The SDK stores the Skyflow tokens from the collect operation and
132
+ * uses them to populate Skyflow Reveal Elements (secure iframes) in the provided `<div>` containers.
133
+ *
134
+ * Redaction is applied automatically per PCI DSS guidelines and cannot be configured.
135
+ */
136
+ export interface IRevealCardFieldsRequest {
137
+ /**
138
+ * Fields to reveal. Each entry can be a plain `RevealableCardField` string (uses all defaults)
139
+ * or an `IRevealCardField` object for custom container, label, altText or styles.
140
+ * CVV is not a valid option.
141
+ */
142
+ fields: (RevealableCardField | IRevealCardField)[];
143
+ /**
144
+ * Global styles applied to all reveal elements.
145
+ * Per-field `styles` in `IRevealCardField` takes priority over this.
146
+ */
147
+ styles?: IRevealElementStyles;
148
+ }
@@ -97,7 +97,12 @@ export interface IProcessPaymentRequest {
97
97
  metadata?: Record<string, any>;
98
98
  currency?: string;
99
99
  payment_method?: string;
100
- card?: ICardFields | string;
100
+ /**
101
+ * For a saved card: pass the `skyflow_id` string of the saved card.
102
+ * For a new card: omit this field — card data is collected from Skyflow Elements
103
+ * mounted via `mountCardFields()`.
104
+ */
105
+ card?: string;
101
106
  isSandbox?: boolean;
102
107
  apm_config?: IMPConfigRequest | Record<string, any>;
103
108
  /**
@@ -107,6 +112,10 @@ export interface IProcessPaymentRequest {
107
112
  returnUrl?: string;
108
113
  order_reference?: string | null;
109
114
  }
115
+ /**
116
+ * @deprecated Raw card fields are no longer accepted by `payment()` or `saveCustomerCard()`.
117
+ * Use `mountCardFields()` to render Skyflow Elements and collect card data securely.
118
+ */
110
119
  export interface ICardFields {
111
120
  card_number: string;
112
121
  cvv: string;