@tonder.io/ionic-lite-sdk 0.0.69-beta.develop.24b2121 → 1.0.0
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.
- package/dist/index.js +1 -1
- package/package.json +1 -1
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 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,P,w,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),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 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",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: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,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",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,a,d,l;const c=null===(t=null==m?void 0:m.styles)||void 0===t?void 0:t[O[e]],u=null===(r=null==m?void 0:m.styles)||void 0===r?void 0:r.cardForm,h=null!==(n=null!==(o=null==c?void 0:c.inputStyles)&&void 0!==o?o:null==u?void 0:u.inputStyles)&&void 0!==n?n:de;return{inputStyles:e===H.CARD_NUMBER&&!1!==(null===(i=null==m?void 0:m.styles)||void 0===i?void 0:i.enableCardIcon)?Object.assign(Object.assign({},h),{base:Object.assign({paddingLeft:"15px"},null==h?void 0:h.base)}):h,labelStyles:null!==(a=null!==(s=null==c?void 0:c.labelStyles)&&void 0!==s?s:null==u?void 0:u.labelStyles)&&void 0!==a?a:le,errorStyles:null!==(l=null!==(d=null==c?void 0:c.errorStyles)&&void 0!==d?d:null==u?void 0:u.errorStyles)&&void 0!==l?l: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);he({element:o,errorStyles:T(r).errorStyles,fieldMessage:[H.CVV,H.EXPIRATION_MONTH,H.EXPIRATION_YEAR].includes(r)?"":g[r],events:I[r]});const 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};
|
|
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:"1.0.0"});var U,L,P,w,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),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 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",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: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,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",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,a,d,l;const c=null===(t=null==m?void 0:m.styles)||void 0===t?void 0:t[O[e]],u=null===(r=null==m?void 0:m.styles)||void 0===r?void 0:r.cardForm,h=null!==(n=null!==(o=null==c?void 0:c.inputStyles)&&void 0!==o?o:null==u?void 0:u.inputStyles)&&void 0!==n?n:de;return{inputStyles:e===H.CARD_NUMBER&&!1!==(null===(i=null==m?void 0:m.styles)||void 0===i?void 0:i.enableCardIcon)?Object.assign(Object.assign({},h),{base:Object.assign({paddingLeft:"15px"},null==h?void 0:h.base)}):h,labelStyles:null!==(a=null!==(s=null==c?void 0:c.labelStyles)&&void 0!==s?s:null==u?void 0:u.labelStyles)&&void 0!==a?a:le,errorStyles:null!==(l=null!==(d=null==c?void 0:c.errorStyles)&&void 0!==d?d:null==u?void 0:u.errorStyles)&&void 0!==l?l: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);he({element:o,errorStyles:T(r).errorStyles,fieldMessage:[H.CVV,H.EXPIRATION_MONTH,H.EXPIRATION_YEAR].includes(r)?"":g[r],events:I[r]});const 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};
|