@tonder.io/ionic-lite-sdk 1.0.1 → 1.0.2-beta.TEC-1207.53fb846
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/README.md +38 -3
- package/dist/classes/3dsHandler.d.ts +26 -2
- package/dist/classes/BaseInlineCheckout.d.ts +12 -9
- package/dist/classes/liteCheckout.d.ts +1 -1
- package/dist/data/businessApi.d.ts +1 -1
- package/dist/data/coreApi.d.ts +15 -0
- package/dist/helpers/corePayment.d.ts +60 -0
- package/dist/helpers/safeUrl.d.ts +15 -0
- package/dist/helpers/sanitize3dsMarkup.d.ts +18 -0
- package/dist/helpers/utils.d.ts +1 -0
- package/dist/helpers/validations.d.ts +1 -0
- package/dist/index.js +1 -1
- package/dist/shared/constants/apiEndpoints.d.ts +2 -0
- package/dist/shared/utils/appError.d.ts +9 -0
- package/dist/types/commons.d.ts +5 -0
- package/dist/types/core.d.ts +28 -0
- package/jest.config.ts +11 -1
- package/package.json +1 -1
- package/src/classes/3dsHandler.ts +134 -30
- package/src/classes/BaseInlineCheckout.ts +128 -16
- package/src/classes/liteCheckout.ts +9 -2
- package/src/data/businessApi.ts +13 -6
- package/src/data/coreApi.ts +47 -0
- package/src/helpers/corePayment.ts +211 -0
- package/src/helpers/safeUrl.ts +26 -0
- package/src/helpers/sanitize3dsMarkup.ts +133 -0
- package/src/helpers/utils.ts +4 -0
- package/src/helpers/validations.ts +9 -0
- package/src/shared/constants/apiEndpoints.ts +2 -0
- package/src/shared/constants/messages.ts +4 -4
- package/src/shared/utils/appError.ts +28 -11
- package/src/types/commons.ts +5 -0
- package/src/types/core.ts +30 -0
- package/tests/coreBusinessConfig.test.ts +100 -0
- package/tests/corePayment.test.ts +393 -0
- package/tests/corePaymentCheckout.test.ts +668 -0
- package/tests/coreStartupFailure.test.ts +70 -0
- package/tests/redirectToChallenge.test.ts +149 -0
- package/tests/sanitize3dsMarkup.test.ts +248 -0
- package/tests/secureTokenBoundary.test.ts +81 -0
- package/tests/threeDsApiKey.test.ts +41 -0
- package/tests/threeDsCore.test.ts +444 -0
- package/tests/threeDsPolling.test.ts +45 -0
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"skyflow-js";function t(e,t,r,o){return new(r||(r=Promise))((function(i,n){function s(e){try{d(o.next(e))}catch(e){n(e)}}function a(e){try{d(o.throw(e))}catch(e){n(e)}}function d(e){var t;e.done?i(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 r(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 o(e,t,r,o,i){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?i.call(e,r):i?i.value=r:t.set(e,r),r}function i(e,r,o){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${e}/api/v1/payments/business/${r}`,{headers:{Authorization:`Token ${r}`},signal:o});return yield t.json()}))}var n;"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"}(n||(n={}));const s={[n.INIT_ERROR]:"Error initializing the SDK.",[n.INVALID_TYPE]:"SDK Type invalid.",[n.STATE_ERROR]:"Error updating SDK state.",[n.FETCH_BUSINESS_ERROR]:"Error retrieving merchant information.",[n.INVALID_CONFIG]:"Required configuration options.",[n.MERCHANT_CREDENTIAL_REQUIRED]:"Merchant credential required.",[n.INVALID_PAYMENT_REQUEST]:"The payment data must be of type: :::interface:::.",[n.INVALID_PAYMENT_REQUEST_CARD_PM]:"The fields card and payment_method cannot be provided together.",[n.TYPE_SDK_REQUIRED]:"SDK type required.",[n.ENVIRONMENT_REQUIRED]:"Environment required.",[n.FETCH_CARDS_ERROR]:"Error retrieving cards.",[n.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.",[n.SAVE_CARD_ERROR]:"Error saving the card.",[n.REMOVE_CARD_ERROR]:"Error deleting the card.",[n.CREATE_PAYMENT_ERROR]:"Error creating the payment.",[n.PAYMENT_PROCESS_ERROR]:"There was an issue processing the payment.",[n.CARD_SAVED_SUCCESSFULLY]:"Card saved successfully.",[n.CARD_REMOVED_SUCCESSFULLY]:"Card deleted successfully.",[n.SAVE_CARD_PROCESS_ERROR]:"Error processing card data.",[n.START_CHECKOUT_ERROR]:"Error processing the payment.",[n.CREATE_ORDER_ERROR]:"Error creating the order.",[n.BUSINESS_ID_REQUIRED]:"Business ID is required.",[n.CLIENT_ID_REQUIRED]:"Client ID is required.",[n.INVALID_AMOUNT]:"Invalid amount.",[n.INVALID_ITEMS]:"Invalid items.",[n.CUSTOMER_OPERATION_ERROR]:"Error registering or fetching customer",[n.INVALID_EMAIL]:"Invalid email.",[n.FETCH_PAYMENT_METHODS_ERROR]:"Error retrieving active payment methods.",[n.INVALID_VAULT_TOKEN]:"An invalid vault token response was received.",[n.VAULT_TOKEN_ERROR]:"Error retrieving the vault token.",[n.SECURE_TOKEN_ERROR]:"Error getting secure token.",[n.SECURE_TOKEN_INVALID]:"Invalid secure token.",[n.INVALID_SECRET_API_KEY]:"SECRET API KEY is required.",[n.REMOVE_CARD]:"Card deleted successfully",[n.SKYFLOW_NOT_INITIALIZED]:"Skyflow not initialized.",[n.ERROR_LOAD_PAYMENT_FORM]:"There was an issue loading the payment form.",[n.INVALID_CARD_DATA]:"Invalid card data.",[n.ERROR_LOAD_ENROLLMENT_FORM]:"There was an issue loading the card form.",[n.MOUNT_COLLECT_ERROR]:"Mount failed. Make sure all inputs are complete and valid.",[n.CARD_ON_FILE_DECLINED]:"Transaction declined. Please verify your card details.",[n.REQUEST_ABORTED]:"Requests canceled.",[n.REQUEST_FAILED]:"Request failed.",[n.UNKNOWN_ERROR]:"An unexpected error occurred.",[n.CREATE_ERROR]:"Error creating the SDK.",[n.FETCH_TRANSACTION_ERROR]:"Error retrieving the transaction.",[n.THREEDS_REDIRECTION_ERROR]:"Ocurrió un error durante la redirección de 3DS.",[n.REMOVE_SDK_ERROR]:"Ocurrió un error removiendo la instancia del SDK."};n.INIT_ERROR,n.STATE_ERROR,n.FETCH_BUSINESS_ERROR,n.INVALID_CONFIG,n.TYPE_SDK_REQUIRED,n.ENVIRONMENT_REQUIRED,n.FETCH_CARDS_ERROR,n.SAVE_CARD_ERROR,n.REMOVE_CARD_ERROR,n.CREATE_PAYMENT_ERROR,n.START_CHECKOUT_ERROR,n.CREATE_ORDER_ERROR,n.BUSINESS_ID_REQUIRED,n.CLIENT_ID_REQUIRED,n.INVALID_AMOUNT,n.INVALID_ITEMS,n.CUSTOMER_OPERATION_ERROR,n.INVALID_EMAIL,n.FETCH_PAYMENT_METHODS_ERROR,n.INVALID_VAULT_TOKEN,n.VAULT_TOKEN_ERROR,n.SECURE_TOKEN_ERROR,n.INVALID_SECRET_API_KEY,n.CUSTOMER_AUTH_TOKEN_NOT_VALID,n.SECURE_TOKEN_INVALID,n.REMOVE_CARD,n.SKYFLOW_NOT_INITIALIZED,n.INVALID_TYPE,n.PAYMENT_PROCESS_ERROR,n.INVALID_PAYMENT_REQUEST,n.INVALID_PAYMENT_REQUEST_CARD_PM,n.SAVE_CARD_PROCESS_ERROR,n.ERROR_LOAD_PAYMENT_FORM,n.INVALID_CARD_DATA,n.ERROR_LOAD_ENROLLMENT_FORM,n.MOUNT_COLLECT_ERROR,n.CARD_ON_FILE_DECLINED,n.CARD_SAVED_SUCCESSFULLY,n.CARD_REMOVED_SUCCESSFULLY,n.REQUEST_ABORTED,n.REQUEST_FAILED,n.UNKNOWN_ERROR,n.CREATE_ERROR,n.FETCH_TRANSACTION_ERROR,n.THREEDS_REDIRECTION_ERROR,n.REMOVE_SDK_ERROR;class a extends Error{constructor(e){var t,r;const o=e.message||s[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 d=Object.freeze({production:"https://d35a75syrgujp0.cloudfront.net",sandbox:"https://static.staging.tonder.io",stage:"https://static.staging.tonder.io",development:"https://static.staging.tonder.io"});function l(e="stage"){return d[e]||d.stage}const c=()=>({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}),u=e=>{var t;return e&&"business"in e?null===(t=null==e?void 0:e.business)||void 0===t?void 0:t.pk:""},h=(e,t="stage")=>{const r=l(t);return"Visa"===e?`${r}/cards/visa.png`:"Mastercard"===e?`${r}/cards/mastercard.png`:"American Express"===e?`${r}/cards/american_express.png`:`${r}/cards/default_card.png`},E="__tonderLockErrorCode__";function _(e){return"object"==typeof e&&null!==e}class R extends Error{constructor(e){var t,r;const o=R.resolveStatusCode(e.statusCode,e.originalError),i=R.resolveMessage(e.errorCode,e.message),n=R.resolveSystemError(null===(t=e.details)||void 0===t?void 0:t.systemError,e.originalError);super(i),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:n},e.lockErrorCode&&Object.defineProperty(this,E,{value:!0,enumerable:!1,configurable:!0}),null===(r=Error.captureStackTrace)||void 0===r||r.call(Error,this,R)}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(R.isRecord(t)){r.push(t.statusCode,t.status);const e=R.isRecord(t.body)?t.body:null;e&&r.push(e.statusCode,e.status)}for(const e of r)if(R.isHttpStatusCode(e))return Math.trunc(Number(e));return 500}static resolveMessage(e,t){return t||(s[e]||s[n.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(R.isRecord(t)){const e=R.isRecord(t.details)?t.details:null,o=R.isRecord(t.body)?t.body:null,i=o&&R.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==i?void 0:i.systemError,null==i?void 0:i.code)}for(const e of r){const t=R.normalizeSystemError(e);if(t)return t}return"APP_INTERNAL_001"}}function m(e){return _(e)&&!0===e[E]}function p(e){return e instanceof R&&void 0!==e.originalError?e.originalError:e}function y(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,i=!!e.message||void 0!==e.statusCode||void 0!==o;return!function(e){return _(e)&&"TonderError"===e.name&&"string"==typeof e.code}(t)||(e.lockErrorCode&&function(e){Object.defineProperty(e,E,{value:!0,enumerable:!1,configurable:!0})}(t),i||e.errorCode!==t.code&&!m(t))?new R({errorCode:e.errorCode,message:e.message,statusCode:e.statusCode,details:void 0!==o?{systemError:o}:void 0,originalError:p(t),lockErrorCode:e.lockErrorCode||m(t)}):t}function v(e){var r,o;return t(this,void 0,void 0,(function*(){const i=yield function(e){return t(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),n={status:e.response.status};return e.response.statusText&&(n.statusText=e.response.statusText),void 0!==i&&(n.body=i),new R({errorCode:e.errorCode,message:e.message,statusCode:null!==(r=e.statusCode)&&void 0!==r?r:e.response.status,details:void 0!==(null===(o=e.details)||void 0===o?void 0:o.systemError)?{systemError:e.details.systemError}:void 0,originalError:n,lockErrorCode:e.lockErrorCode})}))}function C(e,t){return(null==e?void 0:e.response)?v(e):y(e,t)}class A{constructor({payload:e=null,apiKey:t,baseUrl:r,redirectOnComplete:o,tdsIframeId:i,tonderPayButtonId:n,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=i,this.tonderPayButtonId=n,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,i,n;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===(n=null===(i=null===(o=this.payload)||void 0===o?void 0:o.next_action)||void 0===i?void 0:i.iframe_resources)||void 0===n?void 0:n.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,i;const n=null===(i=null===(o=null===(r=this.payload)||void 0===r?void 0:r.next_action)||void 0===o?void 0:o.iframe_resources)||void 0===i?void 0:i.iframe;if(n){this.saveVerifyTransactionUrl();const r=document.createElement("div");r.innerHTML=n,document.body.appendChild(r);const o=document.createElement("script");o.textContent='document.getElementById("tdsMmethodForm").submit();',r.appendChild(o);const i=document.getElementById("tdsMmethodTgtFrame");i?i.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 r=document.querySelector(`#${this.tdsIframeId}`);if(r){r.setAttribute("src",e),r.setAttribute("style","display: block");const o=this,i=e=>t(this,void 0,void 0,(function*(){const e=()=>{try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}r&&r.setAttribute("style","display: none"),o.callBack&&o.callBack(o.payload),r.removeEventListener("load",i)},n=r=>t(this,void 0,void 0,(function*(){const i=yield new Promise(((e,t)=>e(r)));if(i){if((e=>"Pending"!==(null==e?void 0:e.transaction_status))(i))return e();{const e=setTimeout((()=>t(this,void 0,void 0,(function*(){clearTimeout(e),yield n(o.requestTransactionStatus())}))),7e3)}}}));yield n(o.requestTransactionStatus())}));r.addEventListener("load",i)}else console.log("No iframe found")}else this.callBack&&this.callBack(this.payload)}requestTransactionStatus(){return t(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 t(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 t(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 t(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 O=Object.freeze({production:"https://app.tonder.io",sandbox:"https://sandbox.tonder.io",stage:"https://stage.tonder.io",development:"http://localhost:8000"});function T(e,r,o){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/checkout-router/`,i=o,s=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${r}`},body:JSON.stringify(Object.assign(Object.assign({},i),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}))});if(s.ok)return yield s.json();throw yield C({response:s,errorCode:n.START_CHECKOUT_ERROR})}))}function f(e,r,o=!0,i=null){return t(this,void 0,void 0,(function*(){let t=yield window.OpenPay;return t.setId(e),t.setApiKey(r),t.setSandboxMode(o),yield t.deviceData.setup({signal:i})}))}function S(e,t,r){const o=t.replace(/\[(\w+)\]/g,".$1").split(".").filter((e=>""!==e));let i=e;for(const e of o){if(null==i)return r;i=i[e]}return void 0===i?r:i}const I=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"}),g=Object.freeze({TELEMETRY:"/telemetry/v1/events",ACQ_SUBSCRIPTION_TOKEN:"/acq-kushki/subscription/token",ACQ_SUBSCRIPTION_CREATE:"/acq-kushki/subscription/create"});function N(e="stage"){return`${I[e]}${g.TELEMETRY}`}const b="https://cdn.kushkipagos.com/kushki.min.js",D=n.CARD_ON_FILE_DECLINED;let M=!1,k=null;class P{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 I[e]}(r),this.merchantId=e.merchantId,this.apiKey=e.apiKey}initialize(){return t(this,void 0,void 0,(function*(){yield function(){return t(this,void 0,void 0,(function*(){return M?Promise.resolve():k||(k=new Promise(((e,t)=>{if(document.querySelector(`script[src="${b}"]`))return M=!0,void e();const r=document.createElement("script");r.src=b,r.async=!0,r.onload=()=>{M=!0,e()},r.onerror=()=>{k=null,t(C({errorCode:D,lockErrorCode:!0,details:{step:"load_acquirer_script",message:"Failed to load acquirer script"}}))},document.head.appendChild(r)})),k)}))}(),this.acquirerInstance=function(e,t){if(!window.Kushki)throw C({errorCode:D,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 C({errorCode:D,lockErrorCode:!0,details:{step:"get_acquirer_instance",message:"CardOnFile not initialized. Call initialize() first."}});return this.acquirerInstance}getJwt(e){return t(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(C({errorCode:D,lockErrorCode:!0,details:{step:"get_jwt",acquirerResponse:e}}));const t=e;t.jwt?r(t.jwt):o(C({errorCode:D,lockErrorCode:!0,details:{step:"get_jwt",message:"No JWT returned from acquirer",acquirerResponse:t}}))}))}))}))}generateToken(e){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}${g.ACQ_SUBSCRIPTION_TOKEN}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`},body:JSON.stringify(e)});if(!t.ok)throw yield C({response:t,errorCode:D,lockErrorCode:!0,details:{step:"generate_token"}});return t.json()}))}createSubscription(e){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}${g.ACQ_SUBSCRIPTION_CREATE}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`},body:JSON.stringify(e)});if(!t.ok)throw yield C({response:t,errorCode:D,lockErrorCode:!0,details:{step:"create_subscription"}});return t.json()}))}validate3DS(e,r){return t(this,void 0,void 0,(function*(){const t=this.getAcquirerInstance();return new Promise(((o,i)=>{t.requestValidate3DS({secureId:e,security:r},(e=>{const t=e;t.code&&"3DS000"!==t.code?i(C({errorCode:D,lockErrorCode:!0,details:{step:"validate_3ds",message:"3DS validation failed",acquirerResponse:t}})):!1!==t.isValid?o(!0):i(C({errorCode:D,lockErrorCode:!0,details:{step:"validate_3ds",message:"3DS validation failed",acquirerResponse:t}}))}))}))}))}process(e){var r,o;return t(this,void 0,void 0,(function*(){const t=yield this.getJwt(e.cardBin),i=yield this.generateToken({card:e.cardTokens,currency:e.currency,jwt:t}),n=i.secureId||(null===(r=i.details)||void 0===r?void 0:r.secureId),s=i.security||(null===(o=i.details)||void 0===o?void 0:o.security);if(!n||!s)throw C({errorCode:D,lockErrorCode:!0,details:{step:"process",message:"Missing secureId or security in token response",tokenResponse:i}});return yield this.validate3DS(n,s),this.createSubscription({token:i.token,contactDetails:e.contactDetails,metadata:{customerId:e.customerId},currency:e.currency})}))}}class U{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 i={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&&(i.tenant_id=t.tenant_id),t.request_id&&(i.request_id=t.request_id),t.process_id&&(i.process_id=t.process_id),t.user_id&&(i.user_id=t.user_id),r.stack&&(i.stack=r.stack),t.error_code&&(i.error_code=t.error_code),t.http_status&&(i.http_status=t.http_status),i}truncate(e,t){return e.length<=t?e:e.substring(0,t)+"..."}sendEvent(e){this.sendHttpRequest(e).then((()=>{})).catch((()=>{}))}sendHttpRequest(e){return t(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 L=Object.freeze({name:"@tonder.io/ionic-lite-sdk",version:"1.0.1"});var w,V,F,K,j,x,B,Y,$,H,z,q,X;class Q{constructor({mode:e="stage",customization:t,apiKey:r,apiKeyTonder:o,returnUrl:i,tdsIframeId:n,callBack:s=(()=>{}),baseUrlTonder:a,tonderPayButtonId:d,sdkInfo:l}){w.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,V.set(this,void 0),F.set(this,void 0),this.apiKeyTonder=o||r||"",this.returnUrl=i,this.callBack=s,this.mode=e,this.customer={},this.baseUrl=a||O[this.mode]||O.stage,this.abortController=new AbortController,this.requestId=this.generateRequestId(),this.customization=Object.assign(Object.assign({},this.customization),t||{}),this.process3ds=new A({apiKey:r,baseUrl:this.baseUrl,redirectOnComplete:this.customization.redirectOnComplete,tdsIframeId:n,tonderPayButtonId:d,callBack:s}),this.tdsIframeId=n;const c=l||L;this.telemetry=new U({endpoint:N(this.mode),apiKey:this.apiKeyTonder,platform:c.name,platform_version:c.version,mode:this.mode||"stage"})}configureCheckout(e){"secureToken"in e&&r(this,w,"m",x).call(this,e.secureToken),r(this,w,"m",K).call(this,e)}getCustomerId(){var e,t;return null===(t=null===(e=r(this,F,"f"))||void 0===e?void 0:e.id)||void 0===t?void 0:t.toString()}reportSdkError(e,t){var r,o,i,n;try{const s=this.getCustomerId(),a=e instanceof R&&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===(n=null===(i=null===(o=this.merchantData)||void 0===o?void 0:o.business)||void 0===i?void 0:i.pk)||void 0===n?void 0:n.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 t(this,void 0,void 0,(function*(){const e=yield this.process3ds.verifyTransactionStatus(),t=yield r(this,w,"m",z).call(this,e);return this.process3ds.setPayload(t),this._handle3dsRedirect(t)}))}payment(e){return new Promise(((o,i)=>t(this,void 0,void 0,(function*(){var t,s;let a;try{r(this,w,"m",K).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),o(a)}}catch(r){this.reportSdkError(r,{feature:"payment",process_id:(null==a?void 0:a.payment_id)||(null===(t=null==a?void 0:a.payment)||void 0===t?void 0:t.id)||(null===(s=null==a?void 0:a.payment)||void 0===s?void 0:s.pk),metadata:{step:"payment",request:e,response:a}}),i(C({errorCode:n.PAYMENT_PROCESS_ERROR},r))}}))))}getSecureToken(e){return t(this,void 0,void 0,(function*(){try{return yield function(e,r,o=null){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${e}/api/secure-token/`,{method:"POST",headers:{Authorization:`Token ${r}`,"Content-Type":"application/json"},signal:o});if(t.ok)return yield t.json();throw yield C({response:t,errorCode:n.SECURE_TOKEN_ERROR})}))}(this.baseUrl,e)}catch(e){throw this.reportSdkError(e,{feature:"secure-token",metadata:{step:"getSecureToken"}}),C({errorCode:n.SECURE_TOKEN_ERROR},e)}}))}_initializeCheckout(){return t(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 t(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 t(this,void 0,void 0,(function*(){return r(this,F,"f")||o(this,F,yield function(e,r,o,i=null){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/customer/`,s={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(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${r}`},signal:i,body:JSON.stringify(s)});if(a.ok)return yield a.json();throw yield C({response:a,errorCode:n.CUSTOMER_OPERATION_ERROR})}))}(this.baseUrl,this.apiKeyTonder,this.customer,e),"f"),r(this,F,"f")}))}_handleCheckout({card:e,payment_method:o,customer:i,isSandbox:s,enable_card_on_file:a,returnUrl:d}){return t(this,void 0,void 0,(function*(){const{openpay_keys:l,reference:u,business:h}=this.merchantData,E=Number(this.cartTotal);let _,R,m;try{let p;!p&&l.merchant_id&&l.public_key&&!o&&(p=yield f(l.merchant_id,l.public_key,s,this.abortController.signal));const{id:y,auth_token:v}=i;_={business:this.apiKeyTonder,client:v,billing_address_id:null,shipping_address_id:null,amount:E,status:"A",reference:u,is_oneclick:!0,items:this.cartItems,currency:this.currency,metadata:this.metadata};const A=yield function(e,r,o){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/orders/`,i=o,s=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${r}`},body:JSON.stringify(i)});if(s.ok)return yield s.json();throw yield C({response:s,errorCode:n.CREATE_ORDER_ERROR})}))}(this.baseUrl,this.apiKeyTonder,_),O=(new Date).toISOString();R={business_pk:h.pk,client_id:y,amount:E,date:O,order_id:A.id,customer_order_reference:this.order_reference?this.order_reference:u,items:this.cartItems,currency:this.currency,metadata:this.metadata};const I=yield function(e,r,o){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/business/${o.business_pk}/payments/`,i=o,s=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${r}`},body:JSON.stringify(i)});if(s.ok)return yield s.json();throw yield C({response:s,errorCode:n.CREATE_PAYMENT_ERROR})}))}(this.baseUrl,this.apiKeyTonder,R);m=Object.assign(Object.assign(Object.assign(Object.assign({name:S(this.customer,"firstName",S(this.customer,"name","")),last_name:S(this.customer,"lastName",S(this.customer,"lastname","")),email_client:S(this.customer,"email",""),phone_number:S(this.customer,"phone",""),return_url:d||this.returnUrl,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:E,title_ship:"shipping",description:"transaction",device_session_id:p||null,token_id:"",order_id:A.id,business_id:h.pk,payment_id:I.pk,source:"sdk",items:this.cartItems,metadata:this.metadata,browser_info:c(),currency:this.currency},o?{payment_method:o}:{card:e}),{apm_config:r(this,V,"f")}),this.customer&&"identification"in this.customer?{identification:this.customer.identification}:{}),void 0!==a?{enable_card_on_file:a}:{});const g=yield T(this.baseUrl,this.apiKeyTonder,m);return g||!1}catch(e){throw this.reportSdkError(e,{feature:"payment",process_id:null==m?void 0:m.payment_id,metadata:{step:"_handleCheckout",orderItems:_,paymentItems:R,routerItems:m}}),e}}))}_fetchMerchantData(){return t(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,r){return t(this,void 0,void 0,(function*(){return yield function(e,r,o,i,s=null){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/business/${i}/cards/`,a=yield fetch(t,{method:"GET",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":r},signal:s});if(a.ok)return yield a.json();if(401===a.status)return{user_id:0,cards:[]};throw yield C({response:a,errorCode:n.FETCH_CARDS_ERROR})}))}(this.baseUrl,e,this.secureToken,r)}))}_saveCustomerCard(e,r,o,i=!1){return t(this,void 0,void 0,(function*(){return yield function(e,r,o,i,s,a=!1){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/business/${i}/cards/`,d=yield fetch(t,{method:"POST",headers:Object.assign({Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":r},a?{"X-App-Origin":"sdk/ionic"}:{}),body:JSON.stringify(s)});if(d.ok)return yield d.json();throw yield C({response:d,errorCode:n.SAVE_CARD_ERROR})}))}(this.baseUrl,e,this.secureToken,r,o,i)}))}_removeCustomerCard(e,r,o){return t(this,void 0,void 0,(function*(){return yield function(e,r,o,i="",a){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/business/${a}/cards/${i}`,d=yield fetch(t,{method:"DELETE",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":r}});if(204===d.status)return s[n.CARD_REMOVED_SUCCESSFULLY];if(d.ok&&"json"in d)return yield d.json();throw yield C({response:d,errorCode:n.REMOVE_CARD_ERROR})}))}(this.baseUrl,e,this.secureToken,o,r)}))}_fetchCustomerPaymentMethods(){return t(this,void 0,void 0,(function*(){return yield function(e,r,o={status:"active",pagesize:"10000"},i=null){return t(this,void 0,void 0,(function*(){const t=new URLSearchParams(o).toString(),s=yield fetch(`${e}/api/v1/payment_methods?${t}`,{method:"GET",headers:{Authorization:`Token ${r}`,"Content-Type":"application/json"},signal:i});if(s.ok)return yield s.json();throw yield C({response:s,errorCode:n.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 t(this,void 0,void 0,(function*(){return this.cardOnFileInstance||(this.cardOnFileInstance=new P({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 r,o;return t(this,void 0,void 0,(function*(){if(e&&"next_action"in e?null===(o=null===(r=null==e?void 0:e.next_action)||void 0===r?void 0:r.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 W(e,r,o=null){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${e}/api/v1/vault-token/`,{method:"GET",headers:{Authorization:`Token ${r}`},signal:o});if(t.ok){return(yield t.json()).token}throw yield C({response:t,errorCode:n.VAULT_TOKEN_ERROR})}))}V=new WeakMap,F=new WeakMap,w=new WeakSet,K=function(e){var t,o;!e||e&&0===Object.keys(e).length||(r(this,w,"m",j).call(this,e.customer),this._setCartTotal((null===(t=e.cart)||void 0===t?void 0:t.total)||0),r(this,w,"m",B).call(this,(null===(o=e.cart)||void 0===o?void 0:o.items)||[]),r(this,w,"m",Y).call(this,e),r(this,w,"m",$).call(this,e),r(this,w,"m",H).call(this,e),r(this,w,"m",q).call(this,e))},j=function(e){e&&(this.customer=e)},x=function(e){this.secureToken=e},B=function(e){this.cartItems=e},Y=function(e){this.metadata=null==e?void 0:e.metadata,this.order_reference=null==e?void 0:e.order_reference},$=function(e){this.currency=null==e?void 0:e.currency},H=function(e){this.card=null==e?void 0:e.card},z=function(e){var r,o,i,n,s;return t(this,void 0,void 0,(function*(){if("Hard"===(null===(r=null==e?void 0:e.decline)||void 0===r?void 0:r.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===(i=e.checkout)||void 0===i?void 0:i.id)||(null==e?void 0:e.checkout_id)};try{return yield T(this.baseUrl,this.apiKeyTonder,t)}catch(t){this.reportSdkError(t,{feature:"payment",process_id:(null==e?void 0:e.payment_id)||(null===(n=null==e?void 0:e.payment)||void 0===n?void 0:n.id)||(null===(s=null==e?void 0:e.payment)||void 0===s?void 0:s.pk),metadata:{step:"#resumeCheckout",response:e}})}return e}}))},q=function(e){o(this,V,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"}(X||(X={}));const J={type:e.ValidationRuleType.LENGTH_MATCH_RULE,params:{max:70}},G=RegExp("^(?!s*$).+"),Z={type:e.ValidationRuleType.REGEX_MATCH_RULE,params:{regex:G,error:"El campo es requerido"}},ee="Titular de la tarjeta",te="Número de tarjeta",re="CVC/CVV",oe="Mes",ie="Año",ne="Fecha de expiración",se="Nombre como aparece en la tarjeta",ae="1234 1234 1234 1234",de="3-4 dígitos",le="MM",ce="AA",ue={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")'}},he={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif'}},Ee={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif',color:"#f44336"}};function _e({baseUrl:r,apiKey:o,vault_id:i,vault_url:s,data:a}){return t(this,void 0,void 0,(function*(){const d=e.init({vaultID:i,vaultURL:s,getBearerToken:()=>t(this,void 0,void 0,(function*(){return yield W(r,o)})),options:{logLevel:e.LogLevel.ERROR,env:e.Env.DEV}}).container(e.ContainerType.COLLECT),l=yield function(r,o){return t(this,void 0,void 0,(function*(){const i=yield function(r,o){return t(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(r).map((r=>t(this,void 0,void 0,(function*(){return{element:yield o.create({table:"cards",column:r,type:e.ElementType.INPUT_FIELD}),key:r}})))))}))}(r,o);return i?i.map((e=>new Promise((t=>{var o;const i=document.createElement("div");i.hidden=!0,i.id=`id-${e.key}`,null===(o=document.querySelector("body"))||void 0===o||o.appendChild(i),setTimeout((()=>{e.element.mount(`#id-${e.key}`),setInterval((()=>{if(e.element.isMounted()){const o=r[e.key];return e.element.setValue(o),t(e.element.isMounted())}}),120)}),120)})))):[]}))}(a,d);if((yield Promise.all(l)).some((e=>!e)))throw C({errorCode:n.SAVE_CARD_PROCESS_ERROR,details:{step:"get_skyflow_tokens"}});try{const e=yield d.collect();if(e)return e.records[0].fields;throw C({errorCode:n.SAVE_CARD_PROCESS_ERROR,details:{step:"get_skyflow_tokens"}})}catch(e){throw C({errorCode:n.SAVE_CARD_PROCESS_ERROR},e)}}))}function Re(t){const{element:r,fieldMessage:o="",errorStyles:i={},requiredMessage:n="Campo requerido",invalidMessage:s="Campo no válido",events:a}=t;"on"in r&&(r.on(e.EventName.CHANGE,(e=>{pe({eventName:"onChange",data:e,events:a}),me({element:r,errorStyles:i,color:"transparent"})})),r.on(e.EventName.BLUR,(e=>{if(pe({eventName:"onBlur",data:e,events:a}),!e.isValid){const t=e.isEmpty?n:""!=o?`El campo ${o} no es válido`:s;r.setError(t)}me({element:r,errorStyles:i})})),r.on(e.EventName.FOCUS,(e=>{pe({eventName:"onFocus",data:e,events:a}),me({element:r,errorStyles:i,color:"transparent"}),r.resetError()})))}function me(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 pe=e=>{const{eventName:t,data:r,events:o}=e;if(o&&t in o){const e=o[t];"function"==typeof e&&e({elementType:S(r,"elementType",""),isEmpty:S(r,"isEmpty",!1),isFocused:S(r,"isFocused",!1),isValid:S(r,"isValid",!1),value:S(r,"value","")})}};function ye(e){return t(this,void 0,void 0,(function*(){const{element:t,containerId:r,retries:o=2,delay:i=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,i))))}console.warn(`[mountCardFields] Container ${r} was not found after ${o+1} attempts`)}))}const ve=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"}),Ce={[ve.SORIANA]:{label:"Soriana",iconPath:"/payment_methods/soriana.png"},[ve.OXXO]:{label:"Oxxo",iconPath:"/payment_methods/oxxo.png"},[ve.CODI]:{label:"CoDi",iconPath:"/payment_methods/codi.png"},[ve.MERCADOPAGO]:{label:"Mercado Pago",iconPath:"/payment_methods/mercadopago.png"},[ve.OXXOPAY]:{label:"Oxxo Pay",iconPath:"/payment_methods/oxxopay.png"},[ve.SPEI]:{label:"SPEI",iconPath:"/payment_methods/spei.png"},[ve.PAYPAL]:{label:"Paypal",iconPath:"/payment_methods/paypal.png"},[ve.COMERCIALMEXICANA]:{label:"Comercial Mexicana",iconPath:"/payment_methods/comercial_exicana.png"},[ve.BANCOMER]:{label:"Bancomer",iconPath:"/payment_methods/bancomer.png"},[ve.WALMART]:{label:"Walmart",iconPath:"/payment_methods/walmart.png"},[ve.BODEGA]:{label:"Bodega Aurrera",iconPath:"/payment_methods/bodega_aurrera.png"},[ve.SAMSCLUB]:{label:"Sam´s Club",iconPath:"/payment_methods/sams_club.png"},[ve.SUPERAMA]:{label:"Superama",iconPath:"/payment_methods/superama.png"},[ve.CALIMAX]:{label:"Calimax",iconPath:"/payment_methods/calimax.png"},[ve.EXTRA]:{label:"Tiendas Extra",iconPath:"/payment_methods/tiendas_extra.png"},[ve.CIRCULOK]:{label:"Círculo K",iconPath:"/payment_methods/circulo_k.png"},[ve.SEVEN11]:{label:"7 Eleven",iconPath:"/payment_methods/7_eleven.png"},[ve.TELECOMM]:{label:"Telecomm",iconPath:"/payment_methods/telecomm.png"},[ve.BANORTE]:{label:"Banorte",iconPath:"/payment_methods/banorte.png"},[ve.BENAVIDES]:{label:"Farmacias Benavides",iconPath:"/payment_methods/farmacias_benavides.png"},[ve.DELAHORRO]:{label:"Farmacias del Ahorro",iconPath:"/payment_methods/farmacias_ahorro.png"},[ve.ELASTURIANO]:{label:"El Asturiano",iconPath:"/payment_methods/asturiano.png"},[ve.WALDOS]:{label:"Waldos",iconPath:"/payment_methods/waldos.png"},[ve.ALSUPER]:{label:"Alsuper",iconPath:"/payment_methods/al_super.png"},[ve.KIOSKO]:{label:"Kiosko",iconPath:"/payment_methods/kiosko.png"},[ve.STAMARIA]:{label:"Farmacias Santa María",iconPath:"/payment_methods/farmacias_santa_maria.png"},[ve.LAMASBARATA]:{label:"Farmacias la más barata",iconPath:"/payment_methods/farmacias_barata.png"},[ve.FARMROMA]:{label:"Farmacias Roma",iconPath:"/payment_methods/farmacias_roma.png"},[ve.FARMUNION]:{label:"Pago en Farmacias Unión",iconPath:"/payment_methods/farmacias_union.png"},[ve.FARMATODO]:{label:"Pago en Farmacias Farmatodo",iconPath:"/payment_methods/farmacias_farmatodo.png\t"},[ve.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",iconPath:"/payment_methods/farmacias_san_francisco.png"},[ve.FARM911]:{label:"Farmacias 911",iconPath:"/payment_methods/store.png"},[ve.FARMECONOMICAS]:{label:"Farmacias Economicas",iconPath:"/payment_methods/store.png"},[ve.FARMMEDICITY]:{label:"Farmacias Medicity",iconPath:"/payment_methods/store.png"},[ve.RIANXEIRA]:{label:"Rianxeira",iconPath:"/payment_methods/store.png"},[ve.WESTERNUNION]:{label:"Western Union",iconPath:"/payment_methods/store.png"},[ve.ZONAPAGO]:{label:"Zona Pago",iconPath:"/payment_methods/store.png"},[ve.CAJALOSANDES]:{label:"Caja Los Andes",iconPath:"/payment_methods/store.png"},[ve.CAJAPAITA]:{label:"Caja Paita",iconPath:"/payment_methods/store.png"},[ve.CAJASANTA]:{label:"Caja Santa",iconPath:"/payment_methods/store.png"},[ve.CAJASULLANA]:{label:"Caja Sullana",iconPath:"/payment_methods/store.png"},[ve.CAJATRUJILLO]:{label:"Caja Trujillo",iconPath:"/payment_methods/store.png"},[ve.EDPYME]:{label:"Edpyme",iconPath:"/payment_methods/store.png"},[ve.KASNET]:{label:"KasNet",iconPath:"/payment_methods/store.png"},[ve.NORANDINO]:{label:"Norandino",iconPath:"/payment_methods/store.png"},[ve.QAPAQ]:{label:"Qapaq",iconPath:"/payment_methods/store.png"},[ve.RAIZ]:{label:"Raiz",iconPath:"/payment_methods/store.png"},[ve.PAYSER]:{label:"Paysera",iconPath:"/payment_methods/store.png"},[ve.WUNION]:{label:"Western Union",iconPath:"/payment_methods/store.png"},[ve.BANCOCONTINENTAL]:{label:"Banco Continental",iconPath:"/payment_methods/store.png"},[ve.GMONEY]:{label:"Go money",iconPath:"/payment_methods/store.png"},[ve.GOPAY]:{label:"Go pay",iconPath:"/payment_methods/store.png"},[ve.WU]:{label:"Western Union",iconPath:"/payment_methods/store.png"},[ve.PUNTOSHEY]:{label:"Puntoshey",iconPath:"/payment_methods/store.png"},[ve.AMPM]:{label:"Ampm",iconPath:"/payment_methods/store.png"},[ve.JUMBOMARKET]:{label:"Jumbomarket",iconPath:"/payment_methods/store.png"},[ve.SMELPUEBLO]:{label:"Smelpueblo",iconPath:"/payment_methods/store.png"},[ve.BAM]:{label:"Bam",iconPath:"/payment_methods/store.png"},[ve.REFACIL]:{label:"Refacil",iconPath:"/payment_methods/store.png"},[ve.ACYVALORES]:{label:"Acyvalores",iconPath:"/payment_methods/store.png"}},Ae=(e,t="stage")=>{const r=e.toUpperCase().trim().replace(/\s+/g,"");const o=Ce[r]||{iconPath:"/payment_methods/store.png",label:""};return{label:o.label,icon:`${l(t)}${o.iconPath}`}};class Oe extends Q{constructor({apiKey:e,mode:t,returnUrl:r,callBack:o,apiKeyTonder:i,baseUrlTonder:n,customization:s,collectorIds:a,events:d}){super({mode:t,apiKey:e,returnUrl:r,callBack:o,apiKeyTonder:i,baseUrlTonder:n,customization:s,tdsIframeId:a&&"tdsIframe"in a?null==a?void 0:a.tdsIframe:"tdsIframe",sdkInfo:L}),this.activeAPMs=[],this.mountedElementsByContext=new Map,this.customerCardsCache=null,this.lastCollectedTokens=null,this.skyflowInstance=null,this.events=d||{}}injectCheckout(){return t(this,void 0,void 0,(function*(){yield this._initializeCheckout()}))}getCustomerCards(){return t(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=>Object.assign(Object.assign({},e),{fields:Object.assign(Object.assign({},e.fields),{subscription_id:this._hasCardOnFileKeys()?e.fields.subscription_id:void 0}),icon:h(e.fields.card_scheme,this.mode)})))})}catch(e){throw this.reportSdkError(e,{feature:"get-cards",process_id:this.getCustomerId(),metadata:{step:"getCustomerCards"}}),C({errorCode:n.FETCH_CARDS_ERROR},e)}}))}saveCustomerCard(){return t(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:i="",email:s=""}=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:i||"",email:s||""},customerId:r,currency:this.currency||"MXN"})}catch(e){throw C({errorCode:n.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"}}),C({errorCode:n.SAVE_CARD_ERROR},t)}}))}removeCustomerCard(e){return t(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"}}),C({errorCode:n.REMOVE_CARD_ERROR},t)}}))}getCustomerPaymentMethods(){return t(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},Ae(e.payment_method,this.mode)))).sort(((e,t)=>e.priority-t.priority))}catch(e){throw this.reportSdkError(e,{feature:"get-payment-methods",metadata:{step:"getCustomerPaymentMethods"}}),C({errorCode:n.FETCH_PAYMENT_METHODS_ERROR},e)}}))}mountCardFields(r){var o;return t(this,void 0,void 0,(function*(){const i=r.card_id?`update:${r.card_id}`:"create",n=null!==(o=r.unmount_context)&&void 0!==o?o:"all";"none"!==n&&("current"===n?this.unmountCardFields(i):this.unmountCardFields(n)),yield this.createSkyflowInstance();const s=yield function(r){var o,i,n,s,a,d,l,c,u,h,E,_,R;return t(this,void 0,void 0,(function*(){const{skyflowInstance:t,data:m,customization:p,events:y}=r,v=t.container(e.ContainerType.COLLECT),C=[],A={[X.CVV]:e.ElementType.CVV,[X.CARD_NUMBER]:e.ElementType.CARD_NUMBER,[X.EXPIRATION_MONTH]:e.ElementType.EXPIRATION_MONTH,[X.EXPIRATION_YEAR]:e.ElementType.EXPIRATION_YEAR,[X.CARDHOLDER_NAME]:e.ElementType.CARDHOLDER_NAME},O={[X.CVV]:[Z],[X.CARD_NUMBER]:[Z],[X.EXPIRATION_MONTH]:[Z],[X.EXPIRATION_YEAR]:[Z],[X.CARDHOLDER_NAME]:[J,Z]},T={[X.CARDHOLDER_NAME]:"cardholderName",[X.CARD_NUMBER]:"cardNumber",[X.CVV]:"cvv",[X.EXPIRATION_MONTH]:"expirationMonth",[X.EXPIRATION_YEAR]:"expirationYear"},f=e=>{var t,r,o,i,n,s,a,d,l;const c=null===(t=null==p?void 0:p.styles)||void 0===t?void 0:t[T[e]],u=null===(r=null==p?void 0:p.styles)||void 0===r?void 0:r.cardForm,h=null!==(i=null!==(o=null==c?void 0:c.inputStyles)&&void 0!==o?o:null==u?void 0:u.inputStyles)&&void 0!==i?i:ue;return{inputStyles:e===X.CARD_NUMBER&&!1!==(null===(n=null==p?void 0:p.styles)||void 0===n?void 0:n.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:he,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:Ee}},S={cardholder_name:(null===(o=null==p?void 0:p.labels)||void 0===o?void 0:o.name)||ee,card_number:(null===(i=null==p?void 0:p.labels)||void 0===i?void 0:i.card_number)||te,cvv:(null===(n=null==p?void 0:p.labels)||void 0===n?void 0:n.cvv)||re,expiration_date:(null===(s=null==p?void 0:p.labels)||void 0===s?void 0:s.expiry_date)||ne,expiration_month:(null===(a=null==p?void 0:p.labels)||void 0===a?void 0:a.expiration_month)||oe,expiration_year:(null===(d=null==p?void 0:p.labels)||void 0===d?void 0:d.expiration_year)||ie},I={cardholder_name:(null===(l=null==p?void 0:p.placeholders)||void 0===l?void 0:l.name)||se,card_number:(null===(c=null==p?void 0:p.placeholders)||void 0===c?void 0:c.card_number)||ae,cvv:(null===(u=null==p?void 0:p.placeholders)||void 0===u?void 0:u.cvv)||de,expiration_month:(null===(h=null==p?void 0:p.placeholders)||void 0===h?void 0:h.expiration_month)||le,expiration_year:(null===(E=null==p?void 0:p.placeholders)||void 0===E?void 0:E.expiration_year)||ce},g={[X.CVV]:null==y?void 0:y.cvvEvents,[X.CARD_NUMBER]:null==y?void 0:y.cardNumberEvents,[X.EXPIRATION_MONTH]:null==y?void 0:y.monthEvents,[X.EXPIRATION_YEAR]:null==y?void 0:y.yearEvents,[X.CARDHOLDER_NAME]:null==y?void 0:y.cardHolderEvents};if("fields"in m&&Array.isArray(m.fields)){const e={enableCardIcon:null===(R=null===(_=null==p?void 0:p.styles)||void 0===_?void 0:_.enableCardIcon)||void 0===R||R};if(m.fields.length>0&&"string"==typeof m.fields[0])for(const t of m.fields){const r=v.create(Object.assign(Object.assign(Object.assign({table:"cards",column:t,type:A[t],validations:O[t]},f(t)),{label:S[t],placeholder:I[t]}),m.card_id?{skyflowID:m.card_id}:{}),t===X.CARD_NUMBER?e:void 0);Re({element:r,errorStyles:f(t).errorStyles,fieldMessage:[X.CVV,X.EXPIRATION_MONTH,X.EXPIRATION_YEAR].includes(t)?"":S[t],events:g[t]});const o=`#collect_${String(t)}`+(m.card_id?`_${m.card_id}`:"");yield ye({element:r,containerId:o}),C.push({element:r,containerId:o})}else for(const t of m.fields){const r=t.field,o=v.create(Object.assign(Object.assign(Object.assign({table:"cards",column:r,type:A[r],validations:O[r]},f(r)),{label:S[r],placeholder:I[r]}),m.card_id?{skyflowID:m.card_id}:{}),r===X.CARD_NUMBER?e:void 0);Re({element:o,errorStyles:f(r).errorStyles,fieldMessage:[X.CVV,X.EXPIRATION_MONTH,X.EXPIRATION_YEAR].includes(r)?"":S[r],events:g[r]});const i=t.container_id||`#collect_${String(r)}`+(m.card_id?`_${m.card_id}`:"");yield ye({element:o,containerId:i}),C.push({element:o,containerId:i})}}return{elements:C.map((e=>e.element)),container:v}}))}({skyflowInstance:this.skyflowInstance,data:r,customization:this.customization,events:this.events});this.mountedElementsByContext.set(i,{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 r,o,i;return t(this,void 0,void 0,(function*(){const t=this.getContainerByCardId(e);if(!t)return null;try{const e=yield t.collect();return(null===(o=null===(r=null==e?void 0:e.records)||void 0===r?void 0:r[0])||void 0===o?void 0:o.fields)||null}catch(t){const r=null===(i=null==t?void 0:t.error)||void 0===i?void 0:i.description;throw this.reportSdkError(t,{feature:"collect-card-tokens",process_id:e,metadata:{step:"collectCardTokens"}}),new a({code:n.MOUNT_COLLECT_ERROR,details:{message:r}})}}))}collectCreateCardTokens(){var e,r,o,i;return t(this,void 0,void 0,(function*(){const t=this.mountedElementsByContext.get("create"),s=null===(e=null==t?void 0:t.container)||void 0===e?void 0:e.container;if(!s)throw new a({code:n.MOUNT_COLLECT_ERROR,details:{message:"No card fields are mounted. Call mountCardFields() with the required fields before proceeding."}});try{const e=yield s.collect(),t=(null===(o=null===(r=null==e?void 0:e.records)||void 0===r?void 0:r[0])||void 0===o?void 0:o.fields)||{};return this.lastCollectedTokens=t,t}catch(e){const t=null===(i=null==e?void 0:e.error)||void 0===i?void 0:i.description;throw this.reportSdkError(e,{feature:"collect-create-card-tokens",metadata:{step:"collectCreateCardTokens"}}),new a({code:n.MOUNT_COLLECT_ERROR,details:{message:t}})}}))}revealCardFields(r){return t(this,void 0,void 0,(function*(){if(!this.lastCollectedTokens)throw C({errorCode:n.MOUNT_COLLECT_ERROR,details:{message:"No card tokens available. Call saveCustomerCard() or payment() with a new card before calling revealCardFields()."}});if(!this.skyflowInstance)throw C({errorCode:n.MOUNT_COLLECT_ERROR,details:{message:"Skyflow instance not initialized. Ensure mountCardFields() was called before saveCustomerCard() or payment()."}});yield function(r){var o,i,n,s,a,d;return t(this,void 0,void 0,(function*(){const{skyflowInstance:t,tokens:l,request:c}=r,u=t.container(e.ContainerType.REVEAL),h={[X.CARD_NUMBER]:"MASKED",[X.CARDHOLDER_NAME]:"PLAIN_TEXT",[X.EXPIRATION_MONTH]:"PLAIN_TEXT",[X.EXPIRATION_YEAR]:"PLAIN_TEXT"};for(const t of c.fields){const r="string"==typeof t,E=r?t:t.field;if(E===X.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 R=r?{}:t,m=null!==(o=R.container_id)&&void 0!==o?o:`#reveal_${E}`,p=h[E],y=null!==(i=R.styles)&&void 0!==i?i:{},v=null!==(n=c.styles)&&void 0!==n?n:{},C=u.create(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({token:_,redaction:e.RedactionType[p]},void 0!==R.altText&&{altText:R.altText}),void 0!==R.label&&{label:R.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 ye({element:C,containerId:m})}try{yield u.reveal()}catch(e){console.warn("[revealCardFields] reveal completed with errors:",e)}}))}({skyflowInstance:this.skyflowInstance,tokens:this.lastCollectedTokens,request:r})}))}unmountCardFields(e="all"){"all"===e?(this.mountedElementsByContext.forEach(((e,t)=>{this.unmountContext(t)})),this.mountedElementsByContext.clear()):(this.unmountContext(e),this.mountedElementsByContext.delete(e))}unmountContext(e){const t=this.mountedElementsByContext.get(e);if(!t)return;const{elements:r}=t;r&&r.length>0&&r.forEach((t=>{try{t&&"function"==typeof t.unmount&&t.unmount()}catch(t){console.warn(`Error unmounting Skyflow element from context '${e}':`,t),this.reportSdkError(t,{feature:"unmount-card-fields",metadata:{step:"unmountContext",context:e}})}}))}getBusiness(){return t(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"}}),C({errorCode:n.FETCH_BUSINESS_ERROR},e)}}))}createSkyflowInstance(){return t(this,void 0,void 0,(function*(){if(this.skyflowInstance)return this.skyflowInstance;yield this._fetchMerchantData();const{vault_id:r,vault_url:o}=this.merchantData;this.skyflowInstance=yield function({baseUrl:r,apiKey:o,vault_id:i,vault_url:n,mode:s}){return t(this,void 0,void 0,(function*(){const a="production"===s?e.Env.PROD:e.Env.DEV;return e.init({vaultID:i,vaultURL:n,getBearerToken:()=>t(this,void 0,void 0,(function*(){return yield W(r,o)})),options:{logLevel:e.LogLevel.ERROR,env:a}})}))}({vault_id:r,vault_url:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder,mode:this.mode})}))}getOpenpayDeviceSessionID(e,r,o){return t(this,void 0,void 0,(function*(){try{return yield f(e,r,o)}catch(e){throw this.reportSdkError(e,{feature:"get-openpay-device-session",metadata:{step:"getOpenpayDeviceSessionID"}}),C({errorCode:n.START_CHECKOUT_ERROR},e)}}))}getSkyflowTokens({vault_id:e,vault_url:r,data:o}){return t(this,void 0,void 0,(function*(){return yield _e({vault_id:e,vault_url:r,data:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}_setCartTotal(e){this.cartTotal=e}_checkout({card:e,payment_method:r,isSandbox:o,returnUrl:i}){var s,a;return t(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 R,m=null,p=null,y=null,v=!1;const A=()=>t(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(!r){if("string"==typeof e)if(p=e,R={skyflow_id:e},_){yield A();const t=null===(a=null===(s=this.customerCardsCache)||void 0===s?void 0:s.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&&(m={subscriptionId:t.fields.subscription_id})}else yield this.collectCardTokens(e);else R=yield this.collectCreateCardTokens(),p=R.skyflow_id,_&&(y={name:R.cardholder_name,number:R.card_number,expiryMonth:R.expiration_month,expiryYear:R.expiration_year,cvv:R.cvv},v=!0);if(v){if(!p||!y)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:p},!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 i;try{i=yield o.process({cardTokens:y,cardBin:r,contactDetails:{firstName:u||"",lastName:h||"",email:E||""},customerId:c,currency:this.currency||"MXN"})}catch(e){throw C({errorCode:n.CARD_ON_FILE_DECLINED,lockErrorCode:!0},e)}m={subscriptionId:i.subscriptionId},yield this._saveCustomerCard(c,null==l?void 0:l.pk,{skyflow_id:p,subscription_id:m.subscriptionId})}catch(t){throw e&&(yield this.removeCustomerCard(e)),this.reportSdkError(t,{feature:"payment",process_id:e||this.getCustomerId(),metadata:{step:"card_on_file"}}),t}}}return yield this._handleCheckout({card:R,payment_method:r,customer:d,isSandbox:o,returnUrl:i,enable_card_on_file:!!(null==m?void 0:m.subscriptionId)&&_})}))}customerRegister(e){return t(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 C({response:o,errorCode:n.CUSTOMER_OPERATION_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"customer-register",metadata:{step:"customerRegister"}}),C({errorCode:n.CUSTOMER_OPERATION_ERROR},e)}}))}createOrder(e){return t(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 C({response:o,errorCode:n.CREATE_ORDER_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"create-order",metadata:{step:"createOrder"}}),C({errorCode:n.CREATE_ORDER_ERROR},e)}}))}createPayment(e){return t(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 C({response:o,errorCode:n.CREATE_PAYMENT_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"create-payment",metadata:{step:"createPayment"}}),C({errorCode:n.CREATE_PAYMENT_ERROR},e)}}))}startCheckoutRouter(e){return t(this,void 0,void 0,(function*(){const t=yield T(this.baseUrl,this.apiKeyTonder,e);if(yield this.init3DSRedirect(t))return t}))}init3DSRedirect(e){return t(this,void 0,void 0,(function*(){return this.process3ds.setPayload(e),yield this._handle3dsRedirect(e)}))}startCheckoutRouterFull(e){return t(this,void 0,void 0,(function*(){try{const{order:t,total:r,customer:o,skyflowTokens:i,return_url:s,isSandbox:a,metadata:d,currency:l,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 C({errorCode:n.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),R=(new Date).toISOString();if(!("id"in _&&"id"in E&&"business"in h))throw C({errorCode:n.START_CHECKOUT_ERROR,details:{message:"Order response errors",orderResult:_}});{const e={business_pk:h.business.pk,amount:r,date:R,order_id:_.id,client_id:E.id},t=yield this.createPayment(e);let n;const{openpay_keys:m,business:p}=h;m.merchant_id&&m.public_key&&(n=yield f(m.merchant_id,m.public_key,a));const y=Object.assign(Object.assign({name:o.name,last_name:o.lastname,email_client:o.email,phone_number:o.phone,return_url:s,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:r,title_ship:"shipping",description:"transaction",device_session_id:n||null,token_id:"",order_id:"id"in _&&_.id,business_id:p.pk,payment_id:"pk"in t&&t.pk,source:"sdk",metadata:d,browser_info:c(),currency:l},u?{payment_method:u}:{card:i}),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}),v=yield T(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"}}),C({errorCode:n.START_CHECKOUT_ERROR},e)}}))}registerCustomerCard(e,r,o){return t(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const t=yield fetch(`${this.baseUrl}/api/v1/business/${u(this.merchantData)}/cards/`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"User-token":r,"Content-Type":"application/json"},body:JSON.stringify(Object.assign({},o))});if(t.ok)return yield t.json();throw yield C({response:t,errorCode:n.SAVE_CARD_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"register-customer-card",metadata:{step:"registerCustomerCard"}}),C({errorCode:n.SAVE_CARD_ERROR},e)}}))}deleteCustomerCard(e,r=""){return t(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const t=yield fetch(`${this.baseUrl}/api/v1/business/${u(this.merchantData)}/cards/${r}`,{method:"DELETE",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.abortController.signal});if(t.ok)return!0;throw yield C({response:t,errorCode:n.REMOVE_CARD_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"delete-customer-card",process_id:r,metadata:{step:"deleteCustomerCard"}}),C({errorCode:n.REMOVE_CARD_ERROR},e)}}))}getActiveAPMs(){return t(this,void 0,void 0,(function*(){try{const e=yield function(e,r,o="?status=active&page_size=10000&country=México",i=null){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${e}/api/v1/payment_methods${o}`,{method:"GET",headers:{Authorization:`Token ${r}`,"Content-Type":"application/json"},signal:i});if(t.ok)return yield t.json();throw yield C({response:t,errorCode:n.FETCH_PAYMENT_METHODS_ERROR})}))}(this.baseUrl,this.apiKeyTonder),r=e&&e.results&&e.results.length>0?e.results:[];return this.activeAPMs=r.filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},Ae(e.payment_method,this.mode)))).sort(((e,t)=>e.priority-t.priority)),this.activeAPMs}catch(e){return console.error("Error getting APMS",e),[]}}))}}function Te(e){return/^\d{12,19}$/.test(e)&&Ne(e)}function fe(e){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(e)}function Se(e){return/^\d{3,4}$/.test(e)}function Ie(e){return/^(0[1-9]|1[0-2])$/.test(e)}function ge(e){if(!/^\d{2}$/.test(e))return!1;const t=(new Date).getFullYear()%100;return parseInt(e,10)>=t}const Ne=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{R as AppError,Q as BaseInlineCheckout,Oe as LiteCheckout,U as SdkTelemetryClient,Se as validateCVV,Te as validateCardNumber,fe as validateCardholderName,Ie as validateExpirationMonth,ge as validateExpirationYear};
|
|
1
|
+
import e from"skyflow-js";function t(e,t,r,o){return new(r||(r=Promise))((function(i,n){function s(e){try{d(o.next(e))}catch(e){n(e)}}function a(e){try{d(o.throw(e))}catch(e){n(e)}}function d(e){var t;e.done?i(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 r(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 o(e,t,r,o,i){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?i.call(e,r):i?i.value=r:t.set(e,r),r}"function"==typeof SuppressedError&&SuppressedError;const i=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"}),n=Object.freeze({TELEMETRY:"/telemetry/v1/events",ACQ_SUBSCRIPTION_TOKEN:"/acq-kushki/subscription/token",ACQ_SUBSCRIPTION_CREATE:"/acq-kushki/subscription/create",CORE_BUSINESS_CONFIG:"/transactions/v1/business/config",CORE_PROCESS:"/transactions/v1/process"});function s(e="stage"){return`${i[e]}${n.TELEMETRY}`}function a(e="stage"){return i[e]}var d;!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"}(d||(d={}));const l={[d.INIT_ERROR]:"Error initializing the SDK.",[d.INVALID_TYPE]:"SDK Type invalid.",[d.STATE_ERROR]:"Error updating SDK state.",[d.FETCH_BUSINESS_ERROR]:"Error retrieving merchant information.",[d.INVALID_CONFIG]:"Required configuration options.",[d.MERCHANT_CREDENTIAL_REQUIRED]:"Merchant credential required.",[d.INVALID_PAYMENT_REQUEST]:"The payment data must be of type: :::interface:::.",[d.INVALID_PAYMENT_REQUEST_CARD_PM]:"The fields card and payment_method cannot be provided together.",[d.TYPE_SDK_REQUIRED]:"SDK type required.",[d.ENVIRONMENT_REQUIRED]:"Environment required.",[d.FETCH_CARDS_ERROR]:"Error retrieving cards.",[d.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.",[d.SAVE_CARD_ERROR]:"Error saving the card.",[d.REMOVE_CARD_ERROR]:"Error deleting the card.",[d.CREATE_PAYMENT_ERROR]:"Error creating the payment.",[d.PAYMENT_PROCESS_ERROR]:"There was an issue processing the payment.",[d.CARD_SAVED_SUCCESSFULLY]:"Card saved successfully.",[d.CARD_REMOVED_SUCCESSFULLY]:"Card deleted successfully.",[d.SAVE_CARD_PROCESS_ERROR]:"Error processing card data.",[d.START_CHECKOUT_ERROR]:"Error processing the payment.",[d.CREATE_ORDER_ERROR]:"Error creating the order.",[d.BUSINESS_ID_REQUIRED]:"Business ID is required.",[d.CLIENT_ID_REQUIRED]:"Client ID is required.",[d.INVALID_AMOUNT]:"Invalid amount.",[d.INVALID_ITEMS]:"Invalid items.",[d.CUSTOMER_OPERATION_ERROR]:"Error registering or fetching customer",[d.INVALID_EMAIL]:"Invalid email.",[d.FETCH_PAYMENT_METHODS_ERROR]:"Error retrieving active payment methods.",[d.INVALID_VAULT_TOKEN]:"An invalid vault token response was received.",[d.VAULT_TOKEN_ERROR]:"Error retrieving the vault token.",[d.SECURE_TOKEN_ERROR]:"Error getting secure token.",[d.SECURE_TOKEN_INVALID]:"Invalid secure token.",[d.INVALID_SECRET_API_KEY]:"SECRET API KEY is required.",[d.REMOVE_CARD]:"Card deleted successfully",[d.SKYFLOW_NOT_INITIALIZED]:"Skyflow not initialized.",[d.ERROR_LOAD_PAYMENT_FORM]:"There was an issue loading the payment form.",[d.INVALID_CARD_DATA]:"Invalid card data.",[d.ERROR_LOAD_ENROLLMENT_FORM]:"There was an issue loading the card form.",[d.MOUNT_COLLECT_ERROR]:"Mount failed. Make sure all inputs are complete and valid.",[d.CARD_ON_FILE_DECLINED]:"Transaction declined. Please verify your card details.",[d.REQUEST_ABORTED]:"Requests canceled.",[d.REQUEST_FAILED]:"Request failed.",[d.UNKNOWN_ERROR]:"An unexpected error occurred.",[d.CREATE_ERROR]:"Error creating the SDK.",[d.FETCH_TRANSACTION_ERROR]:"Error retrieving the transaction.",[d.THREEDS_REDIRECTION_ERROR]:"An error occurred during the 3DS redirection.",[d.REMOVE_SDK_ERROR]:"An error occurred while removing the SDK instance."};d.INIT_ERROR,d.STATE_ERROR,d.FETCH_BUSINESS_ERROR,d.INVALID_CONFIG,d.TYPE_SDK_REQUIRED,d.ENVIRONMENT_REQUIRED,d.FETCH_CARDS_ERROR,d.SAVE_CARD_ERROR,d.REMOVE_CARD_ERROR,d.CREATE_PAYMENT_ERROR,d.START_CHECKOUT_ERROR,d.CREATE_ORDER_ERROR,d.BUSINESS_ID_REQUIRED,d.CLIENT_ID_REQUIRED,d.INVALID_AMOUNT,d.INVALID_ITEMS,d.CUSTOMER_OPERATION_ERROR,d.INVALID_EMAIL,d.FETCH_PAYMENT_METHODS_ERROR,d.INVALID_VAULT_TOKEN,d.VAULT_TOKEN_ERROR,d.SECURE_TOKEN_ERROR,d.INVALID_SECRET_API_KEY,d.CUSTOMER_AUTH_TOKEN_NOT_VALID,d.SECURE_TOKEN_INVALID,d.REMOVE_CARD,d.SKYFLOW_NOT_INITIALIZED,d.INVALID_TYPE,d.PAYMENT_PROCESS_ERROR,d.INVALID_PAYMENT_REQUEST,d.INVALID_PAYMENT_REQUEST_CARD_PM,d.SAVE_CARD_PROCESS_ERROR,d.ERROR_LOAD_PAYMENT_FORM,d.INVALID_CARD_DATA,d.ERROR_LOAD_ENROLLMENT_FORM,d.MOUNT_COLLECT_ERROR,d.CARD_ON_FILE_DECLINED,d.CARD_SAVED_SUCCESSFULLY,d.CARD_REMOVED_SUCCESSFULLY,d.REQUEST_ABORTED,d.REQUEST_FAILED,d.UNKNOWN_ERROR,d.CREATE_ERROR,d.FETCH_TRANSACTION_ERROR,d.THREEDS_REDIRECTION_ERROR,d.REMOVE_SDK_ERROR;const c="__tonderLockErrorCode__";function u(e){return"object"==typeof e&&null!==e}class h extends Error{constructor(e){var t,r;const o=h.resolveStatusCode(e.statusCode,e.originalError),i=h.resolveMessage(e.errorCode,e.message),n=h.resolveSystemError(null===(t=e.details)||void 0===t?void 0:t.systemError,e.originalError);super(i),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:n},e.lockErrorCode&&Object.defineProperty(this,c,{value:!0,enumerable:!1,configurable:!0}),null===(r=Error.captureStackTrace)||void 0===r||r.call(Error,this,h)}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(h.isRecord(t)){r.push(t.statusCode,t.status);const e=h.isRecord(t.body)?t.body:null;e&&r.push(e.statusCode,e.status)}for(const e of r)if(h.isHttpStatusCode(e))return Math.trunc(Number(e));return 500}static resolveMessage(e,t){return t||(l[e]||l[d.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(h.isRecord(t)){const e=h.isRecord(t.details)?t.details:null,o=h.isRecord(t.body)?t.body:null,i=o&&h.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==i?void 0:i.systemError,null==i?void 0:i.code)}for(const e of r){const t=h.normalizeSystemError(e);if(t)return t}return"APP_INTERNAL_001"}}function _(e){return u(e)&&!0===e[c]}function E(e){return e instanceof h&&void 0!==e.originalError?e.originalError:e}function m(e){return t(this,void 0,void 0,(function*(){try{return yield e.clone().json()}catch(e){}try{return(yield e.text())||void 0}catch(e){return}}))}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,i=!!e.message||void 0!==e.statusCode||void 0!==o;return!function(e){return u(e)&&"TonderError"===e.name&&"string"==typeof e.code}(t)||(e.lockErrorCode&&function(e){Object.defineProperty(e,c,{value:!0,enumerable:!1,configurable:!0})}(t),i||e.errorCode!==t.code&&!_(t))?new h({errorCode:e.errorCode,message:e.message,statusCode:e.statusCode,details:void 0!==o?{systemError:o}:void 0,originalError:E(t),lockErrorCode:e.lockErrorCode||_(t)}):t}function p(e){var t,r;const o={status:e.status};return e.statusText&&(o.statusText=e.statusText),void 0!==e.body&&(o.body=e.body),new h({errorCode:e.errorCode,message:e.message,statusCode:null!==(t=e.statusCode)&&void 0!==t?t:e.status,details:void 0!==(null===(r=e.details)||void 0===r?void 0:r.systemError)?{systemError:e.details.systemError}:void 0,originalError:o,lockErrorCode:e.lockErrorCode})}function y(e,r){return(null==e?void 0:e.response)?function(e){return t(this,void 0,void 0,(function*(){return p(Object.assign(Object.assign({},e),{status:e.response.status,statusText:e.response.statusText,body:yield m(e.response)}))}))}(e):R(e,r)}function v(e,r,o){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${e}${n.CORE_BUSINESS_CONFIG}`,{headers:{Authorization:`Token ${r}`},signal:o});if(t.ok)return yield t.json();throw yield y({response:t,errorCode:d.FETCH_BUSINESS_ERROR})}))}class C extends Error{constructor(e){var t,r;const o=e.message||l[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 f=Object.freeze({production:"https://d35a75syrgujp0.cloudfront.net",sandbox:"https://static.staging.tonder.io",stage:"https://static.staging.tonder.io",development:"https://static.staging.tonder.io"});function A(e="stage"){return f[e]||f.stage}const O=()=>({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}),T=e=>{var t;return e&&"business"in e?null===(t=null==e?void 0:e.business)||void 0===t?void 0:t.pk:""},S=e=>!e||"card"===e.toLowerCase(),g=(e,t="stage")=>{const r=A(t);return"Visa"===e?`${r}/cards/visa.png`:"Mastercard"===e?`${r}/cards/mastercard.png`:"American Express"===e?`${r}/cards/american_express.png`:`${r}/cards/default_card.png`};const I=new Set(["https:"]);function N(e){if("string"!=typeof e)return!1;try{return I.has(new URL(e,document.baseURI).protocol)}catch(e){return!1}}const b=new Set(["script","object","embed","applet","link","meta","base","style","template"]),D=new Set(["srcdoc","style","ping","srcset"]),k=new Set(["src","href","action","formaction","data","poster","background"]);function M(e){const t=e.trim();return""===t||("about:blank"===t.toLowerCase()||N(t))}function P(e){for(const t of Array.from(e.attributes)){const r=t.localName.toLowerCase();r.startsWith("on")||D.has(r)?e.removeAttributeNode(t):k.has(r)&&!M(t.value)&&e.removeAttributeNode(t)}}const U=["Pending","Processing"];class L{constructor({payload:e=null,apiKey:t,baseUrl:r,coreBaseUrl:o,buildCoreResult:i=(e=>e),redirectOnComplete:n,tdsIframeId:s,tonderPayButtonId:a,callBack:d}){this.engine="legacy",this.localStorageKey="verify_transaction_status_url",this.setPayload=e=>{this.payload=e},this.buildCoreResult=i,this.baseUrl=r,this.coreBaseUrl=o,this.apiKey=t,this.payload=e,this.tdsIframeId=s,this.tonderPayButtonId=a,this.redirectOnComplete=n,this.callBack=d}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,i,n;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===(n=null===(i=null===(o=this.payload)||void 0===o?void 0:o.next_action)||void 0===i?void 0:i.iframe_resources)||void 0===n?void 0:n.verify_transaction_status_url;e?this.saveUrlWithExpiration(e):console.log("No verify_transaction_status_url found")}}setEngine(e){this.engine=e}saveUrlWithExpiration(e){try{const t={url:e,expires:(new Date).getTime()+12e5,engine:this.engine};this.setStorageItem(t)}catch(e){console.log("error: ",e)}}getStoredVerification(){const e=this.getStorageItem();if(e){const t=JSON.parse(e);if(!t)return;return(new Date).getTime()>t.expires?(this.removeVerifyTransactionUrl(),null):t}return null}getUrlWithExpiration(){var e;const t=this.getStoredVerification();return void 0===t?void 0:null!==(e=null==t?void 0:t.url)&&void 0!==e?e:null}getStoredEngine(){var e;return"core"===(null===(e=this.getStoredVerification())||void 0===e?void 0:e.engine)?"core":"legacy"}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,i;const n=null===(i=null===(o=null===(r=this.payload)||void 0===r?void 0:r.next_action)||void 0===o?void 0:o.iframe_resources)||void 0===i?void 0:i.iframe;if(n){this.saveVerifyTransactionUrl();const r=document.createElement("div");r.style.display="none",r.appendChild(function(e){const t=(new DOMParser).parseFromString(e,"text/html");for(const e of Array.from(t.body.querySelectorAll("*")))"http://www.w3.org/1999/xhtml"!==e.namespaceURI||b.has(e.localName)?e.remove():P(e);const r=document.createDocumentFragment();for(const e of Array.from(t.body.childNodes))r.appendChild(document.importNode(e,!0));return r}(n)),document.body.appendChild(r);const o=document.createElement("script");o.textContent='document.getElementById("tdsMmethodForm").submit();',r.appendChild(o);const i=document.getElementById("tdsMmethodTgtFrame");i?i.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(!N(e))throw y({errorCode:d.THREEDS_REDIRECTION_ERROR,statusCode:400,lockErrorCode:!0});if(this.saveVerifyTransactionUrl(),this.redirectOnComplete)window.location=e;else{const r=document.querySelector(`#${this.tdsIframeId}`);if(r){r.setAttribute("src",e),r.setAttribute("style","display: block");const o=this,i=e=>t(this,void 0,void 0,(function*(){const e=()=>{try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}r&&r.setAttribute("style","display: none"),o.callBack&&o.callBack(o.payload),r.removeEventListener("load",i)},n=r=>t(this,void 0,void 0,(function*(){const i=yield new Promise(((e,t)=>e(r)));if(i){if((e=>o.isVerificationFinal(e))(i))return e();{const e=setTimeout((()=>t(this,void 0,void 0,(function*(){clearTimeout(e),yield n(o.requestTransactionStatus())}))),7e3)}}}));yield n(o.requestTransactionStatus())}));r.addEventListener("load",i)}else console.log("No iframe found")}}else this.callBack&&this.callBack(this.payload)}fetchVerification(e){return t(this,void 0,void 0,(function*(){const t="core"===e.engine?this.coreBaseUrl:this.baseUrl,r=e.url.startsWith("https://")?e.url:`${t}${e.url}`;return yield fetch(r,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}})}))}requestTransactionStatus(){return t(this,void 0,void 0,(function*(){const e=this.getStoredVerification();if(!e)return null;let t;try{if(t=yield this.fetchVerification(e),200===t.status)return yield t.json()}catch(t){if(this.isTransientCoreFailure(e))return this.keepPolling();throw t}return console.error("La verificación de la transacción falló."),this.isTransientCoreFailure(e,t.status)?this.keepPolling():null}))}keepPolling(){return{status:"Pending",transaction_status:"Pending"}}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 t(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 t(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)}))}isCoreOpen(e){return U.includes(null==e?void 0:e.status)}handleCoreTransaction(e){return t(this,void 0,void 0,(function*(){const t=yield e.json();return this.isCoreOpen(t)||this.removeVerifyTransactionUrl(),this.buildCoreResult(t)}))}isVerificationFinal(e){return"core"===this.engine?!this.isCoreOpen(e):"Pending"!==(null==e?void 0:e.transaction_status)}isTransientCoreFailure(e,t){return"core"===e.engine&&(void 0===t||t>=500||429===t||408===t)}verifyTransactionStatus(){return t(this,void 0,void 0,(function*(){const e=this.getStoredVerification();if(null==e?void 0:e.url)try{const t=yield this.fetchVerification(e);if(200!==t.status){if(console.error("La verificación de la transacción falló."),this.isTransientCoreFailure(e,t.status)||this.removeVerifyTransactionUrl(),"core"===e.engine)throw yield y({response:t,errorCode:d.FETCH_TRANSACTION_ERROR});return t}return"core"===e.engine?yield this.handleCoreTransaction(t):yield this.handleTransactionResponse(t)}catch(t){if(console.error("Error al verificar la transacción:",t),"core"===e.engine)throw y({errorCode:d.FETCH_TRANSACTION_ERROR},t);this.removeVerifyTransactionUrl()}else console.log("No verify_transaction_status_url found")}))}}const w=Object.freeze({production:"https://app.tonder.io",sandbox:"https://sandbox.tonder.io",stage:"https://stage.tonder.io",development:"http://localhost:8000"});function V(e,r,o){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/checkout-router/`,i=o,n=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${r}`},body:JSON.stringify(Object.assign(Object.assign({},i),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}))});if(n.ok)return yield n.json();throw yield y({response:n,errorCode:d.START_CHECKOUT_ERROR})}))}function F(e,r,o=!0,i=null){return t(this,void 0,void 0,(function*(){let t=yield window.OpenPay;return t.setId(e),t.setApiKey(r),t.setSandboxMode(o),yield t.deviceData.setup({signal:i})}))}function K(e){return/^\d{12,19}$/.test(e)&&Y(e)}function j(e){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(e)}function x(e){return/^\d{3,4}$/.test(e)}function B(e){return/^(0[1-9]|1[0-2])$/.test(e)}function $(e){if(!/^\d{2}$/.test(e))return!1;const t=(new Date).getFullYear()%100;return parseInt(e,10)>=t}const Y=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};function H(e,t,r){const o=t.replace(/\[(\w+)\]/g,".$1").split(".").filter((e=>""!==e));let i=e;for(const e of o){if(null==i)return r;i=i[e]}return void 0===i?r:i}const q="https://cdn.kushkipagos.com/kushki.min.js",z=d.CARD_ON_FILE_DECLINED;let X=!1,Q=null;class W{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=a(r),this.merchantId=e.merchantId,this.apiKey=e.apiKey}initialize(){return t(this,void 0,void 0,(function*(){yield function(){return t(this,void 0,void 0,(function*(){return X?Promise.resolve():Q||(Q=new Promise(((e,t)=>{if(document.querySelector(`script[src="${q}"]`))return X=!0,void e();const r=document.createElement("script");r.src=q,r.async=!0,r.onload=()=>{X=!0,e()},r.onerror=()=>{Q=null,t(y({errorCode:z,lockErrorCode:!0,details:{step:"load_acquirer_script",message:"Failed to load acquirer script"}}))},document.head.appendChild(r)})),Q)}))}(),this.acquirerInstance=function(e,t){if(!window.Kushki)throw y({errorCode:z,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:z,lockErrorCode:!0,details:{step:"get_acquirer_instance",message:"CardOnFile not initialized. Call initialize() first."}});return this.acquirerInstance}getJwt(e){return t(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:z,lockErrorCode:!0,details:{step:"get_jwt",acquirerResponse:e}}));const t=e;t.jwt?r(t.jwt):o(y({errorCode:z,lockErrorCode:!0,details:{step:"get_jwt",message:"No JWT returned from acquirer",acquirerResponse:t}}))}))}))}))}generateToken(e){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}${n.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:z,lockErrorCode:!0,details:{step:"generate_token"}});return t.json()}))}createSubscription(e){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}${n.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:z,lockErrorCode:!0,details:{step:"create_subscription"}});return t.json()}))}validate3DS(e,r){return t(this,void 0,void 0,(function*(){const t=this.getAcquirerInstance();return new Promise(((o,i)=>{t.requestValidate3DS({secureId:e,security:r},(e=>{const t=e;t.code&&"3DS000"!==t.code?i(y({errorCode:z,lockErrorCode:!0,details:{step:"validate_3ds",message:"3DS validation failed",acquirerResponse:t}})):!1!==t.isValid?o(!0):i(y({errorCode:z,lockErrorCode:!0,details:{step:"validate_3ds",message:"3DS validation failed",acquirerResponse:t}}))}))}))}))}process(e){var r,o;return t(this,void 0,void 0,(function*(){const t=yield this.getJwt(e.cardBin),i=yield this.generateToken({card:e.cardTokens,currency:e.currency,jwt:t}),n=i.secureId||(null===(r=i.details)||void 0===r?void 0:r.secureId),s=i.security||(null===(o=i.details)||void 0===o?void 0:o.security);if(!n||!s)throw y({errorCode:z,lockErrorCode:!0,details:{step:"process",message:"Missing secureId or security in token response",tokenResponse:i}});return yield this.validate3DS(n,s),this.createSubscription({token:i.token,contactDetails:e.contactDetails,metadata:{customerId:e.customerId},currency:e.currency})}))}}class J{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 i={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&&(i.tenant_id=t.tenant_id),t.request_id&&(i.request_id=t.request_id),t.process_id&&(i.process_id=t.process_id),t.user_id&&(i.user_id=t.user_id),r.stack&&(i.stack=r.stack),t.error_code&&(i.error_code=t.error_code),t.http_status&&(i.http_status=t.http_status),i}truncate(e,t){return e.length<=t?e:e.substring(0,t)+"..."}sendEvent(e){this.sendHttpRequest(e).then((()=>{})).catch((()=>{}))}sendHttpRequest(e){return t(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 G=Object.freeze({name:"@tonder.io/ionic-lite-sdk",version:"1.0.2"});function Z(e){var t;return e instanceof h&&ee({status:e.statusCode,body:null===(t=e.originalError)||void 0===t?void 0:t.body})}function ee(e){var t,r;return 503===e.status&&"operations_disabled"===(null===(r=null===(t=e.body)||void 0===t?void 0:t.error)||void 0===r?void 0:r.code)}const te=["Success","Authorized","Pending","Processing"],re=["card_number","cvv","expiration_month","expiration_year","cardholder_name"];function oe(e){return void 0!==e&&/^\d+$/.test(e)?Number(e):e}function ie(e,t){return[{name:"verify_transaction_status",url:`${t.coreBaseUrl}/transactions/v1/${e.id}`,method:"GET"},{name:"refund_transaction",url:`${t.coreBaseUrl}/transactions/v1/process`,method:"POST",body:{operation_type:"refund",original_transaction_id:e.id}}]}function ne(e,t){var r,o;const i=e.routing,n=null!==(r=null==i?void 0:i.rejected_psp_responses)&&void 0!==r?r:[],s="Hard"===(null==i?void 0:i.decline_type);return{status:"404",message:s?"Hard decline":null!==(o=e.decline_reason)&&void 0!==o?o:"Transaction declined",checkout_id:null==i?void 0:i.checkout_id,is_route_finished:null==i?void 0:i.is_route_finished,transaction_status:e.status,transaction_id:oe(e.transaction_id),payment_id:e.payment_id,provider:e.provider,decline_code:e.decline_code,psp_response:s?n[n.length-1]:n,actions:ie(e,t)}}function se(e){var t,r;return{status:"200",message:null!==(t=e.decline_reason)&&void 0!==t?t:"High risk transaction blocked",checkout_id:null===(r=e.routing)||void 0===r?void 0:r.checkout_id,transaction_status:"Declined",transaction_id:e.transaction_id,payment_id:e.payment_id,provider:e.provider,amount:e.amount,currency:e.currency,psp_response:e.psp_response,decline_code:e.decline_code}}function ae(e,t){var r,o,i;return{status:"200",message:"Success",checkout_id:null===(r=e.routing)||void 0===r?void 0:r.checkout_id,is_route_finished:null===(o=e.routing)||void 0===o?void 0:o.is_route_finished,transaction_status:e.status,transaction_id:oe(e.transaction_id),payment_id:e.payment_id,provider:e.provider,next_action:null!==(i=e.next_action)&&void 0!==i?i:{},psp_response:e.psp_response,actions:ie(e,t)}}function de(e,t,r,o){var i;if(402===e&&"payment_declined"===(null===(i=null==t?void 0:t.error)||void 0===i?void 0:i.code))return{outcome:"reject",status:404,body:{status:"404",message:"Error",psp_response:[],is_route_finished:!0}};if(e>=400)return{outcome:"reject",status:e,statusText:o,body:le(e,t)};const n=t;return te.includes(n.status)?{outcome:"resolve",status:200,body:ae(n,r)}:"Declined"===n.status&&"FH01"===n.decline_code?{outcome:"resolve",status:200,body:se(n)}:{outcome:"reject",status:404,body:ne(n,r)}}function le(e,t){var r,o;return{status:String(e),message:null!==(o=null===(r=null==t?void 0:t.error)||void 0===r?void 0:r.message)&&void 0!==o?o:"Error",psp_response:[],is_route_finished:!1}}var ce,ue,he,_e,Ee,me,Re,pe,ye,ve,Ce,fe,Ae,Oe,Te,Se;class ge{constructor({mode:e="stage",customization:t,apiKey:r,apiKeyTonder:o,returnUrl:i,tdsIframeId:n,callBack:d=(()=>{}),baseUrlTonder:l,tonderPayButtonId:c,sdkInfo:u}){ce.add(this),this.baseUrl="",this.coreBaseUrl="",this.cartTotal="0",this.secureToken="",this.customization={redirectOnComplete:!0},this.metadata={},this.order_reference=null,this.card={},this.currency="",this.cardOnFileInstance=null,ue.set(this,void 0),he.set(this,void 0),this.apiKeyTonder=o||r||"",this.returnUrl=i,this.callBack=d,this.mode=e,this.customer={},this.baseUrl=l||w[this.mode]||w.stage,this.coreBaseUrl=a(this.mode),this.abortController=new AbortController,this.requestId=this.generateRequestId(),this.customization=Object.assign(Object.assign({},this.customization),t||{}),this.process3ds=new L({apiKey:this.apiKeyTonder,baseUrl:this.baseUrl,coreBaseUrl:this.coreBaseUrl,buildCoreResult:e=>de(200,e,{coreBaseUrl:this.coreBaseUrl}).body,redirectOnComplete:this.customization.redirectOnComplete,tdsIframeId:n,tonderPayButtonId:c,callBack:d}),this.tdsIframeId=n;const h=u||G;this.telemetry=new J({endpoint:s(this.mode),apiKey:this.apiKeyTonder,platform:h.name,platform_version:h.version,mode:this.mode||"stage"})}configureCheckout(e){"secureToken"in e&&r(this,ce,"m",ye).call(this,e.secureToken),r(this,ce,"m",Re).call(this,e)}getCustomerId(){var e,t;return null===(t=null===(e=r(this,he,"f"))||void 0===e?void 0:e.id)||void 0===t?void 0:t.toString()}reportSdkError(e,t){var r,o,i,n;try{const s=this.getCustomerId(),a=e instanceof h&&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===(n=null===(i=null===(o=this.merchantData)||void 0===o?void 0:o.business)||void 0===i?void 0:i.pk)||void 0===n?void 0:n.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 t(this,void 0,void 0,(function*(){const e=this.process3ds.getStoredEngine(),t=yield this.process3ds.verifyTransactionStatus();if("core"===e)return this.process3ds.setPayload(t),t;this.process3ds.setEngine("legacy");const o=yield r(this,ce,"m",Oe).call(this,t);return this.process3ds.setPayload(o),this._handle3dsRedirect(o)}))}payment(e){return new Promise(((o,i)=>t(this,void 0,void 0,(function*(){var t,n;let s;try{r(this,ce,"m",Re).call(this,e),s=yield this._checkout(e),this.process3ds.setPayload(s);if(yield this._handle3dsRedirect(s)){try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}this.callBack&&this.callBack(s),o(s)}}catch(r){this.reportSdkError(r,{feature:"payment",process_id:(null==s?void 0:s.payment_id)||(null===(t=null==s?void 0:s.payment)||void 0===t?void 0:t.id)||(null===(n=null==s?void 0:s.payment)||void 0===n?void 0:n.pk),metadata:{step:"payment",request:e,response:s}}),i(y({errorCode:d.PAYMENT_PROCESS_ERROR},r))}}))))}getSecureToken(e){return t(this,void 0,void 0,(function*(){try{return yield function(e,r,o=null){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${e}/api/secure-token/`,{method:"POST",headers:{Authorization:`Token ${r}`,"Content-Type":"application/json"},signal:o});if(t.ok)return yield t.json();throw yield y({response:t,errorCode:d.SECURE_TOKEN_ERROR})}))}(this.baseUrl,e)}catch(e){throw this.reportSdkError(e,{feature:"secure-token",metadata:{step:"getSecureToken"}}),y({errorCode:d.SECURE_TOKEN_ERROR},e)}}))}_initializeCheckout(){return t(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 t(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 t(this,void 0,void 0,(function*(){return r(this,he,"f")||o(this,he,yield function(e,r,o,i=null){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/customer/`,n={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},s=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${r}`},signal:i,body:JSON.stringify(n)});if(s.ok)return yield s.json();throw yield y({response:s,errorCode:d.CUSTOMER_OPERATION_ERROR})}))}(this.baseUrl,this.apiKeyTonder,this.customer,e),"f"),r(this,he,"f")}))}_handleCheckout(e){var o;return t(this,void 0,void 0,(function*(){if(!0===(null===(o=this.merchantData)||void 0===o?void 0:o.core_payments_enabled)&&r(this,ce,"m",_e).call(this,e)){this.process3ds.setEngine("core");try{return yield r(this,ce,"m",Ee).call(this,e)}catch(e){if(!Z(e))throw e}}return this.process3ds.setEngine("legacy"),r(this,ce,"m",me).call(this,e)}))}_fetchMerchantData(){return t(this,void 0,void 0,(function*(){try{return this.merchantData||(this.merchantData=yield v(this.coreBaseUrl,this.apiKeyTonder,this.abortController.signal)),this.merchantData}catch(e){throw this.reportSdkError(e,{feature:"fetch-merchant-data",metadata:{step:"_fetchMerchantData"}}),y({errorCode:d.FETCH_BUSINESS_ERROR},e)}}))}_getCustomerCards(e,r){return t(this,void 0,void 0,(function*(){return yield function(e,r,o,i,n=null){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/business/${i}/cards/`,s=yield fetch(t,{method:"GET",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":r},signal:n});if(s.ok)return yield s.json();if(401===s.status)return{user_id:0,cards:[]};throw yield y({response:s,errorCode:d.FETCH_CARDS_ERROR})}))}(this.baseUrl,e,this.secureToken,r)}))}_saveCustomerCard(e,r,o,i=!1){return t(this,void 0,void 0,(function*(){return yield function(e,r,o,i,n,s=!1){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/business/${i}/cards/`,a=yield fetch(t,{method:"POST",headers:Object.assign({Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":r},s?{"X-App-Origin":"sdk/ionic"}:{}),body:JSON.stringify(n)});if(a.ok)return yield a.json();throw yield y({response:a,errorCode:d.SAVE_CARD_ERROR})}))}(this.baseUrl,e,this.secureToken,r,o,i)}))}_removeCustomerCard(e,r,o){return t(this,void 0,void 0,(function*(){return yield function(e,r,o,i="",n){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/business/${n}/cards/${i}`,s=yield fetch(t,{method:"DELETE",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":r}});if(204===s.status)return l[d.CARD_REMOVED_SUCCESSFULLY];if(s.ok&&"json"in s)return yield s.json();throw yield y({response:s,errorCode:d.REMOVE_CARD_ERROR})}))}(this.baseUrl,e,this.secureToken,o,r)}))}_fetchCustomerPaymentMethods(){return t(this,void 0,void 0,(function*(){return yield function(e,r,o={status:"active",pagesize:"10000"},i=null){return t(this,void 0,void 0,(function*(){const t=new URLSearchParams(o).toString(),n=yield fetch(`${e}/api/v1/payment_methods?${t}`,{method:"GET",headers:{Authorization:`Token ${r}`,"Content-Type":"application/json"},signal:i});if(n.ok)return yield n.json();throw yield y({response:n,errorCode:d.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 t(this,void 0,void 0,(function*(){return this.cardOnFileInstance||(this.cardOnFileInstance=new W({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 r,o;return t(this,void 0,void 0,(function*(){if(e&&"next_action"in e?null===(o=null===(r=null==e?void 0:e.next_action)||void 0===r?void 0:r.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 Ie(e,r,o=null){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${e}/api/v1/vault-token/`,{method:"GET",headers:{Authorization:`Token ${r}`},signal:o});if(t.ok){return(yield t.json()).token}throw yield y({response:t,errorCode:d.VAULT_TOKEN_ERROR})}))}ue=new WeakMap,he=new WeakMap,ce=new WeakSet,_e=function({card:e,payment_method:t}){return!!e&&S(t)},Ee=function({card:e,returnUrl:r}){return t(this,void 0,void 0,(function*(){const{reference:o}=this.merchantData;let i,s;try{i=function(e){const{card:t,customer:r}=e,o=[H(r,"firstName",H(r,"name","")),H(r,"lastName",H(r,"lastname",""))].filter(Boolean).join(" "),i=t.card_number?Object.assign({type:"CARD"},Object.fromEntries(re.map((e=>[e,t[e]])))):{type:"CARD",token:t.skyflow_id};return{operation_type:"payment",amount:e.amount,currency:e.currency,client_reference:String(e.reference),customer:{name:o,email:H(r,"email",""),phone:H(r,"phone",void 0),identification:H(r,"identification",void 0)},payment_method:i,metadata:e.metadata,return_url:e.returnUrl,items:e.items,browser_info:e.browserInfo}}({amount:Number(this.cartTotal),currency:this.currency,reference:this.order_reference?this.order_reference:o,customer:this.customer,card:e,metadata:this.metadata,returnUrl:r||this.returnUrl,items:this.cartItems,browserInfo:O()});const h=yield function(e,r,o,i){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${e}${n.CORE_PROCESS}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${r}`,"X-App-Origin":"sdk/ionic","X-Request-Id":i},body:JSON.stringify(o)}),s=t.ok?yield t.json():yield t.json().catch((()=>{}));return{status:t.status,statusText:t.statusText,body:s}}))}(this.coreBaseUrl,this.apiKeyTonder,i,function(){const e=globalThis.crypto;return"function"==typeof(null==e?void 0:e.randomUUID)?e.randomUUID():`req_${Date.now()}_${Math.random().toString(36).slice(2,12)}`}());if(h.status>=400&&(a=h.status,l=h.body,s={status:a,code:null===(c=null==l?void 0:l.error)||void 0===c?void 0:c.code,type:null===(u=null==l?void 0:l.error)||void 0===u?void 0:u.type,request_id:null==l?void 0:l.request_id}),ee(h))throw p({errorCode:d.START_CHECKOUT_ERROR,status:h.status,body:h.body});const _=de(h.status,h.body,{coreBaseUrl:this.coreBaseUrl},h.statusText);if("resolve"===_.outcome)return _.body;throw p({errorCode:d.START_CHECKOUT_ERROR,status:_.status,statusText:_.statusText,body:_.body})}catch(e){throw Z(e)||this.reportSdkError(e,{feature:"payment",metadata:{step:"_handleCheckout",payment:i,core_error:s}}),e}var a,l,c,u}))},me=function({card:e,payment_method:o,customer:i,isSandbox:n,enable_card_on_file:s,returnUrl:a}){return t(this,void 0,void 0,(function*(){const{openpay_keys:l,reference:c,business:u}=this.merchantData,h=Number(this.cartTotal);let _,E,m;try{let R;!R&&l.merchant_id&&l.public_key&&!o&&(R=yield F(l.merchant_id,l.public_key,n,this.abortController.signal));const{id:p,auth_token:v}=i;_={business:this.apiKeyTonder,client:v,billing_address_id:null,shipping_address_id:null,amount:h,status:"A",reference:c,is_oneclick:!0,items:this.cartItems,currency:this.currency,metadata:this.metadata};const C=yield function(e,r,o){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/orders/`,i=o,n=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${r}`},body:JSON.stringify(i)});if(n.ok)return yield n.json();throw yield y({response:n,errorCode:d.CREATE_ORDER_ERROR})}))}(this.baseUrl,this.apiKeyTonder,_),f=(new Date).toISOString();E={business_pk:u.pk,client_id:p,amount:h,date:f,order_id:C.id,customer_order_reference:this.order_reference?this.order_reference:c,items:this.cartItems,currency:this.currency,metadata:this.metadata};const A=yield function(e,r,o){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/business/${o.business_pk}/payments/`,i=o,n=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${r}`},body:JSON.stringify(i)});if(n.ok)return yield n.json();throw yield y({response:n,errorCode:d.CREATE_PAYMENT_ERROR})}))}(this.baseUrl,this.apiKeyTonder,E);m=Object.assign(Object.assign(Object.assign(Object.assign({name:H(this.customer,"firstName",H(this.customer,"name","")),last_name:H(this.customer,"lastName",H(this.customer,"lastname","")),email_client:H(this.customer,"email",""),phone_number:H(this.customer,"phone",""),return_url:a||this.returnUrl,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:h,title_ship:"shipping",description:"transaction",device_session_id:R||null,token_id:"",order_id:C.id,business_id:u.pk,payment_id:A.pk,source:"sdk",items:this.cartItems,metadata:this.metadata,browser_info:O(),currency:this.currency},o?{payment_method:o}:{card:e}),{apm_config:r(this,ue,"f")}),this.customer&&"identification"in this.customer?{identification:this.customer.identification}:{}),void 0!==s?{enable_card_on_file:s}:{});const T=yield V(this.baseUrl,this.apiKeyTonder,m);return T||!1}catch(e){throw this.reportSdkError(e,{feature:"payment",process_id:null==m?void 0:m.payment_id,metadata:{step:"_handleCheckout",orderItems:_,paymentItems:E,routerItems:m}}),e}}))},Re=function(e){var t,o;!e||e&&0===Object.keys(e).length||(r(this,ce,"m",pe).call(this,e.customer),this._setCartTotal((null===(t=e.cart)||void 0===t?void 0:t.total)||0),r(this,ce,"m",ve).call(this,(null===(o=e.cart)||void 0===o?void 0:o.items)||[]),r(this,ce,"m",Ce).call(this,e),r(this,ce,"m",fe).call(this,e),r(this,ce,"m",Ae).call(this,e),r(this,ce,"m",Te).call(this,e))},pe=function(e){e&&(this.customer=e)},ye=function(e){if("string"!=typeof(t=e)||!/^[\x21-\x7E]+$/.test(t))throw y({errorCode:d.SECURE_TOKEN_INVALID,statusCode:400});var t;this.secureToken=e},ve=function(e){this.cartItems=e},Ce=function(e){this.metadata=null==e?void 0:e.metadata,this.order_reference=null==e?void 0:e.order_reference},fe=function(e){this.currency=null==e?void 0:e.currency},Ae=function(e){this.card=null==e?void 0:e.card},Oe=function(e){var r,o,i,n,s;return t(this,void 0,void 0,(function*(){if("Hard"===(null===(r=null==e?void 0:e.decline)||void 0===r?void 0:r.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===(i=e.checkout)||void 0===i?void 0:i.id)||(null==e?void 0:e.checkout_id)};try{return yield V(this.baseUrl,this.apiKeyTonder,t)}catch(t){this.reportSdkError(t,{feature:"payment",process_id:(null==e?void 0:e.payment_id)||(null===(n=null==e?void 0:e.payment)||void 0===n?void 0:n.id)||(null===(s=null==e?void 0:e.payment)||void 0===s?void 0:s.pk),metadata:{step:"#resumeCheckout",response:e}})}return e}}))},Te=function(e){o(this,ue,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"}(Se||(Se={}));const Ne={type:e.ValidationRuleType.LENGTH_MATCH_RULE,params:{max:70}},be=RegExp("^(?!s*$).+"),De={type:e.ValidationRuleType.REGEX_MATCH_RULE,params:{regex:be,error:"El campo es requerido"}},ke="Titular de la tarjeta",Me="Número de tarjeta",Pe="CVC/CVV",Ue="Mes",Le="Año",we="Fecha de expiración",Ve="Nombre como aparece en la tarjeta",Fe="1234 1234 1234 1234",Ke="3-4 dígitos",je="MM",xe="AA",Be={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")'}},$e={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif'}},Ye={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif',color:"#f44336"}};function He({baseUrl:r,apiKey:o,vault_id:i,vault_url:n,data:s}){return t(this,void 0,void 0,(function*(){const a=e.init({vaultID:i,vaultURL:n,getBearerToken:()=>t(this,void 0,void 0,(function*(){return yield Ie(r,o)})),options:{logLevel:e.LogLevel.ERROR,env:e.Env.DEV}}).container(e.ContainerType.COLLECT),l=yield function(r,o){return t(this,void 0,void 0,(function*(){const i=yield function(r,o){return t(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(r).map((r=>t(this,void 0,void 0,(function*(){return{element:yield o.create({table:"cards",column:r,type:e.ElementType.INPUT_FIELD}),key:r}})))))}))}(r,o);return i?i.map((e=>new Promise((t=>{var o;const i=document.createElement("div");i.hidden=!0,i.id=`id-${e.key}`,null===(o=document.querySelector("body"))||void 0===o||o.appendChild(i),setTimeout((()=>{e.element.mount(`#id-${e.key}`),setInterval((()=>{if(e.element.isMounted()){const o=r[e.key];return e.element.setValue(o),t(e.element.isMounted())}}),120)}),120)})))):[]}))}(s,a);if((yield Promise.all(l)).some((e=>!e)))throw y({errorCode:d.SAVE_CARD_PROCESS_ERROR,details:{step:"get_skyflow_tokens"}});try{const e=yield a.collect();if(e)return e.records[0].fields;throw y({errorCode:d.SAVE_CARD_PROCESS_ERROR,details:{step:"get_skyflow_tokens"}})}catch(e){throw y({errorCode:d.SAVE_CARD_PROCESS_ERROR},e)}}))}function qe(t){const{element:r,fieldMessage:o="",errorStyles:i={},requiredMessage:n="Campo requerido",invalidMessage:s="Campo no válido",events:a}=t;"on"in r&&(r.on(e.EventName.CHANGE,(e=>{Xe({eventName:"onChange",data:e,events:a}),ze({element:r,errorStyles:i,color:"transparent"})})),r.on(e.EventName.BLUR,(e=>{if(Xe({eventName:"onBlur",data:e,events:a}),!e.isValid){const t=e.isEmpty?n:""!=o?`El campo ${o} no es válido`:s;r.setError(t)}ze({element:r,errorStyles:i})})),r.on(e.EventName.FOCUS,(e=>{Xe({eventName:"onFocus",data:e,events:a}),ze({element:r,errorStyles:i,color:"transparent"}),r.resetError()})))}function ze(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 Xe=e=>{const{eventName:t,data:r,events:o}=e;if(o&&t in o){const e=o[t];"function"==typeof e&&e({elementType:H(r,"elementType",""),isEmpty:H(r,"isEmpty",!1),isFocused:H(r,"isFocused",!1),isValid:H(r,"isValid",!1),value:H(r,"value","")})}};function Qe(e){return t(this,void 0,void 0,(function*(){const{element:t,containerId:r,retries:o=2,delay:i=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,i))))}console.warn(`[mountCardFields] Container ${r} was not found after ${o+1} attempts`)}))}const We=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"}),Je={[We.SORIANA]:{label:"Soriana",iconPath:"/payment_methods/soriana.png"},[We.OXXO]:{label:"Oxxo",iconPath:"/payment_methods/oxxo.png"},[We.CODI]:{label:"CoDi",iconPath:"/payment_methods/codi.png"},[We.MERCADOPAGO]:{label:"Mercado Pago",iconPath:"/payment_methods/mercadopago.png"},[We.OXXOPAY]:{label:"Oxxo Pay",iconPath:"/payment_methods/oxxopay.png"},[We.SPEI]:{label:"SPEI",iconPath:"/payment_methods/spei.png"},[We.PAYPAL]:{label:"Paypal",iconPath:"/payment_methods/paypal.png"},[We.COMERCIALMEXICANA]:{label:"Comercial Mexicana",iconPath:"/payment_methods/comercial_exicana.png"},[We.BANCOMER]:{label:"Bancomer",iconPath:"/payment_methods/bancomer.png"},[We.WALMART]:{label:"Walmart",iconPath:"/payment_methods/walmart.png"},[We.BODEGA]:{label:"Bodega Aurrera",iconPath:"/payment_methods/bodega_aurrera.png"},[We.SAMSCLUB]:{label:"Sam´s Club",iconPath:"/payment_methods/sams_club.png"},[We.SUPERAMA]:{label:"Superama",iconPath:"/payment_methods/superama.png"},[We.CALIMAX]:{label:"Calimax",iconPath:"/payment_methods/calimax.png"},[We.EXTRA]:{label:"Tiendas Extra",iconPath:"/payment_methods/tiendas_extra.png"},[We.CIRCULOK]:{label:"Círculo K",iconPath:"/payment_methods/circulo_k.png"},[We.SEVEN11]:{label:"7 Eleven",iconPath:"/payment_methods/7_eleven.png"},[We.TELECOMM]:{label:"Telecomm",iconPath:"/payment_methods/telecomm.png"},[We.BANORTE]:{label:"Banorte",iconPath:"/payment_methods/banorte.png"},[We.BENAVIDES]:{label:"Farmacias Benavides",iconPath:"/payment_methods/farmacias_benavides.png"},[We.DELAHORRO]:{label:"Farmacias del Ahorro",iconPath:"/payment_methods/farmacias_ahorro.png"},[We.ELASTURIANO]:{label:"El Asturiano",iconPath:"/payment_methods/asturiano.png"},[We.WALDOS]:{label:"Waldos",iconPath:"/payment_methods/waldos.png"},[We.ALSUPER]:{label:"Alsuper",iconPath:"/payment_methods/al_super.png"},[We.KIOSKO]:{label:"Kiosko",iconPath:"/payment_methods/kiosko.png"},[We.STAMARIA]:{label:"Farmacias Santa María",iconPath:"/payment_methods/farmacias_santa_maria.png"},[We.LAMASBARATA]:{label:"Farmacias la más barata",iconPath:"/payment_methods/farmacias_barata.png"},[We.FARMROMA]:{label:"Farmacias Roma",iconPath:"/payment_methods/farmacias_roma.png"},[We.FARMUNION]:{label:"Pago en Farmacias Unión",iconPath:"/payment_methods/farmacias_union.png"},[We.FARMATODO]:{label:"Pago en Farmacias Farmatodo",iconPath:"/payment_methods/farmacias_farmatodo.png\t"},[We.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",iconPath:"/payment_methods/farmacias_san_francisco.png"},[We.FARM911]:{label:"Farmacias 911",iconPath:"/payment_methods/store.png"},[We.FARMECONOMICAS]:{label:"Farmacias Economicas",iconPath:"/payment_methods/store.png"},[We.FARMMEDICITY]:{label:"Farmacias Medicity",iconPath:"/payment_methods/store.png"},[We.RIANXEIRA]:{label:"Rianxeira",iconPath:"/payment_methods/store.png"},[We.WESTERNUNION]:{label:"Western Union",iconPath:"/payment_methods/store.png"},[We.ZONAPAGO]:{label:"Zona Pago",iconPath:"/payment_methods/store.png"},[We.CAJALOSANDES]:{label:"Caja Los Andes",iconPath:"/payment_methods/store.png"},[We.CAJAPAITA]:{label:"Caja Paita",iconPath:"/payment_methods/store.png"},[We.CAJASANTA]:{label:"Caja Santa",iconPath:"/payment_methods/store.png"},[We.CAJASULLANA]:{label:"Caja Sullana",iconPath:"/payment_methods/store.png"},[We.CAJATRUJILLO]:{label:"Caja Trujillo",iconPath:"/payment_methods/store.png"},[We.EDPYME]:{label:"Edpyme",iconPath:"/payment_methods/store.png"},[We.KASNET]:{label:"KasNet",iconPath:"/payment_methods/store.png"},[We.NORANDINO]:{label:"Norandino",iconPath:"/payment_methods/store.png"},[We.QAPAQ]:{label:"Qapaq",iconPath:"/payment_methods/store.png"},[We.RAIZ]:{label:"Raiz",iconPath:"/payment_methods/store.png"},[We.PAYSER]:{label:"Paysera",iconPath:"/payment_methods/store.png"},[We.WUNION]:{label:"Western Union",iconPath:"/payment_methods/store.png"},[We.BANCOCONTINENTAL]:{label:"Banco Continental",iconPath:"/payment_methods/store.png"},[We.GMONEY]:{label:"Go money",iconPath:"/payment_methods/store.png"},[We.GOPAY]:{label:"Go pay",iconPath:"/payment_methods/store.png"},[We.WU]:{label:"Western Union",iconPath:"/payment_methods/store.png"},[We.PUNTOSHEY]:{label:"Puntoshey",iconPath:"/payment_methods/store.png"},[We.AMPM]:{label:"Ampm",iconPath:"/payment_methods/store.png"},[We.JUMBOMARKET]:{label:"Jumbomarket",iconPath:"/payment_methods/store.png"},[We.SMELPUEBLO]:{label:"Smelpueblo",iconPath:"/payment_methods/store.png"},[We.BAM]:{label:"Bam",iconPath:"/payment_methods/store.png"},[We.REFACIL]:{label:"Refacil",iconPath:"/payment_methods/store.png"},[We.ACYVALORES]:{label:"Acyvalores",iconPath:"/payment_methods/store.png"}},Ge=(e,t="stage")=>{const r=e.toUpperCase().trim().replace(/\s+/g,"");const o=Je[r]||{iconPath:"/payment_methods/store.png",label:""};return{label:o.label,icon:`${A(t)}${o.iconPath}`}};class Ze extends ge{constructor({apiKey:e,mode:t,returnUrl:r,callBack:o,apiKeyTonder:i,baseUrlTonder:n,customization:s,collectorIds:a,events:d}){super({mode:t,apiKey:e,returnUrl:r,callBack:o,apiKeyTonder:i,baseUrlTonder:n,customization:s,tdsIframeId:a&&"tdsIframe"in a?null==a?void 0:a.tdsIframe:"tdsIframe",sdkInfo:G}),this.activeAPMs=[],this.mountedElementsByContext=new Map,this.customerCardsCache=null,this.lastCollectedTokens=null,this.skyflowInstance=null,this.events=d||{}}injectCheckout(){return t(this,void 0,void 0,(function*(){yield this._initializeCheckout()}))}getCustomerCards(){return t(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=>Object.assign(Object.assign({},e),{fields:Object.assign(Object.assign({},e.fields),{subscription_id:this._hasCardOnFileKeys()?e.fields.subscription_id:void 0}),icon:g(e.fields.card_scheme,this.mode)})))})}catch(e){throw this.reportSdkError(e,{feature:"get-cards",process_id:this.getCustomerId(),metadata:{step:"getCustomerCards"}}),y({errorCode:d.FETCH_CARDS_ERROR},e)}}))}saveCustomerCard(){return t(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:i="",email:n=""}=t,{business:s}=this.merchantData,a=this._hasCardOnFileKeys(),l=yield this.collectCreateCardTokens(),c=yield this._saveCustomerCard(r,null==s?void 0:s.pk,l,a);if(e=c.skyflow_id,a){const e=c.card_bin;if(!e)throw new Error("Card BIN not returned from save card");const t=yield this._initializeCardOnFile();let a;try{a=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:i||"",email:n||""},customerId:r,currency:this.currency||"MXN"})}catch(e){throw y({errorCode:d.CARD_ON_FILE_DECLINED,lockErrorCode:!0},e)}const u={skyflow_id:l.skyflow_id,subscription_id:a.subscriptionId};yield this._saveCustomerCard(r,null==s?void 0:s.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:d.SAVE_CARD_ERROR},t)}}))}removeCustomerCard(e){return t(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:d.REMOVE_CARD_ERROR},t)}}))}getCustomerPaymentMethods(){return t(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},Ge(e.payment_method,this.mode)))).sort(((e,t)=>e.priority-t.priority))}catch(e){throw this.reportSdkError(e,{feature:"get-payment-methods",metadata:{step:"getCustomerPaymentMethods"}}),y({errorCode:d.FETCH_PAYMENT_METHODS_ERROR},e)}}))}mountCardFields(r){var o;return t(this,void 0,void 0,(function*(){const i=r.card_id?`update:${r.card_id}`:"create",n=null!==(o=r.unmount_context)&&void 0!==o?o:"all";"none"!==n&&("current"===n?this.unmountCardFields(i):this.unmountCardFields(n)),yield this.createSkyflowInstance();const s=yield function(r){var o,i,n,s,a,d,l,c,u,h,_,E,m;return t(this,void 0,void 0,(function*(){const{skyflowInstance:t,data:R,customization:p,events:y}=r,v=t.container(e.ContainerType.COLLECT),C=[],f={[Se.CVV]:e.ElementType.CVV,[Se.CARD_NUMBER]:e.ElementType.CARD_NUMBER,[Se.EXPIRATION_MONTH]:e.ElementType.EXPIRATION_MONTH,[Se.EXPIRATION_YEAR]:e.ElementType.EXPIRATION_YEAR,[Se.CARDHOLDER_NAME]:e.ElementType.CARDHOLDER_NAME},A={[Se.CVV]:[De],[Se.CARD_NUMBER]:[De],[Se.EXPIRATION_MONTH]:[De],[Se.EXPIRATION_YEAR]:[De],[Se.CARDHOLDER_NAME]:[Ne,De]},O={[Se.CARDHOLDER_NAME]:"cardholderName",[Se.CARD_NUMBER]:"cardNumber",[Se.CVV]:"cvv",[Se.EXPIRATION_MONTH]:"expirationMonth",[Se.EXPIRATION_YEAR]:"expirationYear"},T=e=>{var t,r,o,i,n,s,a,d,l;const c=null===(t=null==p?void 0:p.styles)||void 0===t?void 0:t[O[e]],u=null===(r=null==p?void 0:p.styles)||void 0===r?void 0:r.cardForm,h=null!==(i=null!==(o=null==c?void 0:c.inputStyles)&&void 0!==o?o:null==u?void 0:u.inputStyles)&&void 0!==i?i:Be;return{inputStyles:e===Se.CARD_NUMBER&&!1!==(null===(n=null==p?void 0:p.styles)||void 0===n?void 0:n.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:$e,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:Ye}},S={cardholder_name:(null===(o=null==p?void 0:p.labels)||void 0===o?void 0:o.name)||ke,card_number:(null===(i=null==p?void 0:p.labels)||void 0===i?void 0:i.card_number)||Me,cvv:(null===(n=null==p?void 0:p.labels)||void 0===n?void 0:n.cvv)||Pe,expiration_date:(null===(s=null==p?void 0:p.labels)||void 0===s?void 0:s.expiry_date)||we,expiration_month:(null===(a=null==p?void 0:p.labels)||void 0===a?void 0:a.expiration_month)||Ue,expiration_year:(null===(d=null==p?void 0:p.labels)||void 0===d?void 0:d.expiration_year)||Le},g={cardholder_name:(null===(l=null==p?void 0:p.placeholders)||void 0===l?void 0:l.name)||Ve,card_number:(null===(c=null==p?void 0:p.placeholders)||void 0===c?void 0:c.card_number)||Fe,cvv:(null===(u=null==p?void 0:p.placeholders)||void 0===u?void 0:u.cvv)||Ke,expiration_month:(null===(h=null==p?void 0:p.placeholders)||void 0===h?void 0:h.expiration_month)||je,expiration_year:(null===(_=null==p?void 0:p.placeholders)||void 0===_?void 0:_.expiration_year)||xe},I={[Se.CVV]:null==y?void 0:y.cvvEvents,[Se.CARD_NUMBER]:null==y?void 0:y.cardNumberEvents,[Se.EXPIRATION_MONTH]:null==y?void 0:y.monthEvents,[Se.EXPIRATION_YEAR]:null==y?void 0:y.yearEvents,[Se.CARDHOLDER_NAME]:null==y?void 0:y.cardHolderEvents};if("fields"in R&&Array.isArray(R.fields)){const e={enableCardIcon:null===(m=null===(E=null==p?void 0:p.styles)||void 0===E?void 0:E.enableCardIcon)||void 0===m||m};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:f[t],validations:A[t]},T(t)),{label:S[t],placeholder:g[t]}),R.card_id?{skyflowID:R.card_id}:{}),t===Se.CARD_NUMBER?e:void 0);qe({element:r,errorStyles:T(t).errorStyles,fieldMessage:[Se.CVV,Se.EXPIRATION_MONTH,Se.EXPIRATION_YEAR].includes(t)?"":S[t],events:I[t]});const o=`#collect_${String(t)}`+(R.card_id?`_${R.card_id}`:"");yield Qe({element:r,containerId:o}),C.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:f[r],validations:A[r]},T(r)),{label:S[r],placeholder:g[r]}),R.card_id?{skyflowID:R.card_id}:{}),r===Se.CARD_NUMBER?e:void 0);qe({element:o,errorStyles:T(r).errorStyles,fieldMessage:[Se.CVV,Se.EXPIRATION_MONTH,Se.EXPIRATION_YEAR].includes(r)?"":S[r],events:I[r]});const i=t.container_id||`#collect_${String(r)}`+(R.card_id?`_${R.card_id}`:"");yield Qe({element:o,containerId:i}),C.push({element:o,containerId:i})}}return{elements:C.map((e=>e.element)),container:v}}))}({skyflowInstance:this.skyflowInstance,data:r,customization:this.customization,events:this.events});this.mountedElementsByContext.set(i,{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 r,o,i;return t(this,void 0,void 0,(function*(){const t=this.getContainerByCardId(e);if(!t)return null;try{const e=yield t.collect();return(null===(o=null===(r=null==e?void 0:e.records)||void 0===r?void 0:r[0])||void 0===o?void 0:o.fields)||null}catch(t){const r=null===(i=null==t?void 0:t.error)||void 0===i?void 0:i.description;throw this.reportSdkError(t,{feature:"collect-card-tokens",process_id:e,metadata:{step:"collectCardTokens"}}),new C({code:d.MOUNT_COLLECT_ERROR,details:{message:r}})}}))}collectCreateCardTokens(){var e,r,o,i;return t(this,void 0,void 0,(function*(){const t=this.mountedElementsByContext.get("create"),n=null===(e=null==t?void 0:t.container)||void 0===e?void 0:e.container;if(!n)throw new C({code:d.MOUNT_COLLECT_ERROR,details:{message:"No card fields are mounted. Call mountCardFields() with the required fields before proceeding."}});try{const e=yield n.collect(),t=(null===(o=null===(r=null==e?void 0:e.records)||void 0===r?void 0:r[0])||void 0===o?void 0:o.fields)||{};return this.lastCollectedTokens=t,t}catch(e){const t=null===(i=null==e?void 0:e.error)||void 0===i?void 0:i.description;throw this.reportSdkError(e,{feature:"collect-create-card-tokens",metadata:{step:"collectCreateCardTokens"}}),new C({code:d.MOUNT_COLLECT_ERROR,details:{message:t}})}}))}revealCardFields(r){return t(this,void 0,void 0,(function*(){if(!this.lastCollectedTokens)throw y({errorCode:d.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:d.MOUNT_COLLECT_ERROR,details:{message:"Skyflow instance not initialized. Ensure mountCardFields() was called before saveCustomerCard() or payment()."}});yield function(r){var o,i,n,s,a,d;return t(this,void 0,void 0,(function*(){const{skyflowInstance:t,tokens:l,request:c}=r,u=t.container(e.ContainerType.REVEAL),h={[Se.CARD_NUMBER]:"MASKED",[Se.CARDHOLDER_NAME]:"PLAIN_TEXT",[Se.EXPIRATION_MONTH]:"PLAIN_TEXT",[Se.EXPIRATION_YEAR]:"PLAIN_TEXT"};for(const t of c.fields){const r="string"==typeof t,_=r?t:t.field;if(_===Se.CVV){console.warn("[revealCardFields] CVV cannot be revealed (PCI DSS req. 3.2.1). Skipping.");continue}const E=l[_];if(!E){console.warn(`[revealCardFields] No token found for field "${_}", skipping.`);continue}const m=r?{}:t,R=null!==(o=m.container_id)&&void 0!==o?o:`#reveal_${_}`,p=h[_],y=null!==(i=m.styles)&&void 0!==i?i:{},v=null!==(n=c.styles)&&void 0!==n?n:{},C=u.create(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({token:E,redaction:e.RedactionType[p]},void 0!==m.altText&&{altText:m.altText}),void 0!==m.label&&{label:m.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 Qe({element:C,containerId:R})}try{yield u.reveal()}catch(e){console.warn("[revealCardFields] reveal completed with errors:",e)}}))}({skyflowInstance:this.skyflowInstance,tokens:this.lastCollectedTokens,request:r})}))}unmountCardFields(e="all"){"all"===e?(this.mountedElementsByContext.forEach(((e,t)=>{this.unmountContext(t)})),this.mountedElementsByContext.clear()):(this.unmountContext(e),this.mountedElementsByContext.delete(e))}unmountContext(e){const t=this.mountedElementsByContext.get(e);if(!t)return;const{elements:r}=t;r&&r.length>0&&r.forEach((t=>{try{t&&"function"==typeof t.unmount&&t.unmount()}catch(t){console.warn(`Error unmounting Skyflow element from context '${e}':`,t),this.reportSdkError(t,{feature:"unmount-card-fields",metadata:{step:"unmountContext",context:e}})}}))}getBusiness(){return t(this,void 0,void 0,(function*(){try{return yield v(this.coreBaseUrl,this.apiKeyTonder,this.abortController.signal)}catch(e){throw this.reportSdkError(e,{feature:"get-business",metadata:{step:"getBusiness"}}),y({errorCode:d.FETCH_BUSINESS_ERROR},e)}}))}createSkyflowInstance(){return t(this,void 0,void 0,(function*(){if(this.skyflowInstance)return this.skyflowInstance;yield this._fetchMerchantData();const{vault_id:r,vault_url:o}=this.merchantData;this.skyflowInstance=yield function({baseUrl:r,apiKey:o,vault_id:i,vault_url:n,mode:s}){return t(this,void 0,void 0,(function*(){const a="production"===s?e.Env.PROD:e.Env.DEV;return e.init({vaultID:i,vaultURL:n,getBearerToken:()=>t(this,void 0,void 0,(function*(){return yield Ie(r,o)})),options:{logLevel:e.LogLevel.ERROR,env:a}})}))}({vault_id:r,vault_url:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder,mode:this.mode})}))}getOpenpayDeviceSessionID(e,r,o){return t(this,void 0,void 0,(function*(){try{return yield F(e,r,o)}catch(e){throw this.reportSdkError(e,{feature:"get-openpay-device-session",metadata:{step:"getOpenpayDeviceSessionID"}}),y({errorCode:d.START_CHECKOUT_ERROR},e)}}))}getSkyflowTokens({vault_id:e,vault_url:r,data:o}){return t(this,void 0,void 0,(function*(){return yield He({vault_id:e,vault_url:r,data:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}_setCartTotal(e){this.cartTotal=e}_checkout({card:e,payment_method:r,isSandbox:o,returnUrl:i}){var n,s,a;return t(this,void 0,void 0,(function*(){yield this._fetchMerchantData();const l=!0===(null===(n=this.merchantData)||void 0===n?void 0:n.core_payments_enabled)&&S(r)?void 0:r,c=yield this._getCustomer(this.abortController.signal),{business:u}=this.merchantData,{auth_token:h,first_name:_="",last_name:E="",email:m=""}=c,R=this._hasCardOnFileKeys();let p,v=null,C=null,f=null,A=!1;const O=()=>t(this,void 0,void 0,(function*(){var e,t;(null===(t=null===(e=this.customerCardsCache)||void 0===e?void 0:e.cards)||void 0===t?void 0:t.length)||(this.customerCardsCache=yield this._getCustomerCards(h,this.merchantData.business.pk))}));if(!l){if("string"==typeof e)if(C=e,p={skyflow_id:e},R){yield O();const t=null===(a=null===(s=this.customerCardsCache)||void 0===s?void 0:s.cards)||void 0===a?void 0:a.find((t=>t.fields.skyflow_id===e));if(!t)throw new Error("Card not found for card-on-file processing");const r=!!t.fields.subscription_id;r||(yield this.collectCardTokens(e)),r&&(v={subscriptionId:t.fields.subscription_id})}else yield this.collectCardTokens(e);else p=yield this.collectCreateCardTokens(),C=p.skyflow_id,R&&(f={name:p.cardholder_name,number:p.card_number,expiryMonth:p.expiration_month,expiryYear:p.expiration_year,cvv:p.cvv},A=!0);if(A){if(!C||!f)throw new Error("Missing card data for card-on-file processing");let e=null;try{const t=yield this._saveCustomerCard(h,null==u?void 0:u.pk,{skyflow_id:C},!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 i;try{i=yield o.process({cardTokens:f,cardBin:r,contactDetails:{firstName:_||"",lastName:E||"",email:m||""},customerId:h,currency:this.currency||"MXN"})}catch(e){throw y({errorCode:d.CARD_ON_FILE_DECLINED,lockErrorCode:!0},e)}v={subscriptionId:i.subscriptionId},yield this._saveCustomerCard(h,null==u?void 0:u.pk,{skyflow_id:C,subscription_id:v.subscriptionId})}catch(t){throw e&&(yield this.removeCustomerCard(e)),this.reportSdkError(t,{feature:"payment",process_id:e||this.getCustomerId(),metadata:{step:"card_on_file"}}),t}}}return yield this._handleCheckout({card:p,payment_method:l,customer:c,isSandbox:o,returnUrl:i,enable_card_on_file:!!(null==v?void 0:v.subscriptionId)&&R})}))}customerRegister(e){return t(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:d.CUSTOMER_OPERATION_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"customer-register",metadata:{step:"customerRegister"}}),y({errorCode:d.CUSTOMER_OPERATION_ERROR},e)}}))}createOrder(e){return t(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:d.CREATE_ORDER_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"create-order",metadata:{step:"createOrder"}}),y({errorCode:d.CREATE_ORDER_ERROR},e)}}))}createPayment(e){return t(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:d.CREATE_PAYMENT_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"create-payment",metadata:{step:"createPayment"}}),y({errorCode:d.CREATE_PAYMENT_ERROR},e)}}))}startCheckoutRouter(e){return t(this,void 0,void 0,(function*(){const t=yield V(this.baseUrl,this.apiKeyTonder,e);if(yield this.init3DSRedirect(t))return t}))}init3DSRedirect(e){return t(this,void 0,void 0,(function*(){return this.process3ds.setPayload(e),yield this._handle3dsRedirect(e)}))}startCheckoutRouterFull(e){return t(this,void 0,void 0,(function*(){try{const{order:t,total:r,customer:o,skyflowTokens:i,return_url:n,isSandbox:s,metadata:a,currency:l,payment_method:c}=e,u=yield this._fetchMerchantData(),h=yield this.customerRegister(o.email);if(!(h&&"auth_token"in h&&u&&"reference"in u))throw y({errorCode:d.START_CHECKOUT_ERROR,details:{message:"Merchant or customer reposne errors",merchantResult:u,customerResult:h}});{const e={business:this.apiKeyTonder,client:h.auth_token,billing_address_id:null,shipping_address_id:null,amount:r,reference:u.reference,is_oneclick:!0,items:t.items},_=yield this.createOrder(e),E=(new Date).toISOString();if(!("id"in _&&"id"in h&&"business"in u))throw y({errorCode:d.START_CHECKOUT_ERROR,details:{message:"Order response errors",orderResult:_}});{const e={business_pk:u.business.pk,amount:r,date:E,order_id:_.id,client_id:h.id},t=yield this.createPayment(e);let d;const{openpay_keys:m,business:R}=u;m.merchant_id&&m.public_key&&(d=yield F(m.merchant_id,m.public_key,s));const p=Object.assign(Object.assign({name:o.name,last_name:o.lastname,email_client:o.email,phone_number:o.phone,return_url:n,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:r,title_ship:"shipping",description:"transaction",device_session_id:d||null,token_id:"",order_id:"id"in _&&_.id,business_id:R.pk,payment_id:"pk"in t&&t.pk,source:"sdk",metadata:a,browser_info:O(),currency:l},c?{payment_method:c}:{card:i}),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}),y=yield V(this.baseUrl,this.apiKeyTonder,p);if(yield this.init3DSRedirect(y))return y}}}catch(e){throw this.reportSdkError(e,{feature:"start-checkout-router-full",metadata:{step:"startCheckoutRouterFull"}}),y({errorCode:d.START_CHECKOUT_ERROR},e)}}))}registerCustomerCard(e,r,o){return t(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const t=yield fetch(`${this.baseUrl}/api/v1/business/${T(this.merchantData)}/cards/`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"User-token":r,"Content-Type":"application/json"},body:JSON.stringify(Object.assign({},o))});if(t.ok)return yield t.json();throw yield y({response:t,errorCode:d.SAVE_CARD_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"register-customer-card",metadata:{step:"registerCustomerCard"}}),y({errorCode:d.SAVE_CARD_ERROR},e)}}))}deleteCustomerCard(e,r=""){return t(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const t=yield fetch(`${this.baseUrl}/api/v1/business/${T(this.merchantData)}/cards/${r}`,{method:"DELETE",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.abortController.signal});if(t.ok)return!0;throw yield y({response:t,errorCode:d.REMOVE_CARD_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"delete-customer-card",process_id:r,metadata:{step:"deleteCustomerCard"}}),y({errorCode:d.REMOVE_CARD_ERROR},e)}}))}getActiveAPMs(){return t(this,void 0,void 0,(function*(){try{const e=yield function(e,r,o="?status=active&page_size=10000&country=México",i=null){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${e}/api/v1/payment_methods${o}`,{method:"GET",headers:{Authorization:`Token ${r}`,"Content-Type":"application/json"},signal:i});if(t.ok)return yield t.json();throw yield y({response:t,errorCode:d.FETCH_PAYMENT_METHODS_ERROR})}))}(this.baseUrl,this.apiKeyTonder),r=e&&e.results&&e.results.length>0?e.results:[];return this.activeAPMs=r.filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},Ge(e.payment_method,this.mode)))).sort(((e,t)=>e.priority-t.priority)),this.activeAPMs}catch(e){return console.error("Error getting APMS",e),[]}}))}}export{h as AppError,ge as BaseInlineCheckout,Ze as LiteCheckout,J as SdkTelemetryClient,x as validateCVV,K as validateCardNumber,j as validateCardholderName,B as validateExpirationMonth,$ as validateExpirationYear};
|
|
@@ -14,6 +14,8 @@ export declare const API_ENDPOINTS: Readonly<{
|
|
|
14
14
|
TELEMETRY: "/telemetry/v1/events";
|
|
15
15
|
ACQ_SUBSCRIPTION_TOKEN: "/acq-kushki/subscription/token";
|
|
16
16
|
ACQ_SUBSCRIPTION_CREATE: "/acq-kushki/subscription/create";
|
|
17
|
+
CORE_BUSINESS_CONFIG: "/transactions/v1/business/config";
|
|
18
|
+
CORE_PROCESS: "/transactions/v1/process";
|
|
17
19
|
}>;
|
|
18
20
|
/**
|
|
19
21
|
* Get the full telemetry endpoint URL for a given mode
|
|
@@ -29,6 +29,15 @@ export interface IBuildPublicAppErrorInput {
|
|
|
29
29
|
response?: Response;
|
|
30
30
|
lockErrorCode?: boolean;
|
|
31
31
|
}
|
|
32
|
+
/**
|
|
33
|
+
* Builds the error of an HTTP answer that was already read, or rebuilt by the SDK from
|
|
34
|
+
* another backend's answer, with the same shape a failed `fetch` produces.
|
|
35
|
+
*/
|
|
36
|
+
export declare function buildPublicAppErrorFromAnswer(data: IBuildPublicAppErrorInput & {
|
|
37
|
+
status: number;
|
|
38
|
+
statusText?: string;
|
|
39
|
+
body?: unknown;
|
|
40
|
+
}): AppError;
|
|
32
41
|
export declare function buildPublicAppError(data: IBuildPublicAppErrorInput & {
|
|
33
42
|
response: Response;
|
|
34
43
|
}, error?: unknown): Promise<AppError>;
|
package/dist/types/commons.d.ts
CHANGED
|
@@ -44,6 +44,11 @@ export type Business = {
|
|
|
44
44
|
reference: number;
|
|
45
45
|
is_installments_available: boolean;
|
|
46
46
|
cardonfile_keys?: CardOnFileKeys;
|
|
47
|
+
/**
|
|
48
|
+
* The merchant's switch already evaluated with the kill switch: when true, card
|
|
49
|
+
* payments are charged by the core instead of the legacy flow.
|
|
50
|
+
*/
|
|
51
|
+
core_payments_enabled?: boolean;
|
|
47
52
|
};
|
|
48
53
|
export type Customer = {
|
|
49
54
|
firstName: string;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** Which backend charges and finishes one payment. It is chosen once and never changes. */
|
|
2
|
+
export type PaymentEngine = "core" | "legacy";
|
|
3
|
+
export interface ICoreRouting {
|
|
4
|
+
checkout_id?: string;
|
|
5
|
+
is_route_finished?: boolean;
|
|
6
|
+
decline_type?: "Hard" | "Soft" | null;
|
|
7
|
+
rejected_psp_responses?: Record<string, any>[];
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* What the core answers to `/transactions/v1/process` and `/transactions/v1/{id}` for a
|
|
11
|
+
* first-party (`sdk/ionic`) payment: Direct API's body plus the fields the SDK needs to
|
|
12
|
+
* rebuild the result merchants get today.
|
|
13
|
+
*/
|
|
14
|
+
export interface ICoreTransactionResponse {
|
|
15
|
+
id: string;
|
|
16
|
+
status: string;
|
|
17
|
+
amount?: number | string;
|
|
18
|
+
currency?: string;
|
|
19
|
+
provider?: string | null;
|
|
20
|
+
next_action?: Record<string, any>;
|
|
21
|
+
decline_code?: string;
|
|
22
|
+
decline_reason?: string;
|
|
23
|
+
payment_id?: number;
|
|
24
|
+
transaction_id?: string;
|
|
25
|
+
routing?: ICoreRouting;
|
|
26
|
+
transaction_status?: string;
|
|
27
|
+
psp_response?: Record<string, any>;
|
|
28
|
+
}
|
package/jest.config.ts
CHANGED
|
@@ -1,8 +1,18 @@
|
|
|
1
1
|
import type { JestConfigWithTsJest } from 'ts-jest'
|
|
2
|
+
import packageJson from './package.json'
|
|
2
3
|
|
|
3
4
|
const jestConfig: JestConfigWithTsJest = {
|
|
4
5
|
testEnvironment: "jsdom",
|
|
6
|
+
// A checkout page is https in every environment that matters, and the SDK resolves
|
|
7
|
+
// relative URLs against it. jsdom defaults to http://localhost, which would make
|
|
8
|
+
// relative URLs fail the https-only scheme check for a reason production never has.
|
|
9
|
+
testEnvironmentOptions: { url: "https://localhost/" },
|
|
5
10
|
preset: 'ts-jest',
|
|
11
|
+
// Rollup's replace plugin injects these at build time; tests get the same values.
|
|
12
|
+
globals: {
|
|
13
|
+
__SDK_NAME__: packageJson.name,
|
|
14
|
+
__SDK_VERSION__: packageJson.version,
|
|
15
|
+
},
|
|
6
16
|
transform: {
|
|
7
17
|
'^.+\\.tsx?$': [
|
|
8
18
|
'ts-jest',
|
|
@@ -12,4 +22,4 @@ const jestConfig: JestConfigWithTsJest = {
|
|
|
12
22
|
},
|
|
13
23
|
}
|
|
14
24
|
|
|
15
|
-
export default jestConfig
|
|
25
|
+
export default jestConfig
|