@astropay/payments-lib 2.0.4 → 2.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/astropay-payments-lib.es.js +1 -1
- package/dist/astropay-payments-lib.umd.js +17 -8
- package/dist/{main-bICtVa5Y.js → main-D0Na6yuS.js} +129 -79
- package/dist/{profiler-CRNNYNR3.js → profiler-BIAivRqj.js} +1 -1
- package/dist/{startRecording-Bf99UXAA.js → startRecording-DjydAa5u.js} +1 -1
- package/package.json +1 -1
|
@@ -510,7 +510,7 @@ ${te}`:""}`;await copyToClipboard(ne)}};function validateValue(ee,re,te){return
|
|
|
510
510
|
flex-direction: column;
|
|
511
511
|
}
|
|
512
512
|
}
|
|
513
|
-
`;class FormTemplate extends Component{constructor(te){super({tag:"div",styles:()=>getFormTemplateStyles()});Le(this,"componentProps");Le(this,"dynamicInputs",{});Le(this,"onValidationChange",()=>{});if(this.componentProps=te,te.title){const ne=new Typography({text:te.title,size:"medium",weight:400}).element;ne.style.padding="12px 0",this.element.append(ne)}this.renderDynamicInputs()}renderDynamicInputs(){if(!this.componentProps.requiredFields)return;const te=this.componentProps.requiredFields.find(oe=>oe.field==="document_type"),ne=this.componentProps.requiredFields.find(oe=>oe.field==="document_number"),ie=this.componentProps.requiredFields.filter(oe=>oe.field!=="document_type"&&oe.field!=="document_number");te&&ne?this.renderDocumentNumberWithType(te,ne):(te&&this.renderStandardInput(te),ne&&this.renderStandardInput(ne)),ie.forEach(oe=>{this.renderStandardInput(oe)})}renderDocumentNumberWithType(te,ne){const ie=document.createElement("div");ie.classList.add("row-container");const oe=this.createInputElement(te),se=this.createInputElement(ne);this.dynamicInputs[te.field]=oe,this.dynamicInputs[ne.field]=se,this.addInputEventListeners(oe,te.type),this.addInputEventListeners(se,ne.type),ie.append(oe.element,se.element),this.element.append(ie)}renderStandardInput(te){const ne=this.createInputElement(te);this.dynamicInputs[te.field]=ne,this.addInputEventListeners(ne,te.type),this.element.append(ne.element)}createInputElement(te){return te.type===EFieldType.SELECT?this.createSelectInput({name:te.field,label:te.label,placeholder:te.placeholder,options:mountSelectOptions(te.values),validateOn:"onChange"}):this.createTextInput({name:te.field,label:te.label,placeholder:te.placeholder,type:"text",validationRegex:parseRegex(te.regex),validateOn:"onChange"})}createSelectInput(te){return new InputSelect(te)}createTextInput(te){return new InputText(te)}addInputEventListeners(te,ne){const ie=ne===EFieldType.TEXT?"input":"change";te.element.addEventListener(ie,()=>{this.validateForm(),this.triggerValidationChange()})}validateForm(){return Object.values(this.dynamicInputs).every(te=>te.getValue()&&te.validate())}getFormData(){const te={};return Object.entries(this.dynamicInputs).forEach(([ne,ie])=>{const oe=ie.getValue();te[ne]=oe!==null?String(oe):""}),te}setValidationChangeHandler(te){this.onValidationChange=te,this.triggerValidationChange()}triggerValidationChange(){this.onValidationChange&&this.onValidationChange(this.validateForm())}setFieldError(te,ne,ie){const oe=this.dynamicInputs[te];oe&&(oe.setErrorState(ne),ie&&oe.setHelperText(ie))}}const RUNTIME_CONFIG={test:{NAME:"@astropay/payments-lib",VERSION:"2.0.
|
|
513
|
+
`;class FormTemplate extends Component{constructor(te){super({tag:"div",styles:()=>getFormTemplateStyles()});Le(this,"componentProps");Le(this,"dynamicInputs",{});Le(this,"onValidationChange",()=>{});if(this.componentProps=te,te.title){const ne=new Typography({text:te.title,size:"medium",weight:400}).element;ne.style.padding="12px 0",this.element.append(ne)}this.renderDynamicInputs()}renderDynamicInputs(){if(!this.componentProps.requiredFields)return;const te=this.componentProps.requiredFields.find(oe=>oe.field==="document_type"),ne=this.componentProps.requiredFields.find(oe=>oe.field==="document_number"),ie=this.componentProps.requiredFields.filter(oe=>oe.field!=="document_type"&&oe.field!=="document_number");te&&ne?this.renderDocumentNumberWithType(te,ne):(te&&this.renderStandardInput(te),ne&&this.renderStandardInput(ne)),ie.forEach(oe=>{this.renderStandardInput(oe)})}renderDocumentNumberWithType(te,ne){const ie=document.createElement("div");ie.classList.add("row-container");const oe=this.createInputElement(te),se=this.createInputElement(ne);this.dynamicInputs[te.field]=oe,this.dynamicInputs[ne.field]=se,this.addInputEventListeners(oe,te.type),this.addInputEventListeners(se,ne.type),ie.append(oe.element,se.element),this.element.append(ie)}renderStandardInput(te){const ne=this.createInputElement(te);this.dynamicInputs[te.field]=ne,this.addInputEventListeners(ne,te.type),this.element.append(ne.element)}createInputElement(te){return te.type===EFieldType.SELECT?this.createSelectInput({name:te.field,label:te.label,placeholder:te.placeholder,options:mountSelectOptions(te.values),validateOn:"onChange"}):this.createTextInput({name:te.field,label:te.label,placeholder:te.placeholder,type:"text",validationRegex:parseRegex(te.regex),validateOn:"onChange"})}createSelectInput(te){return new InputSelect(te)}createTextInput(te){return new InputText(te)}addInputEventListeners(te,ne){const ie=ne===EFieldType.TEXT?"input":"change";te.element.addEventListener(ie,()=>{this.validateForm(),this.triggerValidationChange()})}validateForm(){return Object.values(this.dynamicInputs).every(te=>te.getValue()&&te.validate())}getFormData(){const te={};return Object.entries(this.dynamicInputs).forEach(([ne,ie])=>{const oe=ie.getValue();te[ne]=oe!==null?String(oe):""}),te}setValidationChangeHandler(te){this.onValidationChange=te,this.triggerValidationChange()}triggerValidationChange(){this.onValidationChange&&this.onValidationChange(this.validateForm())}setFieldError(te,ne,ie){const oe=this.dynamicInputs[te];oe&&(oe.setErrorState(ne),ie&&oe.setHelperText(ie))}}const RUNTIME_CONFIG={test:{NAME:"@astropay/payments-lib",VERSION:"2.0.5",MODE:"test",API_BASE_URL:"https://partners-api-tst.astropay.com/api",RESOURCES_BUCKET:"https://rs-tst.astropay.com",CHECKOUT_URL:"https://checkout-tst.astropay.com",SINGULAR_LINK_URL:"https://astropay-tst.sng.link/Eftaj/ovlnu?_smtype=3",SINGULAR_LINK_PREFIX:"apcmobiletst://"},sandbox:{NAME:"@astropay/payments-lib",VERSION:"2.0.5",MODE:"staging",API_BASE_URL:"https://partners-api-sandbox.astropay.com/api",RESOURCES_BUCKET:"https://rs-tst.astropay.com",CHECKOUT_URL:"https://checkout-sandbox.astropay.com",SINGULAR_LINK_URL:"https://astropay-stg.sng.link/Ezzoz/nfnj?_smtype=3",SINGULAR_LINK_PREFIX:"apcmobilestaging://"},production:{NAME:"@astropay/payments-lib",VERSION:"2.0.5",MODE:"production",API_BASE_URL:"https://partners-api.astropay.com/api",RESOURCES_BUCKET:"https://rs.astropay.com",CHECKOUT_URL:"https://checkout.astropay.com",SINGULAR_LINK_URL:"https://astropay.sng.link/E2h2a/jqze?_smtype=3",SINGULAR_LINK_PREFIX:"apcmobile://"}};var EStorageKey=(ee=>(ee.SESSION_ID="session_id",ee))(EStorageKey||{});const Jr=class Jr{static init(re){const te=validateValue(re==null?void 0:re.environment,[...CONFIG_ENVIRONMENT_VALUES,"test"],"production"),ne=validateValue(re==null?void 0:re.currencyMode,CONFIG_CURRENCY_MODE_VALUES,"iso");Jr.environment=te,Jr.currencyMode=ne}static getRuntimeConfig(){const re=Jr.environment||"production";return RUNTIME_CONFIG[re]}static getEnvironment(){return Jr.environment}static getCurrencyMode(){return Jr.currencyMode}};Le(Jr,"environment"),Le(Jr,"currencyMode");let AstroPayConfig=Jr;const locales={AED:"ar-AE",AOA:"pt-AO",AND:"ca-AD",ARS:"es-AR",AUD:"en-AU",BDT:"bn-BD",BGN:"bg-BG",BOB:"es-BO",BRL:"pt-BR",CAD:"en-CA",CDF:"fr-CD",CLP:"es-CL",CNY:"zh-CN",COP:"es-CO",CZK:"cs-CZ",DKK:"da-DK",EGP:"ar-EG",ETB:"am-ET",EUR:"de-DE",GBP:"en-GB",GHS:"en-GH",GTQ:"es-GT",HNL:"es-HN",HKD:"zh-HK",HUF:"hu-HU",IDR:"id-ID",INR:"hi-IN",JPY:"ja-JP",KES:"en-KE",KRW:"ko-KR",KWD:"ar-KW",KZT:"kk-KZ",LKR:"si-LK",LSL:"st-LS",MAD:"ar-MA",MGA:"mg-MG",MKD:"mk-MK",MMK:"my-MM",MNT:"mn-MN",MOP:"zh-MO",MXN:"es-MX",MYR:"ms-MY",MZN:"pt-MZ",NGN:"en-NG",NIO:"es-NI",NOK:"no-NO",NPR:"ne-NP",NZD:"en-NZ",PAB:"es-PA",PEN:"es-PE",PKR:"ur-PK",PLN:"pl-PL",PYG:"es-PY",QAR:"ar-QA",RMB:"zh-CN",RSD:"sr-RS",RUB:"ru-RU",RWF:"rw-RW",SAR:"ar-SA",SEK:"sv-SE",SLL:"en-SL",SVC:"es-SV",THB:"th-TH",TND:"ar-TN",TRY:"tr-TR",TTD:"en-TT",TWD:"zh-TW",TZS:"sw-TZ",UAH:"uk-UA",UGX:"en-UG",USD:"en-US",UYU:"es-UY",UZS:"uz-UZ",VND:"vi-VN",XAF:"fr-CM",XOF:"fr-SN",ZAR:"en-ZA",ZWD:"en-ZW",ZWL:"en-ZW"},formatAmount=(ee,re)=>{const te=locales[re]||"en-US";return new Intl.NumberFormat(te,{style:"decimal",currency:re,minimumFractionDigits:2,maximumFractionDigits:2}).format(ee)},currencyCodeMap={AED:"د.إ",AOA:"Kz",AND:"€",ARS:"$",AUD:"$",BDT:"৳",BGN:"лв",BOB:"Bs.",BRL:"R$",CAD:"$",CDF:"FC",CLP:"$",CNY:"¥",COP:"$",CZK:"Kč",DKK:"kr",EGP:"£",ETB:"Br",EUR:"€",GBP:"£",GHS:"₵",GTQ:"Q",HNL:"L",HKD:"$",HUF:"Ft",IDR:"Rp",INR:"₹",JPY:"¥",KES:"KSh",KRW:"₩",KWD:"د.ك",KZT:"₸",LKR:"₨",LSL:"L",MAD:"د.م.",MGA:"Ar",MKD:"ден",MMK:"K",MNT:"₮",MOP:"MOP$",MXN:"$",MYR:"RM",MZN:"MT",NGN:"₦",NIO:"C$",NOK:"kr",NPR:"₨",NZD:"$",PAB:"B/.",PEN:"S/.",PKR:"₨",PLN:"zł",PYG:"₲",QAR:"﷼",RMB:"¥",RSD:"РСД",RUB:"₽",RWF:"FRw",SAR:"ر.س",SEK:"kr",SLL:"Le",SVC:"$",THB:"฿",TND:"د.ت",TRY:"₺",TTD:"$",TWD:"NT$",TZS:"TSh",UAH:"₴",UGX:"USh",USD:"US$",UYU:"$",UZS:"so'm",VND:"₫",XAF:"FCFA",XOF:"CFA",ZAR:"R",ZWD:"$",ZWL:"$"},codeToSymbol=ee=>ee===void 0?"":currencyCodeMap[ee.trim()]||ee,formatAmountCurrency=(ee,re,te)=>{const ne=formatAmount(ee,re);return te==="symbol"?`${codeToSymbol(re)} ${ne}`:`${ne} ${re}`},getPaymentSummaryStyles=ee=>css`
|
|
514
514
|
display: flex;
|
|
515
515
|
flex-direction: column;
|
|
516
516
|
background-color: ${ee.card.backgroundColor};
|
|
@@ -569,7 +569,7 @@ Body:`)).call(gr,Oi()(vr)));var $r=new XMLHttpRequest;$r.open(De._method||ue.Pos
|
|
|
569
569
|
`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(re){return re instanceof this?re:new this(re)}static concat(re,...te){const ne=new this(re);return te.forEach(ie=>ne.set(ie)),ne}static accessor(re){const ne=(this[$internals]=this[$internals]={accessors:{}}).accessors,ie=this.prototype;function oe(se){const ae=normalizeHeader(se);ne[ae]||(buildAccessors(ie,se),ne[ae]=!0)}return utils$3.isArray(re)?re.forEach(oe):oe(re),this}};AxiosHeaders$1.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),utils$3.reduceDescriptors(AxiosHeaders$1.prototype,({value:ee},re)=>{let te=re[0].toUpperCase()+re.slice(1);return{get:()=>ee,set(ne){this[te]=ne}}}),utils$3.freezeMethods(AxiosHeaders$1);function transformData(ee,re){const te=this||defaults,ne=re||te,ie=AxiosHeaders$1.from(ne.headers);let oe=ne.data;return utils$3.forEach(ee,function(ae){oe=ae.call(te,oe,ie.normalize(),re?re.status:void 0)}),ie.normalize(),oe}function isCancel$1(ee){return!!(ee&&ee.__CANCEL__)}function CanceledError$1(ee,re,te){AxiosError$1.call(this,ee??"canceled",AxiosError$1.ERR_CANCELED,re,te),this.name="CanceledError"}utils$3.inherits(CanceledError$1,AxiosError$1,{__CANCEL__:!0});function settle(ee,re,te){const ne=te.config.validateStatus;!te.status||!ne||ne(te.status)?ee(te):re(new AxiosError$1("Request failed with status code "+te.status,[AxiosError$1.ERR_BAD_REQUEST,AxiosError$1.ERR_BAD_RESPONSE][Math.floor(te.status/100)-4],te.config,te.request,te))}function parseProtocol(ee){const re=/^([-+\w]{1,25})(:?\/\/|:)/.exec(ee);return re&&re[1]||""}function speedometer(ee,re){ee=ee||10;const te=new Array(ee),ne=new Array(ee);let ie=0,oe=0,se;return re=re!==void 0?re:1e3,function(ue){const ce=Date.now(),le=ne[oe];se||(se=ce),te[ie]=ue,ne[ie]=ce;let de=oe,fe=0;for(;de!==ie;)fe+=te[de++],de=de%ee;if(ie=(ie+1)%ee,ie===oe&&(oe=(oe+1)%ee),ce-se<re)return;const he=le&&ce-le;return he?Math.round(fe*1e3/he):void 0}}function throttle(ee,re){let te=0,ne=1e3/re,ie,oe;const se=(ce,le=Date.now())=>{te=le,ie=null,oe&&(clearTimeout(oe),oe=null),ee(...ce)};return[(...ce)=>{const le=Date.now(),de=le-te;de>=ne?se(ce,le):(ie=ce,oe||(oe=setTimeout(()=>{oe=null,se(ie)},ne-de)))},()=>ie&&se(ie)]}const progressEventReducer=(ee,re,te=3)=>{let ne=0;const ie=speedometer(50,250);return throttle(oe=>{const se=oe.loaded,ae=oe.lengthComputable?oe.total:void 0,ue=se-ne,ce=ie(ue),le=se<=ae;ne=se;const de={loaded:se,total:ae,progress:ae?se/ae:void 0,bytes:ue,rate:ce||void 0,estimated:ce&&ae&&le?(ae-se)/ce:void 0,event:oe,lengthComputable:ae!=null,[re?"download":"upload"]:!0};ee(de)},te)},progressEventDecorator=(ee,re)=>{const te=ee!=null;return[ne=>re[0]({lengthComputable:te,total:ee,loaded:ne}),re[1]]},asyncDecorator=ee=>(...re)=>utils$3.asap(()=>ee(...re)),isURLSameOrigin=platform.hasStandardBrowserEnv?((ee,re)=>te=>(te=new URL(te,platform.origin),ee.protocol===te.protocol&&ee.host===te.host&&(re||ee.port===te.port)))(new URL(platform.origin),platform.navigator&&/(msie|trident)/i.test(platform.navigator.userAgent)):()=>!0,cookies=platform.hasStandardBrowserEnv?{write(ee,re,te,ne,ie,oe){const se=[ee+"="+encodeURIComponent(re)];utils$3.isNumber(te)&&se.push("expires="+new Date(te).toGMTString()),utils$3.isString(ne)&&se.push("path="+ne),utils$3.isString(ie)&&se.push("domain="+ie),oe===!0&&se.push("secure"),document.cookie=se.join("; ")},read(ee){const re=document.cookie.match(new RegExp("(^|;\\s*)("+ee+")=([^;]*)"));return re?decodeURIComponent(re[3]):null},remove(ee){this.write(ee,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function isAbsoluteURL(ee){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(ee)}function combineURLs(ee,re){return re?ee.replace(/\/?\/$/,"")+"/"+re.replace(/^\/+/,""):ee}function buildFullPath(ee,re,te){let ne=!isAbsoluteURL(re);return ee&&(ne||te==!1)?combineURLs(ee,re):re}const headersToObject=ee=>ee instanceof AxiosHeaders$1?{...ee}:ee;function mergeConfig$1(ee,re){re=re||{};const te={};function ne(ce,le,de,fe){return utils$3.isPlainObject(ce)&&utils$3.isPlainObject(le)?utils$3.merge.call({caseless:fe},ce,le):utils$3.isPlainObject(le)?utils$3.merge({},le):utils$3.isArray(le)?le.slice():le}function ie(ce,le,de,fe){if(utils$3.isUndefined(le)){if(!utils$3.isUndefined(ce))return ne(void 0,ce,de,fe)}else return ne(ce,le,de,fe)}function oe(ce,le){if(!utils$3.isUndefined(le))return ne(void 0,le)}function se(ce,le){if(utils$3.isUndefined(le)){if(!utils$3.isUndefined(ce))return ne(void 0,ce)}else return ne(void 0,le)}function ae(ce,le,de){if(de in re)return ne(ce,le);if(de in ee)return ne(void 0,ce)}const ue={url:oe,method:oe,data:oe,baseURL:se,transformRequest:se,transformResponse:se,paramsSerializer:se,timeout:se,timeoutMessage:se,withCredentials:se,withXSRFToken:se,adapter:se,responseType:se,xsrfCookieName:se,xsrfHeaderName:se,onUploadProgress:se,onDownloadProgress:se,decompress:se,maxContentLength:se,maxBodyLength:se,beforeRedirect:se,transport:se,httpAgent:se,httpsAgent:se,cancelToken:se,socketPath:se,responseEncoding:se,validateStatus:ae,headers:(ce,le,de)=>ie(headersToObject(ce),headersToObject(le),de,!0)};return utils$3.forEach(Object.keys({...ee,...re}),function(le){const de=ue[le]||ie,fe=de(ee[le],re[le],le);utils$3.isUndefined(fe)&&de!==ae||(te[le]=fe)}),te}const resolveConfig=ee=>{const re=mergeConfig$1({},ee);let{data:te,withXSRFToken:ne,xsrfHeaderName:ie,xsrfCookieName:oe,headers:se,auth:ae}=re;if(re.headers=se=AxiosHeaders$1.from(se),re.url=buildURL(buildFullPath(re.baseURL,re.url,re.allowAbsoluteUrls),ee.params,ee.paramsSerializer),ae&&se.set("Authorization","Basic "+btoa((ae.username||"")+":"+(ae.password?unescape(encodeURIComponent(ae.password)):""))),utils$3.isFormData(te)){if(platform.hasStandardBrowserEnv||platform.hasStandardBrowserWebWorkerEnv)se.setContentType(void 0);else if(utils$3.isFunction(te.getHeaders)){const ue=te.getHeaders(),ce=["content-type","content-length"];Object.entries(ue).forEach(([le,de])=>{ce.includes(le.toLowerCase())&&se.set(le,de)})}}if(platform.hasStandardBrowserEnv&&(ne&&utils$3.isFunction(ne)&&(ne=ne(re)),ne||ne!==!1&&isURLSameOrigin(re.url))){const ue=ie&&oe&&cookies.read(oe);ue&&se.set(ie,ue)}return re},isXHRAdapterSupported=typeof XMLHttpRequest<"u",xhrAdapter=isXHRAdapterSupported&&function(ee){return new Promise(function(te,ne){const ie=resolveConfig(ee);let oe=ie.data;const se=AxiosHeaders$1.from(ie.headers).normalize();let{responseType:ae,onUploadProgress:ue,onDownloadProgress:ce}=ie,le,de,fe,he,pe;function ge(){he&&he(),pe&&pe(),ie.cancelToken&&ie.cancelToken.unsubscribe(le),ie.signal&&ie.signal.removeEventListener("abort",le)}let me=new XMLHttpRequest;me.open(ie.method.toUpperCase(),ie.url,!0),me.timeout=ie.timeout;function ye(){if(!me)return;const _e=AxiosHeaders$1.from("getAllResponseHeaders"in me&&me.getAllResponseHeaders()),Ie={data:!ae||ae==="text"||ae==="json"?me.responseText:me.response,status:me.status,statusText:me.statusText,headers:_e,config:ee,request:me};settle(function(Se){te(Se),ge()},function(Se){ne(Se),ge()},Ie),me=null}"onloadend"in me?me.onloadend=ye:me.onreadystatechange=function(){!me||me.readyState!==4||me.status===0&&!(me.responseURL&&me.responseURL.indexOf("file:")===0)||setTimeout(ye)},me.onabort=function(){me&&(ne(new AxiosError$1("Request aborted",AxiosError$1.ECONNABORTED,ee,me)),me=null)},me.onerror=function(be){const Ie=be&&be.message?be.message:"Network Error",Te=new AxiosError$1(Ie,AxiosError$1.ERR_NETWORK,ee,me);Te.event=be||null,ne(Te),me=null},me.ontimeout=function(){let be=ie.timeout?"timeout of "+ie.timeout+"ms exceeded":"timeout exceeded";const Ie=ie.transitional||transitionalDefaults;ie.timeoutErrorMessage&&(be=ie.timeoutErrorMessage),ne(new AxiosError$1(be,Ie.clarifyTimeoutError?AxiosError$1.ETIMEDOUT:AxiosError$1.ECONNABORTED,ee,me)),me=null},oe===void 0&&se.setContentType(null),"setRequestHeader"in me&&utils$3.forEach(se.toJSON(),function(be,Ie){me.setRequestHeader(Ie,be)}),utils$3.isUndefined(ie.withCredentials)||(me.withCredentials=!!ie.withCredentials),ae&&ae!=="json"&&(me.responseType=ie.responseType),ce&&([fe,pe]=progressEventReducer(ce,!0),me.addEventListener("progress",fe)),ue&&me.upload&&([de,he]=progressEventReducer(ue),me.upload.addEventListener("progress",de),me.upload.addEventListener("loadend",he)),(ie.cancelToken||ie.signal)&&(le=_e=>{me&&(ne(!_e||_e.type?new CanceledError$1(null,ee,me):_e),me.abort(),me=null)},ie.cancelToken&&ie.cancelToken.subscribe(le),ie.signal&&(ie.signal.aborted?le():ie.signal.addEventListener("abort",le)));const ve=parseProtocol(ie.url);if(ve&&platform.protocols.indexOf(ve)===-1){ne(new AxiosError$1("Unsupported protocol "+ve+":",AxiosError$1.ERR_BAD_REQUEST,ee));return}me.send(oe||null)})},composeSignals=(ee,re)=>{const{length:te}=ee=ee?ee.filter(Boolean):[];if(re||te){let ne=new AbortController,ie;const oe=function(ce){if(!ie){ie=!0,ae();const le=ce instanceof Error?ce:this.reason;ne.abort(le instanceof AxiosError$1?le:new CanceledError$1(le instanceof Error?le.message:le))}};let se=re&&setTimeout(()=>{se=null,oe(new AxiosError$1(`timeout ${re} of ms exceeded`,AxiosError$1.ETIMEDOUT))},re);const ae=()=>{ee&&(se&&clearTimeout(se),se=null,ee.forEach(ce=>{ce.unsubscribe?ce.unsubscribe(oe):ce.removeEventListener("abort",oe)}),ee=null)};ee.forEach(ce=>ce.addEventListener("abort",oe));const{signal:ue}=ne;return ue.unsubscribe=()=>utils$3.asap(ae),ue}},streamChunk=function*(ee,re){let te=ee.byteLength;if(te<re){yield ee;return}let ne=0,ie;for(;ne<te;)ie=ne+re,yield ee.slice(ne,ie),ne=ie},readBytes=async function*(ee,re){for await(const te of readStream(ee))yield*streamChunk(te,re)},readStream=async function*(ee){if(ee[Symbol.asyncIterator]){yield*ee;return}const re=ee.getReader();try{for(;;){const{done:te,value:ne}=await re.read();if(te)break;yield ne}}finally{await re.cancel()}},trackStream=(ee,re,te,ne)=>{const ie=readBytes(ee,re);let oe=0,se,ae=ue=>{se||(se=!0,ne&&ne(ue))};return new ReadableStream({async pull(ue){try{const{done:ce,value:le}=await ie.next();if(ce){ae(),ue.close();return}let de=le.byteLength;if(te){let fe=oe+=de;te(fe)}ue.enqueue(new Uint8Array(le))}catch(ce){throw ae(ce),ce}},cancel(ue){return ae(ue),ie.return()}},{highWaterMark:2})},DEFAULT_CHUNK_SIZE=64*1024,{isFunction}=utils$3,globalFetchAPI=(({Request:ee,Response:re})=>({Request:ee,Response:re}))(utils$3.global),{ReadableStream:ReadableStream$1,TextEncoder:TextEncoder$1}=utils$3.global,test=(ee,...re)=>{try{return!!ee(...re)}catch{return!1}},factory=ee=>{ee=utils$3.merge.call({skipUndefined:!0},globalFetchAPI,ee);const{fetch:re,Request:te,Response:ne}=ee,ie=re?isFunction(re):typeof fetch=="function",oe=isFunction(te),se=isFunction(ne);if(!ie)return!1;const ae=ie&&isFunction(ReadableStream$1),ue=ie&&(typeof TextEncoder$1=="function"?(pe=>ge=>pe.encode(ge))(new TextEncoder$1):async pe=>new Uint8Array(await new te(pe).arrayBuffer())),ce=oe&&ae&&test(()=>{let pe=!1;const ge=new te(platform.origin,{body:new ReadableStream$1,method:"POST",get duplex(){return pe=!0,"half"}}).headers.has("Content-Type");return pe&&!ge}),le=se&&ae&&test(()=>utils$3.isReadableStream(new ne("").body)),de={stream:le&&(pe=>pe.body)};ie&&["text","arrayBuffer","blob","formData","stream"].forEach(pe=>{!de[pe]&&(de[pe]=(ge,me)=>{let ye=ge&&ge[pe];if(ye)return ye.call(ge);throw new AxiosError$1(`Response type '${pe}' is not supported`,AxiosError$1.ERR_NOT_SUPPORT,me)})});const fe=async pe=>{if(pe==null)return 0;if(utils$3.isBlob(pe))return pe.size;if(utils$3.isSpecCompliantForm(pe))return(await new te(platform.origin,{method:"POST",body:pe}).arrayBuffer()).byteLength;if(utils$3.isArrayBufferView(pe)||utils$3.isArrayBuffer(pe))return pe.byteLength;if(utils$3.isURLSearchParams(pe)&&(pe=pe+""),utils$3.isString(pe))return(await ue(pe)).byteLength},he=async(pe,ge)=>{const me=utils$3.toFiniteNumber(pe.getContentLength());return me??fe(ge)};return async pe=>{let{url:ge,method:me,data:ye,signal:ve,cancelToken:_e,timeout:be,onDownloadProgress:Ie,onUploadProgress:Te,responseType:Se,headers:Re,withCredentials:Ce="same-origin",fetchOptions:we}=resolveConfig(pe),xe=re||fetch;Se=Se?(Se+"").toLowerCase():"text";let Ne=composeSignals([ve,_e&&_e.toAbortSignal()],be),Ue=null;const $e=Ne&&Ne.unsubscribe&&(()=>{Ne.unsubscribe()});let Ve;try{if(Te&&ce&&me!=="get"&&me!=="head"&&(Ve=await he(Re,ye))!==0){let dr=new te(ge,{method:"POST",body:ye,duplex:"half"}),Qe;if(utils$3.isFormData(ye)&&(Qe=dr.headers.get("content-type"))&&Re.setContentType(Qe),dr.body){const[Bt,Ir]=progressEventDecorator(Ve,progressEventReducer(asyncDecorator(Te)));ye=trackStream(dr.body,DEFAULT_CHUNK_SIZE,Bt,Ir)}}utils$3.isString(Ce)||(Ce=Ce?"include":"omit");const ze=oe&&"credentials"in te.prototype,ur={...we,signal:Ne,method:me.toUpperCase(),headers:Re.normalize().toJSON(),body:ye,duplex:"half",credentials:ze?Ce:void 0};Ue=oe&&new te(ge,ur);let Ge=await(oe?xe(Ue,we):xe(ge,ur));const hr=le&&(Se==="stream"||Se==="response");if(le&&(Ie||hr&&$e)){const dr={};["status","statusText","headers"].forEach(Fe=>{dr[Fe]=Ge[Fe]});const Qe=utils$3.toFiniteNumber(Ge.headers.get("content-length")),[Bt,Ir]=Ie&&progressEventDecorator(Qe,progressEventReducer(asyncDecorator(Ie),!0))||[];Ge=new ne(trackStream(Ge.body,DEFAULT_CHUNK_SIZE,Bt,()=>{Ir&&Ir(),$e&&$e()}),dr)}Se=Se||"text";let fr=await de[utils$3.findKey(de,Se)||"text"](Ge,pe);return!hr&&$e&&$e(),await new Promise((dr,Qe)=>{settle(dr,Qe,{data:fr,headers:AxiosHeaders$1.from(Ge.headers),status:Ge.status,statusText:Ge.statusText,config:pe,request:Ue})})}catch(ze){throw $e&&$e(),ze&&ze.name==="TypeError"&&/Load failed|fetch/i.test(ze.message)?Object.assign(new AxiosError$1("Network Error",AxiosError$1.ERR_NETWORK,pe,Ue),{cause:ze.cause||ze}):AxiosError$1.from(ze,ze&&ze.code,pe,Ue)}}},seedCache=new Map,getFetch=ee=>{let re=ee?ee.env:{};const{fetch:te,Request:ne,Response:ie}=re,oe=[ne,ie,te];let se=oe.length,ae=se,ue,ce,le=seedCache;for(;ae--;)ue=oe[ae],ce=le.get(ue),ce===void 0&&le.set(ue,ce=ae?new Map:factory(re)),le=ce;return ce};getFetch();const knownAdapters={http:httpAdapter,xhr:xhrAdapter,fetch:{get:getFetch}};utils$3.forEach(knownAdapters,(ee,re)=>{if(ee){try{Object.defineProperty(ee,"name",{value:re})}catch{}Object.defineProperty(ee,"adapterName",{value:re})}});const renderReason=ee=>`- ${ee}`,isResolvedHandle=ee=>utils$3.isFunction(ee)||ee===null||ee===!1,adapters={getAdapter:(ee,re)=>{ee=utils$3.isArray(ee)?ee:[ee];const{length:te}=ee;let ne,ie;const oe={};for(let se=0;se<te;se++){ne=ee[se];let ae;if(ie=ne,!isResolvedHandle(ne)&&(ie=knownAdapters[(ae=String(ne)).toLowerCase()],ie===void 0))throw new AxiosError$1(`Unknown adapter '${ae}'`);if(ie&&(utils$3.isFunction(ie)||(ie=ie.get(re))))break;oe[ae||"#"+se]=ie}if(!ie){const se=Object.entries(oe).map(([ue,ce])=>`adapter ${ue} `+(ce===!1?"is not supported by the environment":"is not available in the build"));let ae=te?se.length>1?`since :
|
|
570
570
|
`+se.map(renderReason).join(`
|
|
571
571
|
`):" "+renderReason(se[0]):"as no adapter specified";throw new AxiosError$1("There is no suitable adapter to dispatch the request "+ae,"ERR_NOT_SUPPORT")}return ie},adapters:knownAdapters};function throwIfCancellationRequested(ee){if(ee.cancelToken&&ee.cancelToken.throwIfRequested(),ee.signal&&ee.signal.aborted)throw new CanceledError$1(null,ee)}function dispatchRequest(ee){return throwIfCancellationRequested(ee),ee.headers=AxiosHeaders$1.from(ee.headers),ee.data=transformData.call(ee,ee.transformRequest),["post","put","patch"].indexOf(ee.method)!==-1&&ee.headers.setContentType("application/x-www-form-urlencoded",!1),adapters.getAdapter(ee.adapter||defaults.adapter,ee)(ee).then(function(ne){return throwIfCancellationRequested(ee),ne.data=transformData.call(ee,ee.transformResponse,ne),ne.headers=AxiosHeaders$1.from(ne.headers),ne},function(ne){return isCancel$1(ne)||(throwIfCancellationRequested(ee),ne&&ne.response&&(ne.response.data=transformData.call(ee,ee.transformResponse,ne.response),ne.response.headers=AxiosHeaders$1.from(ne.response.headers))),Promise.reject(ne)})}const VERSION$1="1.12.2",validators$1={};["object","boolean","number","function","string","symbol"].forEach((ee,re)=>{validators$1[ee]=function(ne){return typeof ne===ee||"a"+(re<1?"n ":" ")+ee}});const deprecatedWarnings={};validators$1.transitional=function ee(re,te,ne){function ie(oe,se){return"[Axios v"+VERSION$1+"] Transitional option '"+oe+"'"+se+(ne?". "+ne:"")}return(oe,se,ae)=>{if(re===!1)throw new AxiosError$1(ie(se," has been removed"+(te?" in "+te:"")),AxiosError$1.ERR_DEPRECATED);return te&&!deprecatedWarnings[se]&&(deprecatedWarnings[se]=!0,console.warn(ie(se," has been deprecated since v"+te+" and will be removed in the near future"))),re?re(oe,se,ae):!0}},validators$1.spelling=function ee(re){return(te,ne)=>(console.warn(`${ne} is likely a misspelling of ${re}`),!0)};function assertOptions(ee,re,te){if(typeof ee!="object")throw new AxiosError$1("options must be an object",AxiosError$1.ERR_BAD_OPTION_VALUE);const ne=Object.keys(ee);let ie=ne.length;for(;ie-- >0;){const oe=ne[ie],se=re[oe];if(se){const ae=ee[oe],ue=ae===void 0||se(ae,oe,ee);if(ue!==!0)throw new AxiosError$1("option "+oe+" must be "+ue,AxiosError$1.ERR_BAD_OPTION_VALUE);continue}if(te!==!0)throw new AxiosError$1("Unknown option "+oe,AxiosError$1.ERR_BAD_OPTION)}}const validator={assertOptions,validators:validators$1},validators=validator.validators;let Axios$1=class{constructor(re){this.defaults=re||{},this.interceptors={request:new InterceptorManager,response:new InterceptorManager}}async request(re,te){try{return await this._request(re,te)}catch(ne){if(ne instanceof Error){let ie={};Error.captureStackTrace?Error.captureStackTrace(ie):ie=new Error;const oe=ie.stack?ie.stack.replace(/^.+\n/,""):"";try{ne.stack?oe&&!String(ne.stack).endsWith(oe.replace(/^.+\n.+\n/,""))&&(ne.stack+=`
|
|
572
|
-
`+oe):ne.stack=oe}catch{}}throw ne}}_request(re,te){typeof re=="string"?(te=te||{},te.url=re):te=re||{},te=mergeConfig$1(this.defaults,te);const{transitional:ne,paramsSerializer:ie,headers:oe}=te;ne!==void 0&&validator.assertOptions(ne,{silentJSONParsing:validators.transitional(validators.boolean),forcedJSONParsing:validators.transitional(validators.boolean),clarifyTimeoutError:validators.transitional(validators.boolean)},!1),ie!=null&&(utils$3.isFunction(ie)?te.paramsSerializer={serialize:ie}:validator.assertOptions(ie,{encode:validators.function,serialize:validators.function},!0)),te.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?te.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:te.allowAbsoluteUrls=!0),validator.assertOptions(te,{baseUrl:validators.spelling("baseURL"),withXsrfToken:validators.spelling("withXSRFToken")},!0),te.method=(te.method||this.defaults.method||"get").toLowerCase();let se=oe&&utils$3.merge(oe.common,oe[te.method]);oe&&utils$3.forEach(["delete","get","head","post","put","patch","common"],pe=>{delete oe[pe]}),te.headers=AxiosHeaders$1.concat(se,oe);const ae=[];let ue=!0;this.interceptors.request.forEach(function(ge){typeof ge.runWhen=="function"&&ge.runWhen(te)===!1||(ue=ue&&ge.synchronous,ae.unshift(ge.fulfilled,ge.rejected))});const ce=[];this.interceptors.response.forEach(function(ge){ce.push(ge.fulfilled,ge.rejected)});let le,de=0,fe;if(!ue){const pe=[dispatchRequest.bind(this),void 0];for(pe.unshift(...ae),pe.push(...ce),fe=pe.length,le=Promise.resolve(te);de<fe;)le=le.then(pe[de++],pe[de++]);return le}fe=ae.length;let he=te;for(;de<fe;){const pe=ae[de++],ge=ae[de++];try{he=pe(he)}catch(me){ge.call(this,me);break}}try{le=dispatchRequest.call(this,he)}catch(pe){return Promise.reject(pe)}for(de=0,fe=ce.length;de<fe;)le=le.then(ce[de++],ce[de++]);return le}getUri(re){re=mergeConfig$1(this.defaults,re);const te=buildFullPath(re.baseURL,re.url,re.allowAbsoluteUrls);return buildURL(te,re.params,re.paramsSerializer)}};utils$3.forEach(["delete","get","head","options"],function ee(re){Axios$1.prototype[re]=function(te,ne){return this.request(mergeConfig$1(ne||{},{method:re,url:te,data:(ne||{}).data}))}}),utils$3.forEach(["post","put","patch"],function ee(re){function te(ne){return function(oe,se,ae){return this.request(mergeConfig$1(ae||{},{method:re,headers:ne?{"Content-Type":"multipart/form-data"}:{},url:oe,data:se}))}}Axios$1.prototype[re]=te(),Axios$1.prototype[re+"Form"]=te(!0)});let CancelToken$1=class Lo{constructor(re){if(typeof re!="function")throw new TypeError("executor must be a function.");let te;this.promise=new Promise(function(oe){te=oe});const ne=this;this.promise.then(ie=>{if(!ne._listeners)return;let oe=ne._listeners.length;for(;oe-- >0;)ne._listeners[oe](ie);ne._listeners=null}),this.promise.then=ie=>{let oe;const se=new Promise(ae=>{ne.subscribe(ae),oe=ae}).then(ie);return se.cancel=function(){ne.unsubscribe(oe)},se},re(function(oe,se,ae){ne.reason||(ne.reason=new CanceledError$1(oe,se,ae),te(ne.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(re){if(this.reason){re(this.reason);return}this._listeners?this._listeners.push(re):this._listeners=[re]}unsubscribe(re){if(!this._listeners)return;const te=this._listeners.indexOf(re);te!==-1&&this._listeners.splice(te,1)}toAbortSignal(){const re=new AbortController,te=ne=>{re.abort(ne)};return this.subscribe(te),re.signal.unsubscribe=()=>this.unsubscribe(te),re.signal}static source(){let re;return{token:new Lo(function(ie){re=ie}),cancel:re}}};function spread$1(ee){return function(te){return ee.apply(null,te)}}function isAxiosError$1(ee){return utils$3.isObject(ee)&&ee.isAxiosError===!0}const HttpStatusCode$1={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(HttpStatusCode$1).forEach(([ee,re])=>{HttpStatusCode$1[re]=ee});function createInstance(ee){const re=new Axios$1(ee),te=bind(Axios$1.prototype.request,re);return utils$3.extend(te,Axios$1.prototype,re,{allOwnKeys:!0}),utils$3.extend(te,re,null,{allOwnKeys:!0}),te.create=function(ie){return createInstance(mergeConfig$1(ee,ie))},te}const axios=createInstance(defaults);axios.Axios=Axios$1,axios.CanceledError=CanceledError$1,axios.CancelToken=CancelToken$1,axios.isCancel=isCancel$1,axios.VERSION=VERSION$1,axios.toFormData=toFormData$1,axios.AxiosError=AxiosError$1,axios.Cancel=axios.CanceledError,axios.all=function ee(re){return Promise.all(re)},axios.spread=spread$1,axios.isAxiosError=isAxiosError$1,axios.mergeConfig=mergeConfig$1,axios.AxiosHeaders=AxiosHeaders$1,axios.formToJSON=ee=>formDataToJSON(utils$3.isHTMLForm(ee)?new FormData(ee):ee),axios.getAdapter=adapters.getAdapter,axios.HttpStatusCode=HttpStatusCode$1,axios.default=axios;const{Axios,AxiosError,CanceledError,isCancel,CancelToken,VERSION,all,Cancel,isAxiosError,spread,toFormData,AxiosHeaders,HttpStatusCode,formToJSON,getAdapter,mergeConfig}=axios,mockPath=(ee,re)=>{const te=AstroPayConfig.getRuntimeConfig().MODE==="test";return re&&te?`http://localhost:3333${ee.startsWith("/")?ee:`/${ee}`}`:ee},Wr=class Wr{static getAxiosInstance(){if(!this.axiosInstance)throw new Error("AstroPay Payments Library: Not initialized.");return this.axiosInstance}};Le(Wr,"axiosInstance"),Le(Wr,"config"),Le(Wr,"init",re=>{Wr.config=re,Wr.axiosInstance=axios.create({baseURL:re.baseURL,timeout:re.timeout??5e3,withCredentials:!0,headers:{"Accept-Language":AstroPayI18n.getCurrent(),...re.headers}}),Wr.setupInterceptors()}),Le(Wr,"GET",async({url:re,params:te={},mock:ne=!1,useQueryParams:ie=!0})=>{const oe=mockPath(re,ne),se={params:{useQueryParams:ie,...te}};return await Wr.getAxiosInstance().get(oe,se)}),Le(Wr,"POST",async({url:re,data:te={},mock:ne=!1,useQueryParams:ie=!0})=>{const oe=mockPath(re,ne),se={params:{useQueryParams:ie},headers:{"Content-Type":"text/plain"}};return await Wr.getAxiosInstance().post(oe,te,se)}),Le(Wr,"PUT",async({url:re,data:te={},mock:ne=!1,useQueryParams:ie=!0})=>{const oe=mockPath(re,ne),se={params:{useQueryParams:ie}};return await Wr.getAxiosInstance().put(oe,te,se)}),Le(Wr,"PATCH",async({url:re,data:te={},mock:ne=!1,useQueryParams:ie=!0})=>{const oe=mockPath(re,ne),se={params:{useQueryParams:ie},headers:{"Content-Type":"text/plain"}};return await Wr.getAxiosInstance().patch(oe,te,se)}),Le(Wr,"DELETE",async({url:re,params:te={},mock:ne=!1,useQueryParams:ie=!0})=>{const oe=mockPath(re,ne),se={params:{useQueryParams:ie,...te}};return await Wr.getAxiosInstance().delete(oe,se)}),Le(Wr,"setupInterceptors",()=>{Wr.axiosInstance.interceptors.request.use(re=>{const{useQueryParams:te,...ne}=re.params||{};return te?re.params={...ne,data:Wr.getEncodeParams()}:re.params=ne,re.data&&(re.data=convertData(re.data,"camelCase-to-snake_case")),re}),Wr.axiosInstance.interceptors.response.use(re=>Wr.handleResponse(re),re=>Wr.handleError(re))}),Le(Wr,"handleResponse",re=>{const te=re.status===202,ne=convertData(re.data,"snake_case-to-camelCase");return te?{...ne,statusCode:re.status}:ne}),Le(Wr,"handleError",re=>{var ie;const te=convertData((ie=re.response)==null?void 0:ie.data,"snake_case-to-camelCase"),ne={error:(te==null?void 0:te.error)||"UNKNOWN_ERROR",internalTerm:te==null?void 0:te.internalTerm,message:(te==null?void 0:te.message)||AstroPayI18n.translate("generic_error"),description:te==null?void 0:te.description};return Promise.reject(ne)}),Le(Wr,"getEncodeParams",()=>{const re={app_name:Wr.config.appName,app_id:AstroPayCore.getToken(),environment:AstroPayConfig.getEnvironment(),platform:getOperatingSystem(),version:AstroPayConfig.getRuntimeConfig().VERSION};return encodeData(re)});let HttpClient=Wr;const END_POINTS={createPayment:"/v1/web/payments",paymentDetails:"/v1/web/payments/:paymentExternalId/detail",identifyUser:"/v1/web/payments/:paymentExternalId/identify-user",paymentStatus:"/v1/web/payments/:paymentExternalId/status",paymentMethodDetail:"/v1/web/payments/:paymentExternalId/payment-methods/:methodCode",pciToken:"v1/web/payments/pci/token"};class CardService{}Le(CardService,"getPciToken",async re=>{try{return await HttpClient.POST({url:END_POINTS.pciToken,data:re})}catch(te){return DataDogTracker.trackError(te),Promise.reject(te)}});const formatCardExpiryDate=ee=>{if(!ee)return"";const te=ee.replace(/\s+/g,"").split("/");if(te.length!==2)return"";let[ne,ie]=te;if(ne.length===1&&(ne="0"+ne),ie.length===2){const oe=new Date().getFullYear(),se=Math.floor(oe/100)*100;ie=String(se+Number(ie))}return`${ne}/${ie}`},APTokenizerVersion="v1.1.3";class CardApService{constructor(re,te){Le(this,"collector");Le(this,"form");Le(this,"fields");Le(this,"callback");this.fields=re,this.callback=te}async init(re){try{const te=await sr({environment:this.getCardEnvironment(),version:APTokenizerVersion});this.collector=te.initCollector(),this.form=this.collector.createForm(ne=>{if(this.callback){const ie=Object.entries(ne).reduce((oe,[se,ae])=>(oe[se]={isValid:ae.isValid||!ae.isDirty&&!ae.isTouched,isTouched:ae.isTouched||ae.isDirty},oe),{});this.callback(ie)}}),this.fields.forEach(({field:ne,...ie})=>{this.form.field(ne,ie)}),re==null||re()}catch(te){throw console.error(te),te}}async tokenizeCard(re,te,ne){try{const{accessToken:ie}=await CardService.getPciToken(re);return this.form.accessToken=ie,await new Promise(oe=>{this.form.submit(se=>{const ae={cardNumberTkn:se.card_number.value,cvvToken:se.card_cvc.value,holderName:se.card_holder.value,expirationDate:formatCardExpiryDate(se.card_exp.value),firstSixDigits:se.card_number.details.bin.substring(0,6),lastFourDigits:se.card_number.details.lastFour,brand:se.card_number.details.brand||"unknown"};te(ae),oe()},()=>{ne(new Error(AstroPayI18n.translate("card_tokenization_error")))})})}catch{ne(new Error(AstroPayI18n.translate("generic_error")))}}unmount(){var re;(re=this.form)==null||re.tearDown()}getCardEnvironment(){return AstroPayConfig.getEnvironment()==="production"?"production":"sandbox"}}var ECardPayStatus=(ee=>(ee.PENDING="PENDING",ee.REJECTED="REJECTED",ee))(ECardPayStatus||{});class PaymentService{}Le(PaymentService,"postCreatePayment",async(re,te)=>{try{const ne=await HttpClient.POST({data:re,url:END_POINTS.createPayment});return DataDogTracker.trackEvent("ap_cl_payment_created",{...re,initializer:te}),ne}catch(ne){return DataDogTracker.trackError(ne),Promise.reject(ne)}}),Le(PaymentService,"getPaymentDetails",async(re,te)=>{try{const ne=await HttpClient.GET({url:buildPathWithParams(END_POINTS.paymentDetails,{paymentExternalId:re})});return DataDogTracker.trackEvent("ap_cl_payment_details",{paymentExternalId:re,initializer:te}),ne}catch(ne){return DataDogTracker.trackError(ne),Promise.reject(ne)}}),Le(PaymentService,"postIdentifyUser",async(re,te)=>{try{const ne=await HttpClient.POST({data:te,url:buildPathWithParams(END_POINTS.identifyUser,{paymentExternalId:re})});return DataDogTracker.trackEvent("ap_cl_user_identified",{hasAccount:ne.user.hasAccount,user:ne.user.otherUserData}),ne}catch(ne){return DataDogTracker.trackError(ne),Promise.reject(ne)}}),Le(PaymentService,"getPaymentStatus",async re=>{try{return await HttpClient.GET({url:buildPathWithParams(END_POINTS.paymentStatus,{paymentExternalId:re})})}catch(te){return Promise.reject(te)}}),Le(PaymentService,"getPollingRequest",async re=>{try{const te=re.replace(/^\/?api\//,"");return await HttpClient.GET({url:te})}catch(te){return Promise.reject(te)}}),Le(PaymentService,"postGenericPayment",async(re,te,ne)=>{try{const ie=re.replace(/^\/?api\//,"");return await HttpClient.POST({url:buildPathWithParams(ie,{paymentExternalId:te}),data:ne})}catch(ie){return Promise.reject(ie)}});var EPollingStatus=(ee=>(ee.ACCEPTED="ACCEPTED",ee.FINISHED="FINISHED",ee))(EPollingStatus||{});class PaymentMethodsService{}Le(PaymentMethodsService,"getPaymentMethodDetail",async re=>{try{return await HttpClient.GET({url:buildPathWithParams(END_POINTS.paymentMethodDetail,{paymentExternalId:re.paymentExternalId,methodCode:re.methodCode})})}catch(te){return Promise.reject(te)}});class PollingService{constructor(re,te,ne,ie){Le(this,"pollingTimeout",null);Le(this,"isPollingActive",!1);Le(this,"remainingAttempts");this.pollingAcceptedData=re,this.onWaitingInfo=te,this.onFinished=ne,this.onError=ie,this.remainingAttempts=re.pollingMetadata.remainingHits,this.validatePollingData()}startPolling(){var re;if(this.pollingAcceptedData.pollingMetadata.remainingHits<=0){this.onError(new Error("Polling attempts exhausted"));return}this.isPollingActive=!0,(re=this.pollingAcceptedData.waitingInfo)!=null&&re.text&&this.onWaitingInfo&&this.onWaitingInfo(this.pollingAcceptedData.waitingInfo.text),this.executePoll()}stopPolling(){this.isPollingActive=!1,this.pollingTimeout&&(clearTimeout(this.pollingTimeout),this.pollingTimeout=null)}validatePollingData(){if(!this.pollingAcceptedData.pollingMetadata.pollingUrl)throw new Error("Invalid polling URL");if(this.pollingAcceptedData.pollingMetadata.nextHitIn<=0)throw new Error("Invalid polling interval")}executePoll(){this.isPollingActive&&(this.pollingTimeout=setTimeout(()=>{this.handlePolling().catch(re=>{this.onError(re),this.stopPolling()})},this.getPollingInterval()))}async handlePolling(){const re=await PaymentService.getPollingRequest(this.pollingAcceptedData.pollingMetadata.pollingUrl);re.statusCode===202&&re.pollingStatus===EPollingStatus.ACCEPTED?this.handleAccepted(re):this.handleFinished(re)}handleAccepted(re){if(this.isPollingActive){if(this.remainingAttempts=re.pollingMetadata.remainingHits,this.pollingAcceptedData=re,this.remainingAttempts<=0){const te=re.timeoutInfo.text;this.stopPolling(),this.onError(new Error(te));return}this.executePoll()}}handleFinished(re){this.stopPolling(),this.onFinished(re)}getPollingInterval(){return this.pollingAcceptedData.pollingMetadata.nextHitIn}}const CARD_STYLES=(ee,re)=>({fontSize:"16px",lineHeight:"24px",color:ee,backgroundColor:"inherit",fontFamily:`${re.fontFamily}, sans-serif;`}),getCardPaymentMethodStyles=(ee,{error:re=!1,disabled:te=!1})=>css`
|
|
572
|
+
`+oe):ne.stack=oe}catch{}}throw ne}}_request(re,te){typeof re=="string"?(te=te||{},te.url=re):te=re||{},te=mergeConfig$1(this.defaults,te);const{transitional:ne,paramsSerializer:ie,headers:oe}=te;ne!==void 0&&validator.assertOptions(ne,{silentJSONParsing:validators.transitional(validators.boolean),forcedJSONParsing:validators.transitional(validators.boolean),clarifyTimeoutError:validators.transitional(validators.boolean)},!1),ie!=null&&(utils$3.isFunction(ie)?te.paramsSerializer={serialize:ie}:validator.assertOptions(ie,{encode:validators.function,serialize:validators.function},!0)),te.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?te.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:te.allowAbsoluteUrls=!0),validator.assertOptions(te,{baseUrl:validators.spelling("baseURL"),withXsrfToken:validators.spelling("withXSRFToken")},!0),te.method=(te.method||this.defaults.method||"get").toLowerCase();let se=oe&&utils$3.merge(oe.common,oe[te.method]);oe&&utils$3.forEach(["delete","get","head","post","put","patch","common"],pe=>{delete oe[pe]}),te.headers=AxiosHeaders$1.concat(se,oe);const ae=[];let ue=!0;this.interceptors.request.forEach(function(ge){typeof ge.runWhen=="function"&&ge.runWhen(te)===!1||(ue=ue&&ge.synchronous,ae.unshift(ge.fulfilled,ge.rejected))});const ce=[];this.interceptors.response.forEach(function(ge){ce.push(ge.fulfilled,ge.rejected)});let le,de=0,fe;if(!ue){const pe=[dispatchRequest.bind(this),void 0];for(pe.unshift(...ae),pe.push(...ce),fe=pe.length,le=Promise.resolve(te);de<fe;)le=le.then(pe[de++],pe[de++]);return le}fe=ae.length;let he=te;for(;de<fe;){const pe=ae[de++],ge=ae[de++];try{he=pe(he)}catch(me){ge.call(this,me);break}}try{le=dispatchRequest.call(this,he)}catch(pe){return Promise.reject(pe)}for(de=0,fe=ce.length;de<fe;)le=le.then(ce[de++],ce[de++]);return le}getUri(re){re=mergeConfig$1(this.defaults,re);const te=buildFullPath(re.baseURL,re.url,re.allowAbsoluteUrls);return buildURL(te,re.params,re.paramsSerializer)}};utils$3.forEach(["delete","get","head","options"],function ee(re){Axios$1.prototype[re]=function(te,ne){return this.request(mergeConfig$1(ne||{},{method:re,url:te,data:(ne||{}).data}))}}),utils$3.forEach(["post","put","patch"],function ee(re){function te(ne){return function(oe,se,ae){return this.request(mergeConfig$1(ae||{},{method:re,headers:ne?{"Content-Type":"multipart/form-data"}:{},url:oe,data:se}))}}Axios$1.prototype[re]=te(),Axios$1.prototype[re+"Form"]=te(!0)});let CancelToken$1=class Lo{constructor(re){if(typeof re!="function")throw new TypeError("executor must be a function.");let te;this.promise=new Promise(function(oe){te=oe});const ne=this;this.promise.then(ie=>{if(!ne._listeners)return;let oe=ne._listeners.length;for(;oe-- >0;)ne._listeners[oe](ie);ne._listeners=null}),this.promise.then=ie=>{let oe;const se=new Promise(ae=>{ne.subscribe(ae),oe=ae}).then(ie);return se.cancel=function(){ne.unsubscribe(oe)},se},re(function(oe,se,ae){ne.reason||(ne.reason=new CanceledError$1(oe,se,ae),te(ne.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(re){if(this.reason){re(this.reason);return}this._listeners?this._listeners.push(re):this._listeners=[re]}unsubscribe(re){if(!this._listeners)return;const te=this._listeners.indexOf(re);te!==-1&&this._listeners.splice(te,1)}toAbortSignal(){const re=new AbortController,te=ne=>{re.abort(ne)};return this.subscribe(te),re.signal.unsubscribe=()=>this.unsubscribe(te),re.signal}static source(){let re;return{token:new Lo(function(ie){re=ie}),cancel:re}}};function spread$1(ee){return function(te){return ee.apply(null,te)}}function isAxiosError$1(ee){return utils$3.isObject(ee)&&ee.isAxiosError===!0}const HttpStatusCode$1={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(HttpStatusCode$1).forEach(([ee,re])=>{HttpStatusCode$1[re]=ee});function createInstance(ee){const re=new Axios$1(ee),te=bind(Axios$1.prototype.request,re);return utils$3.extend(te,Axios$1.prototype,re,{allOwnKeys:!0}),utils$3.extend(te,re,null,{allOwnKeys:!0}),te.create=function(ie){return createInstance(mergeConfig$1(ee,ie))},te}const axios=createInstance(defaults);axios.Axios=Axios$1,axios.CanceledError=CanceledError$1,axios.CancelToken=CancelToken$1,axios.isCancel=isCancel$1,axios.VERSION=VERSION$1,axios.toFormData=toFormData$1,axios.AxiosError=AxiosError$1,axios.Cancel=axios.CanceledError,axios.all=function ee(re){return Promise.all(re)},axios.spread=spread$1,axios.isAxiosError=isAxiosError$1,axios.mergeConfig=mergeConfig$1,axios.AxiosHeaders=AxiosHeaders$1,axios.formToJSON=ee=>formDataToJSON(utils$3.isHTMLForm(ee)?new FormData(ee):ee),axios.getAdapter=adapters.getAdapter,axios.HttpStatusCode=HttpStatusCode$1,axios.default=axios;const{Axios,AxiosError,CanceledError,isCancel,CancelToken,VERSION,all,Cancel,isAxiosError,spread,toFormData,AxiosHeaders,HttpStatusCode,formToJSON,getAdapter,mergeConfig}=axios,mockPath=(ee,re)=>{const te=AstroPayConfig.getRuntimeConfig().MODE==="test";return re&&te?`http://localhost:3333${ee.startsWith("/")?ee:`/${ee}`}`:ee},Wr=class Wr{static getAxiosInstance(){if(!this.axiosInstance)throw new Error("AstroPay Payments Library: Not initialized.");return this.axiosInstance}};Le(Wr,"axiosInstance"),Le(Wr,"config"),Le(Wr,"init",re=>{Wr.config=re,Wr.axiosInstance=axios.create({baseURL:re.baseURL,timeout:re.timeout??5e3,withCredentials:!0,headers:{"Accept-Language":AstroPayI18n.getCurrent(),...re.headers}}),Wr.setupInterceptors()}),Le(Wr,"GET",async({url:re,params:te={},mock:ne=!1,useQueryParams:ie=!0})=>{const oe=mockPath(re,ne),se={params:{useQueryParams:ie,...te}};return await Wr.getAxiosInstance().get(oe,se)}),Le(Wr,"POST",async({url:re,data:te={},mock:ne=!1,useQueryParams:ie=!0})=>{const oe=mockPath(re,ne),se={params:{useQueryParams:ie},headers:{"Content-Type":"text/plain"}};return await Wr.getAxiosInstance().post(oe,te,se)}),Le(Wr,"PUT",async({url:re,data:te={},mock:ne=!1,useQueryParams:ie=!0})=>{const oe=mockPath(re,ne),se={params:{useQueryParams:ie}};return await Wr.getAxiosInstance().put(oe,te,se)}),Le(Wr,"PATCH",async({url:re,data:te={},mock:ne=!1,useQueryParams:ie=!0})=>{const oe=mockPath(re,ne),se={params:{useQueryParams:ie},headers:{"Content-Type":"text/plain"}};return await Wr.getAxiosInstance().patch(oe,te,se)}),Le(Wr,"DELETE",async({url:re,params:te={},mock:ne=!1,useQueryParams:ie=!0})=>{const oe=mockPath(re,ne),se={params:{useQueryParams:ie,...te}};return await Wr.getAxiosInstance().delete(oe,se)}),Le(Wr,"setupInterceptors",()=>{Wr.axiosInstance.interceptors.request.use(re=>{const{useQueryParams:te,...ne}=re.params||{};return te?re.params={...ne,data:Wr.getEncodeParams()}:re.params=ne,re.data&&(re.data=convertData(re.data,"camelCase-to-snake_case")),re}),Wr.axiosInstance.interceptors.response.use(re=>Wr.handleResponse(re),re=>Wr.handleError(re))}),Le(Wr,"handleResponse",re=>{const te=re.status===202,ne=convertData(re.data,"snake_case-to-camelCase");return te?{...ne,statusCode:re.status}:ne}),Le(Wr,"handleError",re=>{var ie;const te=convertData((ie=re.response)==null?void 0:ie.data,"snake_case-to-camelCase"),ne={error:(te==null?void 0:te.error)||"UNKNOWN_ERROR",internalTerm:te==null?void 0:te.internalTerm,message:(te==null?void 0:te.message)||AstroPayI18n.translate("generic_error"),description:te==null?void 0:te.description};return Promise.reject(ne)}),Le(Wr,"getEncodeParams",()=>{const re={app_name:Wr.config.appName,app_id:AstroPayCore.getToken(),environment:AstroPayConfig.getEnvironment(),platform:getOperatingSystem(),version:AstroPayConfig.getRuntimeConfig().VERSION};return encodeData(re)});let HttpClient=Wr;const END_POINTS={createPayment:"/v1/web/payments",paymentDetails:"/v1/web/payments/:paymentExternalId/detail",identifyUser:"/v1/web/payments/:paymentExternalId/identify-user",paymentStatus:"/v1/web/payments/:paymentExternalId/status",paymentMethodDetail:"/v1/web/payments/:paymentExternalId/payment-methods/:methodCode",pciToken:"v1/web/payments/pci/token"};class CardService{}Le(CardService,"getPciToken",async re=>{try{return await HttpClient.POST({url:END_POINTS.pciToken,data:re})}catch(te){return DataDogTracker.trackError(te),Promise.reject(te)}});const formatCardExpiryDate=ee=>{if(!ee)return"";const te=ee.replace(/\s+/g,"").split("/");if(te.length!==2)return"";let[ne,ie]=te;if(ne.length===1&&(ne="0"+ne),ie.length===2){const oe=new Date().getFullYear(),se=Math.floor(oe/100)*100;ie=String(se+Number(ie))}return`${ne}/${ie}`},APTokenizerVersion="v1.1.3";class CardApService{constructor(re,te){Le(this,"collector");Le(this,"form");Le(this,"fields");Le(this,"callback");this.fields=re,this.callback=te}async init(re){try{const te=await sr({environment:this.getCardEnvironment(),version:APTokenizerVersion});this.collector=te.initCollector(),this.form=this.collector.createForm(ne=>{if(this.callback){const ie=Object.entries(ne).reduce((oe,[se,ae])=>(oe[se]={isValid:ae.isValid||!ae.isDirty&&!ae.isTouched,isTouched:ae.isTouched||ae.isDirty},oe),{});this.callback(ie)}}),this.fields.forEach(({field:ne,...ie})=>{this.form.field(ne,ie)}),re==null||re()}catch(te){throw console.error(te),te}}async tokenizeCard(re,te,ne){try{const{accessToken:ie}=await CardService.getPciToken(re);return this.form.accessToken=ie,await new Promise(oe=>{this.form.submit(se=>{const ae={cardNumberTkn:se.card_number.value,cvvToken:se.card_cvc.value,holderName:se.card_holder.value,expirationDate:formatCardExpiryDate(se.card_exp.value),firstSixDigits:se.card_number.details.bin.substring(0,6),lastFourDigits:se.card_number.details.lastFour,brand:se.card_number.details.brand||"unknown"};te(ae),oe()},()=>{ne(new Error(AstroPayI18n.translate("card_tokenization_error")))})})}catch{ne(new Error(AstroPayI18n.translate("generic_error")))}}unmount(){var re;(re=this.form)==null||re.tearDown()}getCardEnvironment(){return AstroPayConfig.getEnvironment()==="production"?"production":"sandbox"}}var ECardPayStatus=(ee=>(ee.PENDING="PENDING",ee.REJECTED="REJECTED",ee))(ECardPayStatus||{});class PaymentService{}Le(PaymentService,"postCreatePayment",async(re,te)=>{try{const ne=await HttpClient.POST({data:re,url:END_POINTS.createPayment});return DataDogTracker.trackEvent("ap_cl_payment_created",{...re,initializer:te}),ne}catch(ne){return DataDogTracker.trackError(ne),Promise.reject(ne)}}),Le(PaymentService,"getPaymentDetails",async(re,te)=>{try{const ne=await HttpClient.GET({url:buildPathWithParams(END_POINTS.paymentDetails,{paymentExternalId:re})});return DataDogTracker.trackEvent("ap_cl_payment_details",{paymentExternalId:re,initializer:te}),ne}catch(ne){return DataDogTracker.trackError(ne),Promise.reject(ne)}}),Le(PaymentService,"postIdentifyUser",async(re,te)=>{try{const ne=await HttpClient.POST({data:te,url:buildPathWithParams(END_POINTS.identifyUser,{paymentExternalId:re})});return DataDogTracker.trackEvent("ap_cl_user_identified",{hasAccount:ne.user.hasAccount,user:ne.user.otherUserData}),ne}catch(ne){return DataDogTracker.trackError(ne),Promise.reject(ne)}}),Le(PaymentService,"getPaymentStatus",async re=>{try{return await HttpClient.GET({url:buildPathWithParams(END_POINTS.paymentStatus,{paymentExternalId:re})})}catch(te){return Promise.reject(te)}}),Le(PaymentService,"getPollingRequest",async re=>{try{const te=re.replace(/^\/?api\//,"");return await HttpClient.GET({url:te})}catch(te){return Promise.reject(te)}}),Le(PaymentService,"postGenericPayment",async(re,te,ne)=>{try{const ie=re.replace(/^\/?api\//,"");return await HttpClient.POST({url:buildPathWithParams(ie,{paymentExternalId:te}),data:ne})}catch(ie){return Promise.reject(ie)}});var EPollingStatus=(ee=>(ee.ACCEPTED="ACCEPTED",ee.FINISHED="FINISHED",ee))(EPollingStatus||{});class PaymentMethodsService{}Le(PaymentMethodsService,"getPaymentMethodDetail",async re=>{try{return await HttpClient.GET({url:buildPathWithParams(END_POINTS.paymentMethodDetail,{paymentExternalId:re.paymentExternalId,methodCode:re.methodCode})})}catch(te){return Promise.reject(te)}});class PollingService{constructor(re,te,ne,ie){Le(this,"pollingTimeout",null);Le(this,"isPollingActive",!1);Le(this,"remainingAttempts");this.pollingAcceptedData=re,this.onWaitingInfo=te,this.onFinished=ne,this.onError=ie,this.remainingAttempts=re.pollingMetadata.remainingHits,this.validatePollingData()}startPolling(){var re;if(this.pollingAcceptedData.pollingMetadata.remainingHits<=0){this.onError(new Error("Polling attempts exhausted"));return}this.isPollingActive=!0,(re=this.pollingAcceptedData.waitingInfo)!=null&&re.text&&this.onWaitingInfo&&this.onWaitingInfo(this.pollingAcceptedData.waitingInfo.text),this.executePoll()}stopPolling(){this.isPollingActive=!1,this.pollingTimeout&&(clearTimeout(this.pollingTimeout),this.pollingTimeout=null)}validatePollingData(){if(!this.pollingAcceptedData.pollingMetadata.pollingUrl)throw new Error("Invalid polling URL");if(this.pollingAcceptedData.pollingMetadata.nextHitIn<=0)throw new Error("Invalid polling interval")}executePoll(){this.isPollingActive&&(this.pollingTimeout=setTimeout(()=>{this.handlePolling().catch(re=>{this.onError(re),this.stopPolling()})},this.getPollingInterval()))}async handlePolling(){const re=await PaymentService.getPollingRequest(this.pollingAcceptedData.pollingMetadata.pollingUrl);re.statusCode===202&&re.pollingStatus===EPollingStatus.ACCEPTED?this.handleAccepted(re):this.handleFinished(re)}handleAccepted(re){if(this.isPollingActive){if(this.remainingAttempts=re.pollingMetadata.remainingHits,this.pollingAcceptedData=re,this.remainingAttempts<=0){this.stopPolling(),this.onError(re.timeoutInfo);return}this.executePoll()}}handleFinished(re){this.stopPolling(),this.onFinished(re)}getPollingInterval(){return this.pollingAcceptedData.pollingMetadata.nextHitIn}}const CARD_STYLES=(ee,re)=>({fontSize:"16px",lineHeight:"24px",color:ee,backgroundColor:"inherit",fontFamily:`${re.fontFamily}, sans-serif;`}),getCardPaymentMethodStyles=(ee,{error:re=!1,disabled:te=!1})=>css`
|
|
573
573
|
display: flex;
|
|
574
574
|
flex-direction: column;
|
|
575
575
|
gap: 12px;
|
|
@@ -640,7 +640,7 @@ Body:`)).call(gr,Oi()(vr)));var $r=new XMLHttpRequest;$r.open(De._method||ue.Pos
|
|
|
640
640
|
}
|
|
641
641
|
`,getCardFieldStyles=()=>css`
|
|
642
642
|
width: 100%;
|
|
643
|
-
`;class CardField extends Component{constructor({id:te,label:ne,initialHelperText:ie,isValid:oe=!0}){super({tag:"div",styles:()=>getCardFieldStyles()});Le(this,"inputContainer");Le(this,"labelTextElement",null);Le(this,"helperTextElement",null);Le(this,"id");this.id=te;const se=inputStyle(!oe);if(this.inputContainer=document.createElement("div"),this.inputContainer.classList.add("input-container"),ne){const ue=document.createElement("label");this.labelTextElement=new Typography({text:ne,size:se.label.size,weight:se.label.weight,color:se.label.color}).element,ue.append(this.labelTextElement),ue.htmlFor=te,this.inputContainer.append(this.labelTextElement)}const ae=document.createElement("div");ae.id=te,ae.classList.add("form-field"),this.inputContainer.append(ae),ie&&(this.helperTextElement=new Typography({text:ie,size:se.helperText.size,weight:se.helperText.weight,color:se.helperText.color}).element,this.inputContainer.append(this.helperTextElement)),this.element.append(this.inputContainer)}setHelperText(te,ne=!0){const ie=inputStyle(!ne);this.helperTextElement||(this.helperTextElement=new Typography({text:te,size:ie.helperText.size,weight:ie.helperText.weight,color:ie.helperText.color}).element,this.inputContainer.append(this.helperTextElement)),this.helperTextElement.textContent=te,this.helperTextElement.style.color=ie.helperText.color}setValid(te){if(this.labelTextElement){const ie=inputStyle(!te);this.labelTextElement.style.color=ie.label.color}const ne=this.element.querySelector(`#${this.id}`);ne&&ne.classList.toggle("card-input-error",!te)}resetValidation(){this.setValid(!0),this.setHelperText("",!0)}}const APCardsFields=(ee,re,te)=>[{field:"#cc-holder",type:"text",name:"card_holder",placeholder:"card_holder_placeholder",autocomplete:"off",validations:["required","/^[a-zA-Z ]{0,200}$/"],styles:CARD_STYLES(ee,te)},{field:"#cc-number",type:"card-number",name:"card_number",placeholder:"4111 1111 1111 1111",autocomplete:"off",validations:["required","validCardNumber"],styles:CARD_STYLES(ee,te)},{field:"#cc-expiration-date",type:"card-expiration-date",name:"card_exp",lengthYear:re==="MM/YY"?2:4,placeholder:re,autocomplete:"off",validations:["required","validCardExpirationDate"],styles:CARD_STYLES(ee,te)},{field:"#cc-cvc",type:"card-security-code",name:"card_cvc",placeholder:"123",autocomplete:"off",validations:["required","/^\\d{3,4}$/"],styles:CARD_STYLES(ee,te)}],EMPTY_FORM_DATA={card_holder:{isValid:!0,isTouched:!1},card_number:{isValid:!0,isTouched:!1},card_exp:{isValid:!0,isTouched:!1},card_cvc:{isValid:!0,isTouched:!1}},DEFAULT_EXPIRATION_DATE_FORMAT="MM/YY";class CardPaymentMethod extends Component{constructor(te){super({tag:"div",styles:ne=>getCardPaymentMethodStyles(ne,{error:!1,disabled:!1})});Le(this,"componentProps");Le(this,"loadingWrapper");Le(this,"btnPay",null);Le(this,"cardManager",null);Le(this,"cardHolderInput",null);Le(this,"cardNumberInput",null);Le(this,"cardExpInput",null);Le(this,"cardCvvInput",null);Le(this,"requiredFieldsForm",null);Le(this,"formState",EMPTY_FORM_DATA);Le(this,"isFormTemplateValid",!1);Le(this,"pollingService",null);this.componentProps={...te,showPaymentSummary:te.showPaymentSummary??!0,expirationDateFormat:te.expirationDateFormat??DEFAULT_EXPIRATION_DATE_FORMAT},this.loadingWrapper=this.createLoadingWrapper(AstroPayI18n.translate("hold_on")),this.element.append(this.loadingWrapper),sessionStorage.getItem(EStorageKey.SESSION_ID)||sessionStorage.setItem(EStorageKey.SESSION_ID,uuid()),this.fetchPaymentMethodDetail()}async fetchPaymentMethodDetail(){var te,ne;try{const ie=await PaymentMethodsService.getPaymentMethodDetail({paymentExternalId:this.componentProps.paymentExternalId,methodCode:this.componentProps.paymentMethod.code});this.renderCardSection(ie.fields)}catch(ie){const oe=ie;(ne=(te=this.componentProps)==null?void 0:te.onError)==null||ne.call(te),this.showErrorMessage(oe.message)}finally{this.loadingWrapper.remove()}}renderCardSection(te){const{amount:ne,currency:ie,showPaymentSummary:oe,expirationDateFormat:se}=this.componentProps;if(oe){const ue=new PaymentSummary({amount:ne,currency:ie}).element;this.element.append(ue)}this.cardHolderInput=new CardField({id:"cc-holder",label:AstroPayI18n.translate("card_holder_label")}),this.cardNumberInput=new CardField({id:"cc-number",label:AstroPayI18n.translate("card_number")});const ae=document.createElement("div");ae.classList.add("row-container"),this.cardExpInput=new CardField({id:"cc-expiration-date",label:AstroPayI18n.translate("card_exp_date")}),this.cardCvvInput=new CardField({id:"cc-cvc",label:"CVV"}),ae.append(this.cardExpInput.element,this.cardCvvInput.element),this.element.append(this.cardHolderInput.element,this.cardNumberInput.element,ae),this.cardManager=new CardApService(APCardsFields(defineInputStyles().textColor,se??DEFAULT_EXPIRATION_DATE_FORMAT,ThemeManager.getStyles()).map(ue=>({...ue,placeholder:AstroPayI18n.translate(ue.placeholder)})),this.handleFormStateChange.bind(this)),this.cardManager.init(),te&&te.length>0&&this.renderRequiredFields(te),this.btnPay=new Button({text:AstroPayI18n.translate("pay_amount",{amount:formatAmountCurrency(this.componentProps.amount,this.componentProps.currency,AstroPayConfig.getCurrencyMode())}),onClick:()=>{this.handleSubmit()},isFullWidth:!0,iconLeft:"lock_line",isDisabled:!0}),this.element.append(this.btnPay.element)}renderRequiredFields(te){this.requiredFieldsForm=new FormTemplate({title:AstroPayI18n.translate("additional_information"),requiredFields:te}),this.requiredFieldsForm.setValidationChangeHandler(ne=>{this.isFormTemplateValid=ne,this.updateSubmitButton()}),this.element.append(this.requiredFieldsForm.element)}handleFormStateChange(te){this.formState=te,this.updateInputsValidation(),this.updateSubmitButton()}updateInputsValidation(){[{input:this.cardHolderInput,...this.formState.card_holder},{input:this.cardNumberInput,...this.formState.card_number},{input:this.cardExpInput,...this.formState.card_exp},{input:this.cardCvvInput,...this.formState.card_cvc}].forEach(({input:ne,isValid:ie})=>{ne==null||ne.setValid(ie),ne==null||ne.setHelperText(ie?"":AstroPayI18n.translate("invalid_field"),ie)})}updateSubmitButton(){var ie;const ne=Object.values(this.formState).every(oe=>oe.isValid&&oe.isTouched)&&(this.requiredFieldsForm?this.isFormTemplateValid:!0);(ie=this.btnPay)==null||ie.setDisabled(!ne)}async handleSubmit(){var te,ne,ie,oe,se,ae,ue;try{(te=this.btnPay)==null||te.setLoading(!0);const ce=await this.handleTokenizeCard(),le={paymentMethods:[{methodCode:this.componentProps.paymentMethod.code,currency:this.componentProps.currency,amount:this.componentProps.amount,user:{sessionId:sessionStorage.getItem(EStorageKey.SESSION_ID)||"",...(ne=this.requiredFieldsForm)==null?void 0:ne.getFormData()},cardData:ce}]};if((ie=this.componentProps.paymentMethod)!=null&&ie.uri){const{status:de,reason:fe}=await PaymentService.postGenericPayment(this.componentProps.paymentMethod.uri,this.componentProps.paymentExternalId,le);if(de===ECardPayStatus.PENDING)await this.checkPaymentStatus(),(oe=this.btnPay)==null||oe.setLoading(!1),(se=this.btnPay)==null||se.setDisabled(!0);else throw new Error(fe||AstroPayI18n.translate("generic_error"))}else throw new Error(AstroPayI18n.translate("generic_error"))}catch(ce){const le=ce;console.error(le.message),this.showErrorMessage(le.message),(ue=(ae=this.componentProps)==null?void 0:ae.onError)==null||ue.call(ae),this.renderRetryButton()}}async handleTokenizeCard(){return new Promise((te,ne)=>{var ae;if(!this.cardManager)return;const{document_type:ie,document_number:oe}=((ae=this.requiredFieldsForm)==null?void 0:ae.getFormData())??{},se={documentType:ie??"",documentNumber:oe??"",sessionId:sessionStorage.getItem(EStorageKey.SESSION_ID)||""};this.cardManager.tokenizeCard(se,ue=>te(ue),ue=>{ne(ue)})})}showErrorMessage(te){this.element.innerHTML="";const ne=new Typography({text:te,size:ThemeManager.getFontScale().xSmall,color:ThemeManager.getStyles().messages.error.textColor}).element;this.element.append(ne)}async checkPaymentStatus(){try{const te=await PaymentService.getPaymentStatus(this.componentProps.paymentExternalId);te.pollingStatus===EPollingStatus.ACCEPTED?this.initializePollingService(te):te.pollingStatus===EPollingStatus.FINISHED&&this.handlePaymentSuccess(te)}catch(te){const ne=te;this.showErrorMessage(ne.message),this.stopPolling()}}initializePollingService(te){this.pollingService=new PollingService(te,ne=>this.showWaitingInfo(ne),ne=>this.handlePaymentSuccess(ne),ne=>this.handlePollingError(ne)),this.pollingService.startPolling()}stopPolling(){this.pollingService&&(this.pollingService.stopPolling(),this.pollingService=null)}handlePollingError(te){var ie,oe;const ne=te;this.showErrorMessage(ne.message),this.stopPolling(),(oe=(ie=this.componentProps)==null?void 0:ie.onError)==null||oe.call(ie),this.renderRetryButton()}showWaitingInfo(te){this.element.innerHTML="";const ne=this.createLoadingWrapper(te);ne.style.minHeight="400px",this.element.append(ne)}handlePaymentSuccess(te){var oe,se;const ne=[],ie=new Status$1({type:"success",title:(oe=te.data.successSection)==null?void 0:oe.title,description:(se=te.data.successSection)==null?void 0:se.description}).element;ne.push(ie),this.componentProps.onSuccess?this.componentProps.onSuccess(ne):(this.element.innerHTML="",ne.forEach(ae=>this.element.append(ae)))}createLoadingWrapper(te){const ne=document.createElement("div");ne.classList.add("loading-wrapper");const ie=new Loading({size:100,variant:"fetching",color:ThemeManager.getStyles().primaryColor}).element,oe=new Typography({text:te,size:"base",lineHeight:30,weight:600,align:"center"}).element;return ne.append(ie,oe),ne}renderRetryButton(){const te=document.createElement("div");te.classList.add("center-row");const ne=new Button({text:AstroPayI18n.translate("try_again"),variant:"text",size:"small",iconRight:"refresh_2_fill",onClick:()=>{this.element.innerHTML="",this.element.append(this.loadingWrapper),this.fetchPaymentMethodDetail()}}).element;te.append(ne),this.element.append(te)}destroy(){this.stopPolling(),this.element.remove()}}class AmplitudeAnalytics{constructor(){Le(this,"tracker",AmplitudeTracker);Le(this,"astroPayPaymentImpression",re=>{this.tracker.trackEvent(new AstroPayPaymentImpression({component_name:re}))});Le(this,"astroPayPaymentStarted",re=>{this.tracker.trackEvent(new AstroPayPaymentStarted({payment_external_id:re}))});Le(this,"astroPayPaymentClicked",re=>{this.tracker.trackEvent(new AstroPayPaymentClicked({payment_external_id:re}))});Le(this,"astroPayPaymentPhoneNumberEntered",re=>{this.tracker.trackEvent(new AstroPayPaymentPhoneNumberEntered({payment_external_id:re}))});Le(this,"astroPayPaymentUserIdentified",re=>{this.tracker.trackEvent(new AstroPayPaymentUserIdentified({payment_external_id:re}))});Le(this,"astroPayPaymentLinkCopied",re=>{this.tracker.trackEvent(new AstroPayPaymentLinkCopied({payment_external_id:re}))});Le(this,"astroPayPaymentCardClicked",re=>{this.tracker.trackEvent(new AstroPayPaymentCardClicked({payment_external_id:re}))})}}const AmplitudeAnalytics$1=new AmplitudeAnalytics;var EPaymentCode=(ee=>(ee.AP="AP",ee.IX="IX",ee.CREDIT_CARD="EC",ee.DEBIT_CARD="DR",ee.CW="CW",ee.DC="DC",ee.CC="CC",ee))(EPaymentCode||{});const CARDS_METHOD=["EC","DR","CW","DC","CC"],getAstroPayCardPaymentStyles=ee=>css`
|
|
643
|
+
`;class CardField extends Component{constructor({id:te,label:ne,initialHelperText:ie,isValid:oe=!0}){super({tag:"div",styles:()=>getCardFieldStyles()});Le(this,"inputContainer");Le(this,"labelTextElement",null);Le(this,"helperTextElement",null);Le(this,"id");this.id=te;const se=inputStyle(!oe);if(this.inputContainer=document.createElement("div"),this.inputContainer.classList.add("input-container"),ne){const ue=document.createElement("label");this.labelTextElement=new Typography({text:ne,size:se.label.size,weight:se.label.weight,color:se.label.color}).element,ue.append(this.labelTextElement),ue.htmlFor=te,this.inputContainer.append(this.labelTextElement)}const ae=document.createElement("div");ae.id=te,ae.classList.add("form-field"),this.inputContainer.append(ae),ie&&(this.helperTextElement=new Typography({text:ie,size:se.helperText.size,weight:se.helperText.weight,color:se.helperText.color}).element,this.inputContainer.append(this.helperTextElement)),this.element.append(this.inputContainer)}setHelperText(te,ne=!0){const ie=inputStyle(!ne);this.helperTextElement||(this.helperTextElement=new Typography({text:te,size:ie.helperText.size,weight:ie.helperText.weight,color:ie.helperText.color}).element,this.inputContainer.append(this.helperTextElement)),this.helperTextElement.textContent=te,this.helperTextElement.style.color=ie.helperText.color}setValid(te){if(this.labelTextElement){const ie=inputStyle(!te);this.labelTextElement.style.color=ie.label.color}const ne=this.element.querySelector(`#${this.id}`);ne&&ne.classList.toggle("card-input-error",!te)}resetValidation(){this.setValid(!0),this.setHelperText("",!0)}}const APCardsFields=(ee,re,te)=>[{field:"#cc-holder",type:"text",name:"card_holder",placeholder:"card_holder_placeholder",autocomplete:"off",validations:["required","/^[a-zA-Z ]{0,200}$/"],styles:CARD_STYLES(ee,te)},{field:"#cc-number",type:"card-number",name:"card_number",placeholder:"4111 1111 1111 1111",autocomplete:"off",validations:["required","validCardNumber"],styles:CARD_STYLES(ee,te)},{field:"#cc-expiration-date",type:"card-expiration-date",name:"card_exp",lengthYear:re==="MM/YY"?2:4,placeholder:re,autocomplete:"off",validations:["required","validCardExpirationDate"],styles:CARD_STYLES(ee,te)},{field:"#cc-cvc",type:"card-security-code",name:"card_cvc",placeholder:"123",autocomplete:"off",validations:["required","/^\\d{3,4}$/"],styles:CARD_STYLES(ee,te)}],EMPTY_FORM_DATA={card_holder:{isValid:!0,isTouched:!1},card_number:{isValid:!0,isTouched:!1},card_exp:{isValid:!0,isTouched:!1},card_cvc:{isValid:!0,isTouched:!1}},DEFAULT_EXPIRATION_DATE_FORMAT="MM/YY";class CardPaymentMethod extends Component{constructor(te){super({tag:"div",styles:ne=>getCardPaymentMethodStyles(ne,{error:!1,disabled:!1})});Le(this,"componentProps");Le(this,"loadingWrapper");Le(this,"btnPay",null);Le(this,"cardManager",null);Le(this,"cardHolderInput",null);Le(this,"cardNumberInput",null);Le(this,"cardExpInput",null);Le(this,"cardCvvInput",null);Le(this,"requiredFieldsForm",null);Le(this,"formState",EMPTY_FORM_DATA);Le(this,"isFormTemplateValid",!1);Le(this,"pollingService",null);this.componentProps={...te,showPaymentSummary:te.showPaymentSummary??!0,expirationDateFormat:te.expirationDateFormat??DEFAULT_EXPIRATION_DATE_FORMAT},this.loadingWrapper=this.createLoadingWrapper(AstroPayI18n.translate("hold_on")),this.element.append(this.loadingWrapper),sessionStorage.getItem(EStorageKey.SESSION_ID)||sessionStorage.setItem(EStorageKey.SESSION_ID,uuid()),this.fetchPaymentMethodDetail()}async fetchPaymentMethodDetail(){try{const te=await PaymentMethodsService.getPaymentMethodDetail({paymentExternalId:this.componentProps.paymentExternalId,methodCode:this.componentProps.paymentMethod.code});this.renderCardSection(te.fields)}catch(te){const ne=te;this.showErrorMessage(ne.description??ne.message)}finally{this.loadingWrapper.remove()}}renderCardSection(te){const{amount:ne,currency:ie,showPaymentSummary:oe,expirationDateFormat:se}=this.componentProps;if(oe){const ue=new PaymentSummary({amount:ne,currency:ie}).element;this.element.append(ue)}this.cardHolderInput=new CardField({id:"cc-holder",label:AstroPayI18n.translate("card_holder_label")}),this.cardNumberInput=new CardField({id:"cc-number",label:AstroPayI18n.translate("card_number")});const ae=document.createElement("div");ae.classList.add("row-container"),this.cardExpInput=new CardField({id:"cc-expiration-date",label:AstroPayI18n.translate("card_exp_date")}),this.cardCvvInput=new CardField({id:"cc-cvc",label:"CVV"}),ae.append(this.cardExpInput.element,this.cardCvvInput.element),this.element.append(this.cardHolderInput.element,this.cardNumberInput.element,ae),this.cardManager=new CardApService(APCardsFields(defineInputStyles().textColor,se??DEFAULT_EXPIRATION_DATE_FORMAT,ThemeManager.getStyles()).map(ue=>({...ue,placeholder:AstroPayI18n.translate(ue.placeholder)})),this.handleFormStateChange.bind(this)),this.cardManager.init(),te&&te.length>0&&this.renderRequiredFields(te),this.btnPay=new Button({text:AstroPayI18n.translate("pay_amount",{amount:formatAmountCurrency(this.componentProps.amount,this.componentProps.currency,AstroPayConfig.getCurrencyMode())}),onClick:()=>{this.handleSubmit()},isFullWidth:!0,iconLeft:"lock_line",isDisabled:!0}),this.element.append(this.btnPay.element)}renderRequiredFields(te){this.requiredFieldsForm=new FormTemplate({title:AstroPayI18n.translate("additional_information"),requiredFields:te}),this.requiredFieldsForm.setValidationChangeHandler(ne=>{this.isFormTemplateValid=ne,this.updateSubmitButton()}),this.element.append(this.requiredFieldsForm.element)}handleFormStateChange(te){this.formState=te,this.updateInputsValidation(),this.updateSubmitButton()}updateInputsValidation(){[{input:this.cardHolderInput,...this.formState.card_holder},{input:this.cardNumberInput,...this.formState.card_number},{input:this.cardExpInput,...this.formState.card_exp},{input:this.cardCvvInput,...this.formState.card_cvc}].forEach(({input:ne,isValid:ie})=>{ne==null||ne.setValid(ie),ne==null||ne.setHelperText(ie?"":AstroPayI18n.translate("invalid_field"),ie)})}updateSubmitButton(){var ie;const ne=Object.values(this.formState).every(oe=>oe.isValid&&oe.isTouched)&&(this.requiredFieldsForm?this.isFormTemplateValid:!0);(ie=this.btnPay)==null||ie.setDisabled(!ne)}async handleSubmit(){var te,ne,ie,oe,se;try{(te=this.btnPay)==null||te.setLoading(!0);const ae=await this.handleTokenizeCard(),ue={paymentMethods:[{methodCode:this.componentProps.paymentMethod.code,currency:this.componentProps.currency,amount:this.componentProps.amount,user:{sessionId:sessionStorage.getItem(EStorageKey.SESSION_ID)||"",...(ne=this.requiredFieldsForm)==null?void 0:ne.getFormData()},cardData:ae}]};if((ie=this.componentProps.paymentMethod)!=null&&ie.uri){const{status:ce,reason:le}=await PaymentService.postGenericPayment(this.componentProps.paymentMethod.uri,this.componentProps.paymentExternalId,ue);if(ce===ECardPayStatus.PENDING)await this.checkPaymentStatus(),(oe=this.btnPay)==null||oe.setLoading(!1),(se=this.btnPay)==null||se.setDisabled(!0);else throw new Error(le||AstroPayI18n.translate("generic_error"))}else throw new Error(AstroPayI18n.translate("generic_error"))}catch(ae){const ue=ae;console.error(ue.message),this.showErrorMessage(ue.description??ue.message),this.renderRetryButton()}}async handleTokenizeCard(){return new Promise((te,ne)=>{var ae;if(!this.cardManager)return;const{document_type:ie,document_number:oe}=((ae=this.requiredFieldsForm)==null?void 0:ae.getFormData())??{},se={documentType:ie??"",documentNumber:oe??"",sessionId:sessionStorage.getItem(EStorageKey.SESSION_ID)||""};this.cardManager.tokenizeCard(se,ue=>te(ue),ue=>{ne(ue)})})}showErrorMessage(te){this.element.innerHTML="";const ne=new Typography({text:te,size:ThemeManager.getFontScale().xSmall,color:ThemeManager.getStyles().messages.error.textColor}).element;this.element.append(ne)}async checkPaymentStatus(){try{const te=await PaymentService.getPaymentStatus(this.componentProps.paymentExternalId);te.pollingStatus===EPollingStatus.ACCEPTED?this.initializePollingService(te):te.pollingStatus===EPollingStatus.FINISHED&&this.handlePaymentSuccess(te)}catch(te){const ne=te;this.showErrorMessage(ne.description??ne.message),this.stopPolling()}}initializePollingService(te){this.pollingService=new PollingService(te,ne=>this.showWaitingInfo(ne),ne=>this.handlePaymentSuccess(ne),ne=>this.handlePollingError(ne)),this.pollingService.startPolling()}stopPolling(){this.pollingService&&(this.pollingService.stopPolling(),this.pollingService=null)}handlePollingError(te){if(typeof te=="object"&&te!==null&&"text"in te){const ie=te;this.showErrorMessage(ie.text)}else{const ie=te;this.showErrorMessage(ie.description??ie.message)}this.stopPolling(),this.renderRetryButton()}showWaitingInfo(te){this.element.innerHTML="";const ne=this.createLoadingWrapper(te);ne.style.minHeight="400px",this.element.append(ne)}handlePaymentSuccess(te){var oe,se;const ne=[],ie=new Status$1({type:"success",title:(oe=te.data.successSection)==null?void 0:oe.title,description:(se=te.data.successSection)==null?void 0:se.description}).element;ne.push(ie),this.componentProps.onSuccess?this.componentProps.onSuccess(ne):(this.element.innerHTML="",ne.forEach(ae=>this.element.append(ae)))}createLoadingWrapper(te){const ne=document.createElement("div");ne.classList.add("loading-wrapper");const ie=new Loading({size:100,variant:"fetching",color:ThemeManager.getStyles().primaryColor}).element,oe=new Typography({text:te,size:"base",lineHeight:30,weight:600,align:"center"}).element;return ne.append(ie,oe),ne}renderRetryButton(){const te=document.createElement("div");te.classList.add("center-row");const ne=new Button({text:AstroPayI18n.translate("try_again"),variant:"text",size:"small",iconRight:"refresh_2_fill",onClick:()=>{this.element.innerHTML="",this.element.append(this.loadingWrapper),this.fetchPaymentMethodDetail()}}).element;te.append(ne),this.element.append(te)}destroy(){this.stopPolling(),this.element.remove()}}class AmplitudeAnalytics{constructor(){Le(this,"tracker",AmplitudeTracker);Le(this,"astroPayPaymentImpression",re=>{this.tracker.trackEvent(new AstroPayPaymentImpression({component_name:re}))});Le(this,"astroPayPaymentStarted",re=>{this.tracker.trackEvent(new AstroPayPaymentStarted({payment_external_id:re}))});Le(this,"astroPayPaymentClicked",re=>{this.tracker.trackEvent(new AstroPayPaymentClicked({payment_external_id:re}))});Le(this,"astroPayPaymentPhoneNumberEntered",re=>{this.tracker.trackEvent(new AstroPayPaymentPhoneNumberEntered({payment_external_id:re}))});Le(this,"astroPayPaymentUserIdentified",re=>{this.tracker.trackEvent(new AstroPayPaymentUserIdentified({payment_external_id:re}))});Le(this,"astroPayPaymentLinkCopied",re=>{this.tracker.trackEvent(new AstroPayPaymentLinkCopied({payment_external_id:re}))});Le(this,"astroPayPaymentCardClicked",re=>{this.tracker.trackEvent(new AstroPayPaymentCardClicked({payment_external_id:re}))})}}const AmplitudeAnalytics$1=new AmplitudeAnalytics;var EPaymentCode=(ee=>(ee.AP="AP",ee.IX="IX",ee.CREDIT_CARD="EC",ee.DEBIT_CARD="DR",ee.CW="CW",ee.DC="DC",ee.CC="CC",ee))(EPaymentCode||{});const CARDS_METHOD=["EC","DR","CW","DC","CC"],getAstroPayCardPaymentStyles=ee=>css`
|
|
644
644
|
background-color: ${ee.backgroundColor};
|
|
645
645
|
|
|
646
646
|
display: flex;
|
|
@@ -668,7 +668,7 @@ Body:`)).call(gr,Oi()(vr)));var $r=new XMLHttpRequest;$r.open(De._method||ue.Pos
|
|
|
668
668
|
align-items: center;
|
|
669
669
|
gap: 8px;
|
|
670
670
|
}
|
|
671
|
-
`;class AstroPayCardPayment extends Component{constructor(te){super({tag:"div",styles:ie=>getAstroPayCardPaymentStyles(ie)});Le(this,"loadingWrapper");Le(this,"componentProps");Le(this,"methodCode");this.componentProps={...te,country:te.country.trim(),currency:te.currency.trim()},this.methodCode=EPaymentCode.DEBIT_CARD,AstroPayCore.registerComponent(this),AmplitudeAnalytics$1.astroPayPaymentImpression("AstroPayCardPayment"),this.loadingWrapper=document.createElement("div"),this.loadingWrapper.classList.add("loading-wrapper");const ne=new Loading({size:100,variant:"fetching",color:ThemeManager.getStyles().primaryColor}).element;this.loadingWrapper.append(ne),this.element.appendChild(this.loadingWrapper),DataDogTracker.trackEvent("ap_cl_astropay_card_payment_init"),this.createPayment()}async createPayment(){var te,ne;try{const{amount:ie,currency:oe,country:se,order:ae}=this.componentProps,ue={country:se,currency:oe,amount:ie,order:ae,methodCode:this.methodCode},ce=await PaymentService.postCreatePayment(ue,"card_payment");this.renderAstroPayCardMethod(ce)}catch(ie){const oe=ie;(ne=(te=this.componentProps)==null?void 0:te.onError)==null||ne.call(te),this.showErrorMessage(oe.message)}finally{this.loadingWrapper.remove()}}renderAstroPayCardMethod(te){var ie,oe,se;this.element.innerHTML="";const ne=(ie=te.paymentMethods)==null?void 0:ie.find(ae=>ae.enabled&&CARDS_METHOD.includes(ae.code));if(ne){const ae=new CardPaymentMethod({...this.componentProps,paymentExternalId:te.paymentExternalId,paymentMethod:ne,onSuccess:ue=>this.showSuccessContent(ue)}).element;this.element.append(ae)}else(se=(oe=this.componentProps)==null?void 0:oe.onError)==null||se.call(oe),this.showErrorMessage(AstroPayI18n.translate("generic_error"))}showErrorMessage(te){this.element.innerHTML="";const ne=new Typography({text:te,size:ThemeManager.getFontScale().xSmall,color:ThemeManager.getStyles().messages.error.textColor}).element;this.element.append(ne)}showSuccessContent(te){this.element.innerHTML="";const ne=document.createElement("div");if(ne.classList.add("payment-success-content"),te.forEach(ie=>ne.append(ie)),this.element.append(ne),DataDogTracker.trackEvent("ap_cl_payment_success"),this.componentProps.onSuccess){const ie=new LoadingSuccess({onSuccess:this.componentProps.onSuccess}).element;this.element.append(ie)}}render(te){if(!te)throw new Error("Container element not found");te.appendChild(this.element)}destroy(){this.element.remove(),AstroPayCore.unregisterComponent(this)}}const getDividerStyles=ee=>css`
|
|
671
|
+
`;class AstroPayCardPayment extends Component{constructor(te){super({tag:"div",styles:ie=>getAstroPayCardPaymentStyles(ie)});Le(this,"loadingWrapper");Le(this,"componentProps");Le(this,"methodCode");this.componentProps={...te,country:te.country.trim().toUpperCase(),currency:te.currency.trim().toUpperCase()},this.methodCode=EPaymentCode.DEBIT_CARD,AstroPayCore.registerComponent(this),AmplitudeAnalytics$1.astroPayPaymentImpression("AstroPayCardPayment"),this.loadingWrapper=document.createElement("div"),this.loadingWrapper.classList.add("loading-wrapper");const ne=new Loading({size:100,variant:"fetching",color:ThemeManager.getStyles().primaryColor}).element;this.loadingWrapper.append(ne),this.element.appendChild(this.loadingWrapper),DataDogTracker.trackEvent("ap_cl_astropay_card_payment_init"),this.createPayment()}async createPayment(){var te,ne;try{const{amount:ie,currency:oe,country:se,order:ae}=this.componentProps,ue={country:se,currency:oe,amount:ie,order:ae,methodCode:this.methodCode},ce=await PaymentService.postCreatePayment(ue,"card_payment");this.renderAstroPayCardMethod(ce)}catch(ie){const oe=ie;(ne=(te=this.componentProps)==null?void 0:te.onError)==null||ne.call(te),this.showErrorMessage(oe.description??oe.message)}finally{this.loadingWrapper.remove()}}renderAstroPayCardMethod(te){var ie,oe,se;this.element.innerHTML="";const ne=(ie=te.paymentMethods)==null?void 0:ie.find(ae=>ae.enabled&&CARDS_METHOD.includes(ae.code));if(ne){const ae=new CardPaymentMethod({...this.componentProps,paymentExternalId:te.paymentExternalId,paymentMethod:ne,onSuccess:ue=>this.showSuccessContent(ue)}).element;this.element.append(ae)}else(se=(oe=this.componentProps)==null?void 0:oe.onError)==null||se.call(oe),this.showErrorMessage(AstroPayI18n.translate("generic_error"))}showErrorMessage(te){this.element.innerHTML="";const ne=new Typography({text:te,size:ThemeManager.getFontScale().xSmall,color:ThemeManager.getStyles().messages.error.textColor}).element;this.element.append(ne)}showSuccessContent(te){this.element.innerHTML="";const ne=document.createElement("div");if(ne.classList.add("payment-success-content"),te.forEach(ie=>ne.append(ie)),this.element.append(ne),DataDogTracker.trackEvent("ap_cl_payment_success"),this.componentProps.onSuccess){const ie=new LoadingSuccess({onSuccess:this.componentProps.onSuccess}).element;this.element.append(ie)}}render(te){if(!te)throw new Error("Container element not found");te.appendChild(this.element)}destroy(){this.element.remove(),AstroPayCore.unregisterComponent(this)}}const getDividerStyles=ee=>css`
|
|
672
672
|
display: flex;
|
|
673
673
|
align-items: center;
|
|
674
674
|
gap: 10px;
|
|
@@ -856,7 +856,7 @@ Minimum version required to store current data is: `+xe+`.
|
|
|
856
856
|
gap: 4px;
|
|
857
857
|
}
|
|
858
858
|
|
|
859
|
-
.
|
|
859
|
+
.inline-content {
|
|
860
860
|
display: flex;
|
|
861
861
|
flex-direction: row;
|
|
862
862
|
align-items: center;
|
|
@@ -865,6 +865,15 @@ Minimum version required to store current data is: `+xe+`.
|
|
|
865
865
|
flex-wrap: wrap;
|
|
866
866
|
}
|
|
867
867
|
|
|
868
|
+
.column-content {
|
|
869
|
+
display: flex;
|
|
870
|
+
flex-direction: column;
|
|
871
|
+
align-items: center;
|
|
872
|
+
justify-content: center;
|
|
873
|
+
gap: 4px;
|
|
874
|
+
flex-wrap: wrap;
|
|
875
|
+
}
|
|
876
|
+
|
|
868
877
|
.loading-pooling {
|
|
869
878
|
display: flex;
|
|
870
879
|
align-items: center;
|
|
@@ -884,7 +893,7 @@ Minimum version required to store current data is: `+xe+`.
|
|
|
884
893
|
opacity: 1;
|
|
885
894
|
}
|
|
886
895
|
}
|
|
887
|
-
`;var EFlowType=(ee=>(ee.AUTHENTICATED="AUTHENTICATED",ee.GUEST="GUEST",ee))(EFlowType||{});class AstroPayPaymentMethod extends Component{constructor(te){super({tag:"div",styles:()=>getAstroPayPaymentStyles$1()});Le(this,"componentProps");Le(this,"btnAstroPay",null);Le(this,"formCountryPhone");Le(this,"pushFeedbackWrapper");Le(this,"pollingService",null);Le(this,"updatedInitialState");Le(this,"currentFlow",null);Le(this,"renderAPComponent",()=>{var te;if(this.updatedInitialState){if(this.element.innerHTML="",this.btnAstroPay=new Button({text:((te=this.componentProps)==null?void 0:te.actionLabel)??"AstroPay",onClick:this.handleAstroPayClick.bind(this),isFullWidth:!0,iconRight:"arrow_right_line",isApTheme:!0}),this.element.append(this.btnAstroPay.element),this.componentProps.benefits){const ne=new Badge({items:this.componentProps.benefits.batch,variant:"highlight",isFullWidth:!0,align:"center"}).element;this.element.append(ne)}this.updatedInitialState=!1}});Le(this,"handleOnChangePhoneNumber",()=>{this.stopPolling(),this.pushFeedbackWrapper&&this.pushFeedbackWrapper.remove(),this.currentFlow=null});this.componentProps=te,this.updatedInitialState=!0,this.currentFlow=null,AmplitudeAnalytics$1.astroPayPaymentStarted(this.componentProps.paymentExternalId),this.renderAPComponent()}handleAstroPayClick(){var te,ne;if(AmplitudeAnalytics$1.astroPayPaymentClicked(this.componentProps.paymentExternalId),(ne=(te=this.componentProps).onClickCallback)==null||ne.call(te),this.updatedInitialState=!0,isMobile()){this.handleMobileFlow();return}if(this.componentProps.user.hasAccount){this.handleAccountFlow();return}this.renderPhoneInput()}async fetchIdentifyUser(te,ne){var ie
|
|
896
|
+
`;var EFlowType=(ee=>(ee.AUTHENTICATED="AUTHENTICATED",ee.GUEST="GUEST",ee))(EFlowType||{});class AstroPayPaymentMethod extends Component{constructor(te){super({tag:"div",styles:()=>getAstroPayPaymentStyles$1()});Le(this,"componentProps");Le(this,"btnAstroPay",null);Le(this,"formCountryPhone");Le(this,"pushFeedbackWrapper");Le(this,"pollingService",null);Le(this,"updatedInitialState");Le(this,"currentFlow",null);Le(this,"renderAPComponent",()=>{var te;if(this.updatedInitialState){if(this.element.innerHTML="",this.btnAstroPay=new Button({text:((te=this.componentProps)==null?void 0:te.actionLabel)??"AstroPay",onClick:this.handleAstroPayClick.bind(this),isFullWidth:!0,iconRight:"arrow_right_line",isApTheme:!0}),this.element.append(this.btnAstroPay.element),this.componentProps.benefits){const ne=new Badge({items:this.componentProps.benefits.batch,variant:"highlight",isFullWidth:!0,align:"center"}).element;this.element.append(ne)}this.updatedInitialState=!1}});Le(this,"handleOnChangePhoneNumber",()=>{this.stopPolling(),this.pushFeedbackWrapper&&this.pushFeedbackWrapper.remove(),this.currentFlow=null});this.componentProps=te,this.updatedInitialState=!0,this.currentFlow=null,AmplitudeAnalytics$1.astroPayPaymentStarted(this.componentProps.paymentExternalId),this.renderAPComponent()}handleAstroPayClick(){var te,ne;if(AmplitudeAnalytics$1.astroPayPaymentClicked(this.componentProps.paymentExternalId),(ne=(te=this.componentProps).onClickCallback)==null||ne.call(te),this.updatedInitialState=!0,isMobile()){this.handleMobileFlow();return}if(this.componentProps.user.hasAccount){this.handleAccountFlow();return}this.renderPhoneInput()}async fetchIdentifyUser(te,ne){var ie;try{const oe={phoneNumber:formatPhoneNumber(te)};if((await PaymentService.postIdentifyUser(this.componentProps.paymentExternalId,oe)).user.hasAccount){AmplitudeAnalytics$1.astroPayPaymentUserIdentified(this.componentProps.paymentExternalId),(ie=this.formCountryPhone)==null||ie.setDisable(!0),this.handleAccountFlow();return}ne==null||ne()}catch(oe){const se=oe,ae=new Typography({text:se.description??se.message,size:ThemeManager.getFontScale().xSmall,color:ThemeManager.getStyles().messages.error.textColor}).element;this.element.append(ae)}}async handlePhoneNumberSubmit(te){try{this.formCountryPhone&&this.formCountryPhone.setLoading(!0),await this.fetchIdentifyUser(te.phoneNumber,()=>this.handleNoAccountFlow())}finally{this.formCountryPhone&&this.formCountryPhone.setLoading(!1)}}renderPhoneInput(){var te;this.element.innerHTML="",this.formCountryPhone=new PhoneInputForm({availableCountries:((te=this.componentProps)==null?void 0:te.countries)??[],onSubmit:ne=>{AmplitudeAnalytics$1.astroPayPaymentPhoneNumberEntered(this.componentProps.paymentExternalId),this.handlePhoneNumberSubmit(ne)},onChange:this.handleOnChangePhoneNumber}),this.element.append(this.formCountryPhone.element)}generateRedirectUrl(){return UniversalLinkService.generate(`checkout-payment/${this.componentProps.paymentExternalId}`,{data:encodeData(this.componentProps.paymentAmount)})}handleMobileFlow(){const te=buildPathWithParams(EAppDeepLink.IN_APP_CHECKOUT,{token:this.componentProps.paymentExternalId});SingularTracker.getUrlRedirectApp({appDeepLink:te,shouldOpenApp:!0})}async checkPaymentStatus(te){try{this.currentFlow=te,this.stopPolling();const ne=await PaymentService.getPaymentStatus(this.componentProps.paymentExternalId);ne.pollingStatus===EPollingStatus.ACCEPTED?this.initializePollingService(ne):ne.pollingStatus===EPollingStatus.FINISHED&&this.handlePaymentSuccess(ne)}catch(ne){const ie=ne;this.showErrorMessage(ie.description??ie.message)}}initializePollingService(te){this.pollingService=new PollingService(te,ne=>this.showWaitingInfo(ne),ne=>this.handlePaymentSuccess(ne),ne=>this.handlePollingError(ne)),this.pollingService.startPolling()}showWaitingInfo(te){this.currentFlow===EFlowType.GUEST&&(this.pushFeedbackWrapper&&this.pushFeedbackWrapper.remove(),this.pushFeedbackWrapper=document.createElement("div"),this.pushFeedbackWrapper.classList.add("feedback-message-wrapper"),this.element.append(this.pushFeedbackWrapper)),this.showAccountWaitingInfo(te)}handlePollingError(te){if(typeof te=="object"&&te!==null&&"text"in te){const ie=te;this.showErrorMessage(ie.text,ie.cta?{text:ie.cta,onClick:()=>{this.checkPaymentStatus(this.currentFlow??EFlowType.AUTHENTICATED)}}:void 0)}else{const ie=te;this.showErrorMessage(ie.description??ie.message)}this.stopPolling(),this.currentFlow=null}stopPolling(){this.pollingService&&(this.pollingService.stopPolling(),this.pollingService=null),this.element.querySelectorAll(".loading-pooling").forEach(ne=>ne.remove())}handleAccountFlow(){this.renderAlreadySent(),this.checkPaymentStatus(EFlowType.AUTHENTICATED)}renderAlreadySent(){var fe;this.pushFeedbackWrapper&&this.pushFeedbackWrapper.remove(),(fe=this.btnAstroPay)==null||fe.setDisabled(!0),this.pushFeedbackWrapper=document.createElement("div"),this.pushFeedbackWrapper.classList.add("feedback-message-wrapper");const te=new Badge({items:[{title:AstroPayI18n.translate("push_notification_sent"),icon:"notification_fill"}],variant:"highlight",isFullWidth:!0,align:"center"}).element,ne=document.createElement("div");ne.classList.add("sent-message-content");const ie=new Typography({text:AstroPayI18n.translate("didnt_receive"),size:"medium",weight:600}).element,oe=new Typography({text:AstroPayI18n.translate("scan_qr_copy_link"),size:"small",weight:400}).element;ne.append(ie,oe);const se=buildPathWithParams(EAppDeepLink.IN_APP_CHECKOUT,{token:this.componentProps.paymentExternalId}),ae=SingularTracker.getUrlRedirectApp({appDeepLink:se}),ue=new QrCode({width:120,value:ae,altText:AstroPayI18n.translate("qr_code")}).element,ce=this.generateRedirectUrl(),le=SingularTracker.getUrlRedirectApp({appDeepLink:se,fallbackRedirect:ce}),de=new Button({text:AstroPayI18n.translate("copy_payment_link"),variant:"copy-to-clipboard",size:"small",iconRight:"copy_2_line",onClick:()=>{AmplitudeAnalytics$1.astroPayPaymentLinkCopied(this.componentProps.paymentExternalId),copyToClipboard(le)}}).element;this.pushFeedbackWrapper.append(te,ne,ue,de),this.element.append(this.pushFeedbackWrapper)}showAccountWaitingInfo(te){if(!this.pushFeedbackWrapper)return;let ne=this.pushFeedbackWrapper.querySelector(".loading-pooling");ne||(ne=document.createElement("div"),ne.classList.add("loading-pooling"),this.pushFeedbackWrapper.append(ne)),ne.innerHTML="";const ie=new Loading({size:12,color:ThemeManager.getStyles().textPrimaryColor}).element,oe=new Typography({text:te,size:"xSmall"}).element;ne.append(ie,oe)}handleNoAccountFlow(){const te=this.generateRedirectUrl(),ne=window.open(te,"_blank");(!ne||ne.closed||typeof ne.closed>"u")&&(window.location.href=te),setTimeout(()=>{this.showNoAccountWaitingInfo()},5e3)}showNoAccountWaitingInfo(){this.pushFeedbackWrapper&&this.pushFeedbackWrapper.remove(),this.pushFeedbackWrapper=document.createElement("div"),this.pushFeedbackWrapper.classList.add("feedback-message-wrapper");const te=document.createElement("div");te.classList.add("inline-content");const ne=new Typography({text:AstroPayI18n.translate("already_paid"),size:"xSmall"}).element,ie=new Link({text:AstroPayI18n.translate("check_payment_status"),size:"xSmall",onClick:()=>{var oe;te.remove(),(oe=this.formCountryPhone)==null||oe.setDisable(!0),this.checkPaymentStatus(EFlowType.GUEST)}}).element;te.append(ne,ie),this.pushFeedbackWrapper.append(te),this.element.append(this.pushFeedbackWrapper)}handlePaymentSuccess(te){var oe,se;const ne=[],ie=new Status$1({type:"success",title:(oe=te.data.successSection)==null?void 0:oe.title,description:(se=te.data.successSection)==null?void 0:se.description}).element;ne.push(ie),this.componentProps.onSuccess?this.componentProps.onSuccess(ne):(this.element.innerHTML="",ne.forEach(ae=>this.element.append(ae)))}showErrorMessage(te,ne){if(!this.pushFeedbackWrapper)return;const ie=document.createElement("div");ie.classList.add("column-content");const oe=new Typography({text:te,size:ThemeManager.getFontScale().xSmall,color:ThemeManager.getStyles().messages.error.textColor,align:"center"}).element;if(ie.append(oe),ne){const se=new Link({text:ne.text,size:"xSmall",onClick:()=>{ie.remove(),ne.onClick()}}).element;ie.append(se)}this.pushFeedbackWrapper.append(ie)}destroy(){this.stopPolling(),this.element.remove()}}const formatTimeInSeconds=ee=>{const re=Math.floor(ee/60),te=ee%60;return`${String(re).padStart(2,"0")}:${String(te).padStart(2,"0")}`},getTimerStyles=ee=>css`
|
|
888
897
|
display: flex;
|
|
889
898
|
flex-wrap: nowrap;
|
|
890
899
|
align-items: center;
|
|
@@ -935,7 +944,7 @@ Minimum version required to store current data is: `+xe+`.
|
|
|
935
944
|
align-items: center;
|
|
936
945
|
gap: 8px;
|
|
937
946
|
}
|
|
938
|
-
`;class PaymentMethod extends Component{constructor(te){super({tag:"div",styles:ne=>getPaymentMethodStyles(ne)});Le(this,"componentProps");Le(this,"loadingWrapper");Le(this,"timerElement",null);Le(this,"timerInstance",null);Le(this,"pollingService",null);this.componentProps=te,this.loadingWrapper=this.createLoadingWrapper(),this.element.append(this.loadingWrapper),this.fetchPaymentMethodData()}createLoadingWrapper(){const te=document.createElement("div");te.classList.add("loading-wrapper");const ne=new Loading({size:100,variant:"fetching",color:ThemeManager.getStyles().primaryColor}).element,ie=new Typography({text:AstroPayI18n.translate("waiting_confirmation"),size:"base",lineHeight:30,weight:600}).element;ie.style.marginTop="8px";const oe=new Typography({text:AstroPayI18n.translate("do_not_close_window"),size:"medium",lineHeight:24}).element;return te.append(ne,ie,oe),te}async fetchPaymentMethodData(){var te,ne,ie;try{if((te=this.componentProps.paymentMethod)!=null&&te.uri){const oe={methodCode:this.componentProps.paymentMethod.code},se=await PaymentService.postGenericPayment(this.componentProps.paymentMethod.uri,this.componentProps.paymentExternalId,oe);this.renderSections(se.sections)}else throw new Error(AstroPayI18n.translate("generic_error"))}catch(oe){const se=oe;(ie=(ne=this.componentProps)==null?void 0:ne.onError)==null||ie.call(ne),this.showErrorMessage(se.message)}finally{this.loadingWrapper.remove()}}async checkPaymentStatus(){try{const te=await PaymentService.getPaymentStatus(this.componentProps.paymentExternalId);te.pollingStatus===EPollingStatus.ACCEPTED?this.initializePollingService(te):te.pollingStatus===EPollingStatus.FINISHED&&this.handlePaymentSuccess(te)}catch(te){const ne=te;this.showErrorMessage(ne.message),this.stopTimer(),this.stopPolling()}}initializePollingService(te){this.pollingService=new PollingService(te,ne=>this.showWaitingInfo(ne),ne=>this.handlePaymentSuccess(ne),ne=>this.handlePollingError(ne)),this.pollingService.startPolling()}handlePollingError(te){var ie,oe;const ne=te;this.showErrorMessage(ne.message),this.stopPolling(),(oe=(ie=this.componentProps)==null?void 0:ie.onError)==null||oe.call(ie)}stopTimer(){this.timerInstance&&(this.timerInstance.stopTimer(),this.timerInstance=null,this.timerElement=null)}handlePaymentSuccess(te){var oe,se;const ne=[],ie=new Status$1({type:"success",title:(oe=te.data.successSection)==null?void 0:oe.title,description:(se=te.data.successSection)==null?void 0:se.description}).element;ne.push(ie),this.componentProps.onSuccess?this.componentProps.onSuccess(ne):(this.element.innerHTML="",ne.forEach(ae=>this.element.append(ae)))}showErrorMessage(te){this.element.innerHTML="";const ne=document.createElement("div");ne.classList.add("timeout-container");const ie=new Typography({text:te,size:ThemeManager.getFontScale().xSmall,color:ThemeManager.getStyles().messages.error.textColor}).element;ne.append(ie,this.renderRetryButton()),this.element.append(ne)}showWaitingInfo(te){let ne=this.element.querySelector(".loading-pooling");ne||(ne=document.createElement("div"),ne.classList.add("loading-pooling"),this.element.append(ne)),ne.innerHTML="";const ie=new Loading({size:12,color:ThemeManager.getStyles().textPrimaryColor}).element,oe=new Typography({text:te,size:"xSmall"}).element;ne.append(ie,oe)}async renderSections(te){te.filter(ne=>!!ne).sort((ne,ie)=>ne.order-ie.order).forEach(ne=>{const{componentType:ie,metadata:oe}=ne;switch(ie){case EComponentType.AMOUNT_DISPLAY:this.renderAmountDisplay(oe);break;case EComponentType.COPY:this.renderCopy(oe);break;case EComponentType.DESCRIPTION:this.renderDescription(oe);break;case EComponentType.EXPIRATION_TIMER:this.renderTimer(oe);break;case EComponentType.QR_CODE:this.renderQRCode(oe);break;case EComponentType.SHARE:this.renderShare(oe);break;default:console.warn("Unknown component type:",ie)}}),await this.checkPaymentStatus()}renderCopy(te){const ne=new Button({text:te.label,variant:"copy-to-clipboard",size:"medium",iconLeft:te.iconLeft,iconRight:te.iconRight??"copy_2_line",onClick:()=>{copyToClipboard(te.value)}}).element;this.element.append(ne)}renderShare(te){const ne=new Button({text:te.label,variant:"text",size:"medium",iconRight:te.iconRight,iconLeft:te.iconLeft,onClick:()=>{var ie,oe,se;shareInfo(((ie=te==null?void 0:te.richTextInfo)==null?void 0:ie.title)??"Share",((oe=te==null?void 0:te.richTextInfo)==null?void 0:oe.description)??te.value,(se=te==null?void 0:te.richTextInfo)==null?void 0:se.url)}}).element;this.element.append(ne)}renderDescription(te){const ne=new Typography({text:`${te.text} ${formatAmountCurrency(te.amount,te.currency,AstroPayConfig.getCurrencyMode())}`,size:"medium",lineHeight:24,weight:600}).element;this.element.append(ne)}renderQRCode(te){const ne=new QrCode({value:te.value,altText:AstroPayI18n.translate("qr_code")}).element;this.element.append(ne)}renderAmountDisplay(te){const ne=new Typography({text:te.value,size:"medium",lineHeight:24,weight:600}).element;this.element.append(ne)}renderTimer(te){this.timerInstance=new Timer({time:te.time,text:te.label,iconLeft:te.iconLeft,iconRight:te.iconRight,timeoutText:te.timeoutInfo.description,onTimeOut:()=>this.handleTimeout(te)}),this.timerElement=this.timerInstance.element,this.element.append(this.timerElement)}handleTimeout(te){this.stopPolling(),this.stopTimer();const ne=document.createElement("div");ne.classList.add("timeout-container"),this.timerElement&&ne.append(this.timerElement),te.timeoutInfo.description&&ne.append(this.renderExpiredBadge(te.timeoutInfo.description)),te.timeoutInfo.retry&&ne.append(this.renderRetryButton()),this.element.innerHTML="",this.element.append(ne)}renderRetryButton(){return new Button({text:AstroPayI18n.translate("try_again"),variant:"primary",size:"medium",iconRight:"refresh_2_fill",onClick:()=>{this.element.innerHTML="",this.timerElement=null,this.timerInstance=null,this.stopPolling(),this.element.append(this.loadingWrapper),this.fetchPaymentMethodData()}}).element}renderExpiredBadge(te){return new Badge({items:[{title:te,icon:"alert_line"}],variant:"default",align:"center"}).element}stopPolling(){this.pollingService&&(this.pollingService.stopPolling(),this.pollingService=null)}destroy(){this.stopPolling(),this.element.remove()}}const paymentIcons={[EPaymentCode.AP]:"astropay_payment_method",[EPaymentCode.IX]:"system_pix",[EPaymentCode.CREDIT_CARD]:"bank_card_line",[EPaymentCode.DEBIT_CARD]:"bank_card_line",[EPaymentCode.CW]:"bank_card_line",[EPaymentCode.DC]:"bank_card_line",[EPaymentCode.CC]:"bank_card_line"},paymentAuxIcons={[EPaymentCode.CREDIT_CARD]:["payment_visa","payment_master"],[EPaymentCode.DEBIT_CARD]:["payment_visa","payment_master"],[EPaymentCode.CW]:["payment_visa","payment_master"],[EPaymentCode.DC]:["payment_visa","payment_master"],[EPaymentCode.CC]:["payment_visa","payment_master"]},callbackEvent=(ee,re)=>{switch(ee){case EPaymentCode.CREDIT_CARD:case EPaymentCode.DEBIT_CARD:case EPaymentCode.CW:case EPaymentCode.DC:case EPaymentCode.CC:AmplitudeAnalytics$1.astroPayPaymentCardClicked(re);break}},validatePaymentMethod=ee=>!!ee.enabled,createPaymentInstance=(ee,re)=>{const{paymentExternalId:te,amount:ne,currency:ie,country:oe,user:se,countries:ae,benefits:ue,cardConfig:ce,actionLabel:le,onSuccess:de,onError:fe}=re;switch(ee.code){case EPaymentCode.AP:return new AstroPayPaymentMethod({paymentExternalId:te,user:se,countries:ae,benefits:ue,paymentAmount:{amount:ne,currency:ie},actionLabel:le,onSuccess:de,onError:fe});default:return CARDS_METHOD.includes(ee.code)?new CardPaymentMethod({paymentExternalId:te,amount:ne,currency:ie,country:oe,paymentMethod:ee,showPaymentSummary:ce==null?void 0:ce.showPaymentSummary,expirationDateFormat:ce==null?void 0:ce.expirationDateFormat,onSuccess:de,onError:fe}):new PaymentMethod({paymentExternalId:te,paymentMethod:ee,onSuccess:de,onError:fe})}},mountPaymentMethodItems=({paymentMethods:ee,paymentExternalId:re,...te})=>ee!=null&&ee.length?ee.filter(validatePaymentMethod).map(ne=>{let ie=null;const oe=()=>{ie==null||ie.destroy();const ae={paymentExternalId:re,...te};return ie=createPaymentInstance(ne,ae),ie.element},se=()=>{ie==null||ie.destroy(),ie=null};return{icon:ne.logo||paymentIcons[ne.code]||"pay_line",title:ne.label,description:ne==null?void 0:ne.description,auxImage:paymentAuxIcons[ne.code],content:oe,onClose:se,onClickCallback:()=>callbackEvent(ne.code,re)}}):[];class AstroPayFullCheckout extends Component{constructor(te){super({tag:"div",elementId:"payment-component",styles:ie=>getAstroPayFullCheckoutStyles(ie)});Le(this,"loadingWrapper");Le(this,"componentProps");Le(this,"accPaymentMethods");this.componentProps={...te,showTitle:te.showTitle??!0,showDescription:te.showDescription??!0,country:te.country.trim(),currency:te.currency.trim()},AstroPayCore.registerComponent(this),AmplitudeAnalytics$1.astroPayPaymentImpression("AstroPayFullCheckout"),this.loadingWrapper=document.createElement("div"),this.loadingWrapper.classList.add("loading-wrapper");const ne=new Loading({size:100,variant:"fetching",color:ThemeManager.getStyles().primaryColor}).element;this.loadingWrapper.append(ne),this.element.appendChild(this.loadingWrapper),DataDogTracker.trackEvent("ap_cl_full_checkout_init"),this.createPayment()}async createPayment(){var te,ne;try{const{amount:ie,currency:oe,country:se,user:ae,order:ue,paymentExternalId:ce}=this.componentProps;let le;if(ce)le=await PaymentService.getPaymentDetails(ce,"full_checkout");else{const de={country:se,currency:oe,amount:ie,user:ae,order:ue};le=await PaymentService.postCreatePayment(de,"full_checkout")}this.renderPaymentMethods(le)}catch(ie){const oe=ie;(ne=(te=this.componentProps)==null?void 0:te.onError)==null||ne.call(te);const se=new Typography({text:oe.message,size:ThemeManager.getFontScale().xSmall,color:ThemeManager.getStyles().messages.error.textColor}).element;this.element.appendChild(se)}finally{this.loadingWrapper.remove()}}renderPaymentMethods(te){var fe,he,pe,ge;const{paymentExternalId:ne,user:ie,paymentMethods:oe,countries:se,paymentComponentDescription:ae,benefits:ue,metadata:ce}=te;if(this.element.innerHTML="",this.componentProps.showTitle){const me=new Typography({text:AstroPayI18n.translate("checkout_method"),variant:"div",size:"large",weight:600}).element;this.element.append(me)}if(this.componentProps.showDescription&&ae){const me=new Typography({text:ae,size:"small",color:ThemeManager.getStyles().textSecondaryColor,weight:400}).element;this.element.append(me)}const le={code:EPaymentCode.AP,label:((fe=te==null?void 0:te.metadata)==null?void 0:fe.title)||AstroPayI18n.translate("astro_express_checkout"),description:(he=te==null?void 0:te.metadata)==null?void 0:he.description,enabled:!0},de=mountPaymentMethodItems({paymentMethods:[le,...oe??[]],paymentExternalId:ne,amount:this.componentProps.amount,currency:this.componentProps.currency,country:this.componentProps.country,user:ie,countries:se,benefits:ue,actionLabel:ce==null?void 0:ce.actionLabel,onSuccess:me=>this.showSuccessContent(me),onError:(pe=this.componentProps)==null?void 0:pe.onError,cardConfig:(ge=this.componentProps)==null?void 0:ge.cardConfig});de.length>0&&(this.accPaymentMethods=new Accordion({items:de,defaultActiveItem:0}),this.element.append(this.accPaymentMethods.element))}showSuccessContent(te){this.element.innerHTML="";const ne=document.createElement("div");if(ne.classList.add("payment-success-content"),te.forEach(ie=>ne.append(ie)),this.element.append(ne),DataDogTracker.trackEvent("ap_cl_payment_success"),this.componentProps.onSuccess){const ie=new LoadingSuccess({onSuccess:this.componentProps.onSuccess}).element;this.element.append(ie)}}render(te){if(!te)throw new Error("Container element not found");te.appendChild(this.element)}destroy(){this.element.remove(),AstroPayCore.unregisterComponent(this)}}const getAstroPayPaymentStyles=ee=>css`
|
|
947
|
+
`;class PaymentMethod extends Component{constructor(te){super({tag:"div",styles:ne=>getPaymentMethodStyles(ne)});Le(this,"componentProps");Le(this,"loadingWrapper");Le(this,"timerElement",null);Le(this,"timerInstance",null);Le(this,"pollingService",null);this.componentProps=te,this.loadingWrapper=this.createLoadingWrapper(),this.element.append(this.loadingWrapper),this.fetchPaymentMethodData()}createLoadingWrapper(){const te=document.createElement("div");te.classList.add("loading-wrapper");const ne=new Loading({size:100,variant:"fetching",color:ThemeManager.getStyles().primaryColor}).element,ie=new Typography({text:AstroPayI18n.translate("waiting_confirmation"),size:"base",lineHeight:30,weight:600}).element;ie.style.marginTop="8px";const oe=new Typography({text:AstroPayI18n.translate("do_not_close_window"),size:"medium",lineHeight:24}).element;return te.append(ne,ie,oe),te}async fetchPaymentMethodData(){var te;try{if((te=this.componentProps.paymentMethod)!=null&&te.uri){const ne={methodCode:this.componentProps.paymentMethod.code},ie=await PaymentService.postGenericPayment(this.componentProps.paymentMethod.uri,this.componentProps.paymentExternalId,ne);this.renderSections(ie.sections)}else throw new Error(AstroPayI18n.translate("generic_error"))}catch(ne){const ie=ne;this.showErrorMessage(ie.description??ie.message)}finally{this.loadingWrapper.remove()}}async checkPaymentStatus(){try{const te=await PaymentService.getPaymentStatus(this.componentProps.paymentExternalId);te.pollingStatus===EPollingStatus.ACCEPTED?this.initializePollingService(te):te.pollingStatus===EPollingStatus.FINISHED&&this.handlePaymentSuccess(te)}catch(te){const ne=te;this.showErrorMessage(ne.description??ne.message),this.stopTimer(),this.stopPolling()}}initializePollingService(te){this.pollingService=new PollingService(te,ne=>this.showWaitingInfo(ne),ne=>this.handlePaymentSuccess(ne),ne=>this.handlePollingError(ne)),this.pollingService.startPolling()}handlePollingError(te){if(typeof te=="object"&&te!==null&&"text"in te){const ie=te;this.showErrorMessage(ie.text)}else{const ie=te;this.showErrorMessage(ie.description??ie.message)}this.stopPolling()}stopTimer(){this.timerInstance&&(this.timerInstance.stopTimer(),this.timerInstance=null,this.timerElement=null)}handlePaymentSuccess(te){var oe,se;const ne=[],ie=new Status$1({type:"success",title:(oe=te.data.successSection)==null?void 0:oe.title,description:(se=te.data.successSection)==null?void 0:se.description}).element;ne.push(ie),this.componentProps.onSuccess?this.componentProps.onSuccess(ne):(this.element.innerHTML="",ne.forEach(ae=>this.element.append(ae)))}showErrorMessage(te){this.element.innerHTML="";const ne=document.createElement("div");ne.classList.add("timeout-container");const ie=new Typography({text:te,size:ThemeManager.getFontScale().xSmall,color:ThemeManager.getStyles().messages.error.textColor}).element;ne.append(ie,this.renderRetryButton()),this.element.append(ne)}showWaitingInfo(te){let ne=this.element.querySelector(".loading-pooling");ne||(ne=document.createElement("div"),ne.classList.add("loading-pooling"),this.element.append(ne)),ne.innerHTML="";const ie=new Loading({size:12,color:ThemeManager.getStyles().textPrimaryColor}).element,oe=new Typography({text:te,size:"xSmall"}).element;ne.append(ie,oe)}async renderSections(te){te.filter(ne=>!!ne).sort((ne,ie)=>ne.order-ie.order).forEach(ne=>{const{componentType:ie,metadata:oe}=ne;switch(ie){case EComponentType.AMOUNT_DISPLAY:this.renderAmountDisplay(oe);break;case EComponentType.COPY:this.renderCopy(oe);break;case EComponentType.DESCRIPTION:this.renderDescription(oe);break;case EComponentType.EXPIRATION_TIMER:this.renderTimer(oe);break;case EComponentType.QR_CODE:this.renderQRCode(oe);break;case EComponentType.SHARE:this.renderShare(oe);break;default:console.warn("Unknown component type:",ie)}}),await this.checkPaymentStatus()}renderCopy(te){const ne=new Button({text:te.label,variant:"copy-to-clipboard",size:"medium",iconLeft:te.iconLeft,iconRight:te.iconRight??"copy_2_line",onClick:()=>{copyToClipboard(te.value)}}).element;this.element.append(ne)}renderShare(te){const ne=new Button({text:te.label,variant:"text",size:"medium",iconRight:te.iconRight,iconLeft:te.iconLeft,onClick:()=>{var ie,oe,se;shareInfo(((ie=te==null?void 0:te.richTextInfo)==null?void 0:ie.title)??"Share",((oe=te==null?void 0:te.richTextInfo)==null?void 0:oe.description)??te.value,(se=te==null?void 0:te.richTextInfo)==null?void 0:se.url)}}).element;this.element.append(ne)}renderDescription(te){const ne=new Typography({text:`${te.text} ${formatAmountCurrency(te.amount,te.currency,AstroPayConfig.getCurrencyMode())}`,size:"medium",lineHeight:24,weight:600}).element;this.element.append(ne)}renderQRCode(te){const ne=new QrCode({value:te.value,altText:AstroPayI18n.translate("qr_code")}).element;this.element.append(ne)}renderAmountDisplay(te){const ne=new Typography({text:te.value,size:"medium",lineHeight:24,weight:600}).element;this.element.append(ne)}renderTimer(te){this.timerInstance=new Timer({time:te.time,text:te.label,iconLeft:te.iconLeft,iconRight:te.iconRight,timeoutText:te.timeoutInfo.description,onTimeOut:()=>this.handleTimeout(te)}),this.timerElement=this.timerInstance.element,this.element.append(this.timerElement)}handleTimeout(te){this.stopPolling(),this.stopTimer();const ne=document.createElement("div");ne.classList.add("timeout-container"),this.timerElement&&ne.append(this.timerElement),te.timeoutInfo.description&&ne.append(this.renderExpiredBadge(te.timeoutInfo.description)),te.timeoutInfo.retry&&ne.append(this.renderRetryButton()),this.element.innerHTML="",this.element.append(ne)}renderRetryButton(){return new Button({text:AstroPayI18n.translate("try_again"),variant:"primary",size:"medium",iconRight:"refresh_2_fill",onClick:()=>{this.element.innerHTML="",this.timerElement=null,this.timerInstance=null,this.stopPolling(),this.element.append(this.loadingWrapper),this.fetchPaymentMethodData()}}).element}renderExpiredBadge(te){return new Badge({items:[{title:te,icon:"alert_line"}],variant:"default",align:"center"}).element}stopPolling(){this.pollingService&&(this.pollingService.stopPolling(),this.pollingService=null)}destroy(){this.stopPolling(),this.element.remove()}}const paymentIcons={[EPaymentCode.AP]:"astropay_payment_method",[EPaymentCode.IX]:"system_pix",[EPaymentCode.CREDIT_CARD]:"bank_card_line",[EPaymentCode.DEBIT_CARD]:"bank_card_line",[EPaymentCode.CW]:"bank_card_line",[EPaymentCode.DC]:"bank_card_line",[EPaymentCode.CC]:"bank_card_line"},paymentAuxIcons={[EPaymentCode.CREDIT_CARD]:["payment_visa","payment_master"],[EPaymentCode.DEBIT_CARD]:["payment_visa","payment_master"],[EPaymentCode.CW]:["payment_visa","payment_master"],[EPaymentCode.DC]:["payment_visa","payment_master"],[EPaymentCode.CC]:["payment_visa","payment_master"]},callbackEvent=(ee,re)=>{switch(ee){case EPaymentCode.CREDIT_CARD:case EPaymentCode.DEBIT_CARD:case EPaymentCode.CW:case EPaymentCode.DC:case EPaymentCode.CC:AmplitudeAnalytics$1.astroPayPaymentCardClicked(re);break}},validatePaymentMethod=ee=>!!ee.enabled,createPaymentInstance=(ee,re)=>{const{paymentExternalId:te,amount:ne,currency:ie,country:oe,user:se,countries:ae,benefits:ue,cardConfig:ce,actionLabel:le,onSuccess:de,onError:fe}=re;switch(ee.code){case EPaymentCode.AP:return new AstroPayPaymentMethod({paymentExternalId:te,user:se,countries:ae,benefits:ue,paymentAmount:{amount:ne,currency:ie},actionLabel:le,onSuccess:de,onError:fe});default:return CARDS_METHOD.includes(ee.code)?new CardPaymentMethod({paymentExternalId:te,amount:ne,currency:ie,country:oe,paymentMethod:ee,showPaymentSummary:ce==null?void 0:ce.showPaymentSummary,expirationDateFormat:ce==null?void 0:ce.expirationDateFormat,onSuccess:de,onError:fe}):new PaymentMethod({paymentExternalId:te,paymentMethod:ee,onSuccess:de,onError:fe})}},mountPaymentMethodItems=({paymentMethods:ee,paymentExternalId:re,...te})=>ee!=null&&ee.length?ee.filter(validatePaymentMethod).map(ne=>{let ie=null;const oe=()=>{ie==null||ie.destroy();const ae={paymentExternalId:re,...te};return ie=createPaymentInstance(ne,ae),ie.element},se=()=>{ie==null||ie.destroy(),ie=null};return{icon:ne.logo||paymentIcons[ne.code]||"pay_line",title:ne.label,description:ne==null?void 0:ne.description,auxImage:paymentAuxIcons[ne.code],content:oe,onClose:se,onClickCallback:()=>callbackEvent(ne.code,re)}}):[];class AstroPayFullCheckout extends Component{constructor(te){super({tag:"div",elementId:"payment-component",styles:ie=>getAstroPayFullCheckoutStyles(ie)});Le(this,"loadingWrapper");Le(this,"componentProps");Le(this,"accPaymentMethods");this.componentProps={...te,showTitle:te.showTitle??!0,showDescription:te.showDescription??!0,country:te.country.trim().toUpperCase(),currency:te.currency.trim().toUpperCase()},AstroPayCore.registerComponent(this),AmplitudeAnalytics$1.astroPayPaymentImpression("AstroPayFullCheckout"),this.loadingWrapper=document.createElement("div"),this.loadingWrapper.classList.add("loading-wrapper");const ne=new Loading({size:100,variant:"fetching",color:ThemeManager.getStyles().primaryColor}).element;this.loadingWrapper.append(ne),this.element.appendChild(this.loadingWrapper),DataDogTracker.trackEvent("ap_cl_full_checkout_init"),this.createPayment()}async createPayment(){var te,ne;try{const{amount:ie,currency:oe,country:se,user:ae,order:ue,paymentExternalId:ce,description:le,paymentLink:de}=this.componentProps;let fe;if(ce)fe=await PaymentService.getPaymentDetails(ce,"full_checkout");else{const he={country:se,currency:oe,amount:ie,user:ae,order:ue,description:le,paymentLink:de};fe=await PaymentService.postCreatePayment(he,"full_checkout")}this.renderPaymentMethods(fe)}catch(ie){const oe=ie;(ne=(te=this.componentProps)==null?void 0:te.onError)==null||ne.call(te);const se=new Typography({text:oe.description??oe.message,size:ThemeManager.getFontScale().xSmall,color:ThemeManager.getStyles().messages.error.textColor}).element;this.element.appendChild(se)}finally{this.loadingWrapper.remove()}}renderPaymentMethods(te){var fe,he,pe,ge;const{paymentExternalId:ne,user:ie,paymentMethods:oe,countries:se,paymentComponentDescription:ae,benefits:ue,metadata:ce}=te;if(this.element.innerHTML="",this.componentProps.showTitle){const me=new Typography({text:AstroPayI18n.translate("checkout_method"),variant:"div",size:"large",weight:600}).element;this.element.append(me)}if(this.componentProps.showDescription&&ae){const me=new Typography({text:ae,size:"small",color:ThemeManager.getStyles().textSecondaryColor,weight:400}).element;this.element.append(me)}const le={code:EPaymentCode.AP,label:((fe=te==null?void 0:te.metadata)==null?void 0:fe.title)||AstroPayI18n.translate("astro_express_checkout"),description:(he=te==null?void 0:te.metadata)==null?void 0:he.description,enabled:!0},de=mountPaymentMethodItems({paymentMethods:[le,...oe??[]],paymentExternalId:ne,amount:this.componentProps.amount,currency:this.componentProps.currency,country:this.componentProps.country,user:ie,countries:se,benefits:ue,actionLabel:ce==null?void 0:ce.actionLabel,onSuccess:me=>this.showSuccessContent(me),onError:(pe=this.componentProps)==null?void 0:pe.onError,cardConfig:(ge=this.componentProps)==null?void 0:ge.cardConfig});de.length>0&&(this.accPaymentMethods=new Accordion({items:de,defaultActiveItem:0}),this.element.append(this.accPaymentMethods.element))}showSuccessContent(te){this.element.innerHTML="";const ne=document.createElement("div");if(ne.classList.add("payment-success-content"),te.forEach(ie=>ne.append(ie)),this.element.append(ne),DataDogTracker.trackEvent("ap_cl_payment_success"),this.componentProps.onSuccess){const ie=new LoadingSuccess({onSuccess:this.componentProps.onSuccess}).element;this.element.append(ie)}}render(te){if(!te)throw new Error("Container element not found");te.appendChild(this.element)}destroy(){this.element.remove(),AstroPayCore.unregisterComponent(this)}}const getAstroPayPaymentStyles=ee=>css`
|
|
939
948
|
background-color: ${ee.backgroundColor};
|
|
940
949
|
|
|
941
950
|
display: flex;
|
|
@@ -962,5 +971,5 @@ Minimum version required to store current data is: `+xe+`.
|
|
|
962
971
|
align-items: center;
|
|
963
972
|
gap: 8px;
|
|
964
973
|
}
|
|
965
|
-
`;class AstroPayPayment extends Component{constructor(te){super({tag:"div",styles:ie=>getAstroPayPaymentStyles(ie)});Le(this,"loadingWrapper");Le(this,"componentProps");Le(this,"methodCode");this.componentProps={...te,country:te.country.trim(),currency:te.currency.trim()},this.methodCode="AP",AstroPayCore.registerComponent(this),AmplitudeAnalytics$1.astroPayPaymentImpression("AstroPayPayment"),this.loadingWrapper=document.createElement("div"),this.loadingWrapper.classList.add("loading-wrapper");const ne=new Loading({size:100,variant:"fetching",color:ThemeManager.getStyles().primaryColor}).element;this.loadingWrapper.append(ne),this.element.appendChild(this.loadingWrapper),DataDogTracker.trackEvent("ap_cl_astropay_payment_init"),this.createPayment()}async createPayment(){var te,ne;try{const{amount:ie,currency:oe,country:se,user:ae,order:ue}=this.componentProps,ce={country:se,currency:oe,amount:ie,user:ae,order:ue,methodCode:this.methodCode},le=await PaymentService.postCreatePayment(ce,"astropay_payment");this.renderAstroPayMethod(le)}catch(ie){const oe=ie;(ne=(te=this.componentProps)==null?void 0:te.onError)==null||ne.call(te);const se=new Typography({text:oe.message,size:ThemeManager.getFontScale().xSmall,color:ThemeManager.getStyles().messages.error.textColor}).element;this.element.appendChild(se)}finally{this.loadingWrapper.remove()}}renderAstroPayMethod(te){const{paymentExternalId:ne,user:ie,countries:oe,benefits:se,metadata:ae}=te;this.element.innerHTML="";const ue={amount:this.componentProps.amount,currency:this.componentProps.currency},ce=new AstroPayPaymentMethod({paymentExternalId:ne,user:ie,countries:oe,benefits:se,paymentAmount:ue,actionLabel:ae==null?void 0:ae.actionLabel,onSuccess:le=>this.showSuccessContent(le)}).element;this.element.append(ce)}showSuccessContent(te){this.element.innerHTML="";const ne=document.createElement("div");if(ne.classList.add("payment-success-content"),te.forEach(ie=>ne.append(ie)),this.element.append(ne),DataDogTracker.trackEvent("ap_cl_payment_success"),this.componentProps.onSuccess){const ie=new LoadingSuccess({onSuccess:this.componentProps.onSuccess}).element;this.element.append(ie)}}render(te){if(!te)throw new Error("Container element not found");te.appendChild(this.element)}destroy(){this.element.remove(),AstroPayCore.unregisterComponent(this)}}loadFonts();const serializedNodeIds=new WeakMap;function hasSerializedNode(ee){return serializedNodeIds.has(ee)}function nodeAndAncestorsHaveSerializedNode(ee){let re=ee;for(;re;){if(!hasSerializedNode(re)&&!isNodeShadowRoot(re))return!1;re=getParentNode(re)}return!0}function getSerializedNodeId(ee){return serializedNodeIds.get(ee)}function setSerializedNodeId(ee,re){serializedNodeIds.set(ee,re)}function getElementInputValue(ee,re){const te=ee.tagName,ne=ee.value;if(shouldMaskNode(ee,re)){const ie=ee.type;return te==="INPUT"&&(ie==="button"||ie==="submit"||ie==="reset")?ne:!ne||te==="OPTION"?void 0:CENSORED_STRING_MARK}if(te==="OPTION"||te==="SELECT")return ee.value;if(!(te!=="INPUT"&&te!=="TEXTAREA"))return ne}const URL_IN_CSS_REF=/url\((?:(')([^']*)'|(")([^"]*)"|([^)]*))\)/gm,ABSOLUTE_URL=/^[A-Za-z]+:|^\/\//,DATA_URI=/^data:.*,/i;function switchToAbsoluteUrl(ee,re){return ee.replace(URL_IN_CSS_REF,(te,ne,ie,oe,se,ae)=>{const ue=ie||se||ae;if(!re||!ue||ABSOLUTE_URL.test(ue)||DATA_URI.test(ue))return te;const ce=ne||oe||"";return`url(${ce}${makeUrlAbsolute(ue,re)}${ce})`})}function makeUrlAbsolute(ee,re){try{return buildUrl(ee,re).href}catch{return ee}}const TAG_NAME_REGEX=/[^a-z1-6-_]/;function getValidTagName(ee){const re=ee.toLowerCase().trim();return TAG_NAME_REGEX.test(re)?"div":re}function censoredImageForSize(ee,re){return`data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${ee}' height='${re}' style='background-color:silver'%3E%3C/svg%3E`}const RecordType={FullSnapshot:2,IncrementalSnapshot:3,Meta:4,Focus:6,ViewEnd:7,VisualViewport:8,FrustrationRecord:9},NodeType={Document:0,DocumentType:1,Element:2,Text:3,CDATA:4,DocumentFragment:11},IncrementalSource={Mutation:0,MouseMove:1,MouseInteraction:2,Scroll:3,ViewportResize:4,Input:5,TouchMove:6,MediaInteraction:7,StyleSheetRule:8},MouseInteractionType={MouseUp:0,MouseDown:1,Click:2,ContextMenu:3,DblClick:4,Focus:5,Blur:6,TouchStart:7,TouchEnd:9},MediaInteractionType={Play:0,Pause:1};function serializeStyleSheets(ee){if(!(ee===void 0||ee.length===0))return ee.map(re=>{const te=re.cssRules||re.rules;return{cssRules:Array.from(te,oe=>oe.cssText),disabled:re.disabled||void 0,media:re.media.length>0?Array.from(re.media):void 0}})}function serializeAttribute(ee,re,te,ne){if(re===NodePrivacyLevel.HIDDEN)return null;const ie=ee.getAttribute(te);if(re===NodePrivacyLevel.MASK&&te!==PRIVACY_ATTR_NAME&&!STABLE_ATTRIBUTES.includes(te)&&te!==ne.actionNameAttribute){const oe=ee.tagName;switch(te){case"title":case"alt":case"placeholder":return CENSORED_STRING_MARK}if(oe==="IMG"&&(te==="src"||te==="srcset")){const se=ee;if(se.naturalWidth>0)return censoredImageForSize(se.naturalWidth,se.naturalHeight);const{width:ae,height:ue}=ee.getBoundingClientRect();return ae>0||ue>0?censoredImageForSize(ae,ue):CENSORED_IMG_MARK}if(oe==="SOURCE"&&(te==="src"||te==="srcset"))return CENSORED_IMG_MARK;if(oe==="A"&&te==="href"||ie&&te.startsWith("data-")||oe==="IFRAME"&&te==="srcdoc")return CENSORED_STRING_MARK}return!ie||typeof ie!="string"?ie:isLongDataUrl(ie)?sanitizeDataUrl(ie):ie}function serializeAttributes(ee,re,te){if(re===NodePrivacyLevel.HIDDEN)return{};const ne={},ie=getValidTagName(ee.tagName),oe=ee.ownerDocument;for(let le=0;le<ee.attributes.length;le+=1){const fe=ee.attributes.item(le).name,he=serializeAttribute(ee,re,fe,te.configuration);he!==null&&(ne[fe]=he)}if(ee.value&&(ie==="textarea"||ie==="select"||ie==="option"||ie==="input")){const le=getElementInputValue(ee,re);le!==void 0&&(ne.value=le)}if(ie==="option"&&re===NodePrivacyLevel.ALLOW){const le=ee;le.selected&&(ne.selected=le.selected)}if(ie==="link"){const le=Array.from(oe.styleSheets).find(fe=>fe.href===ee.href),de=getCssRulesString(le);de&&le&&(ne._cssText=de)}if(ie==="style"&&ee.sheet){const le=getCssRulesString(ee.sheet);le&&(ne._cssText=le)}const se=ee;if(ie==="input"&&(se.type==="radio"||se.type==="checkbox")&&(re===NodePrivacyLevel.ALLOW?ne.checked=!!se.checked:shouldMaskNode(se,re)&&delete ne.checked),ie==="audio"||ie==="video"){const le=ee;ne.rr_mediaState=le.paused?"paused":"played"}let ae,ue;const ce=te.serializationContext;switch(ce.status){case 0:ae=Math.round(ee.scrollTop),ue=Math.round(ee.scrollLeft),(ae||ue)&&ce.elementsScrollPositions.set(ee,{scrollTop:ae,scrollLeft:ue});break;case 1:ce.elementsScrollPositions.has(ee)&&({scrollTop:ae,scrollLeft:ue}=ce.elementsScrollPositions.get(ee));break}return ue&&(ne.rr_scrollLeft=ue),ae&&(ne.rr_scrollTop=ae),ne}function getCssRulesString(ee){if(!ee)return null;let re;try{re=ee.rules||ee.cssRules}catch{}if(!re)return null;const te=Array.from(re,isSafari()?getCssRuleStringForSafari:getCssRuleString).join("");return switchToAbsoluteUrl(te,ee.href)}function getCssRuleStringForSafari(ee){if(isCSSStyleRule(ee)&&ee.selectorText.includes(":")){const re=/(\[[\w-]+[^\\])(:[^\]]+\])/g;return ee.cssText.replace(re,"$1\\$2")}return getCssRuleString(ee)}function getCssRuleString(ee){return isCSSImportRule(ee)&&getCssRulesString(ee.styleSheet)||ee.cssText}function isCSSImportRule(ee){return"styleSheet"in ee}function isCSSStyleRule(ee){return"selectorText"in ee}function serializeNodeWithId(ee,re){const te=serializeNode(ee,re);if(!te)return null;const ne=getSerializedNodeId(ee)||generateNextId(),ie=te;return ie.id=ne,setSerializedNodeId(ee,ne),re.serializedNodeIds&&re.serializedNodeIds.add(ne),ie}let _nextId=1;function generateNextId(){return _nextId++}function serializeChildNodes(ee,re){const te=[];return forEachChildNodes(ee,ne=>{const ie=serializeNodeWithId(ne,re);ie&&te.push(ie)}),te}function serializeNode(ee,re){switch(ee.nodeType){case ee.DOCUMENT_NODE:return serializeDocumentNode(ee,re);case ee.DOCUMENT_FRAGMENT_NODE:return serializeDocumentFragmentNode(ee,re);case ee.DOCUMENT_TYPE_NODE:return serializeDocumentTypeNode(ee);case ee.ELEMENT_NODE:return serializeElementNode(ee,re);case ee.TEXT_NODE:return serializeTextNode(ee,re);case ee.CDATA_SECTION_NODE:return serializeCDataNode()}}function serializeDocumentNode(ee,re){return{type:NodeType.Document,childNodes:serializeChildNodes(ee,re),adoptedStyleSheets:serializeStyleSheets(ee.adoptedStyleSheets)}}function serializeDocumentFragmentNode(ee,re){const te=isNodeShadowRoot(ee);return te&&re.serializationContext.shadowRootsController.addShadowRoot(ee),{type:NodeType.DocumentFragment,childNodes:serializeChildNodes(ee,re),isShadowRoot:te,adoptedStyleSheets:te?serializeStyleSheets(ee.adoptedStyleSheets):void 0}}function serializeDocumentTypeNode(ee){return{type:NodeType.DocumentType,name:ee.name,publicId:ee.publicId,systemId:ee.systemId}}function serializeElementNode(ee,re){const te=getValidTagName(ee.tagName),ne=isSVGElement(ee)||void 0,ie=reducePrivacyLevel(getNodeSelfPrivacyLevel(ee),re.parentNodePrivacyLevel);if(ie===NodePrivacyLevel.HIDDEN){const{width:ae,height:ue}=ee.getBoundingClientRect();return{type:NodeType.Element,tagName:te,attributes:{rr_width:`${ae}px`,rr_height:`${ue}px`,[PRIVACY_ATTR_NAME]:PRIVACY_ATTR_VALUE_HIDDEN},childNodes:[],isSVG:ne}}if(ie===NodePrivacyLevel.IGNORE)return;const oe=serializeAttributes(ee,ie,re);let se=[];if(hasChildNodes(ee)&&te!=="style"){let ae;re.parentNodePrivacyLevel===ie&&re.ignoreWhiteSpace===(te==="head")?ae=re:ae={...re,parentNodePrivacyLevel:ie,ignoreWhiteSpace:te==="head"},se=serializeChildNodes(ee,ae)}return{type:NodeType.Element,tagName:te,attributes:oe,childNodes:se,isSVG:ne}}function isSVGElement(ee){return ee.tagName==="svg"||ee instanceof SVGElement}function serializeTextNode(ee,re){const te=getTextContent(ee,re.ignoreWhiteSpace||!1,re.parentNodePrivacyLevel);if(te!==void 0)return{type:NodeType.Text,textContent:te}}function serializeCDataNode(){return{type:NodeType.CDATA,textContent:""}}function serializeDocument(ee,re,te){return serializeNodeWithId(ee,{serializationContext:te,parentNodePrivacyLevel:re.defaultPrivacyLevel,configuration:re})}function isTouchEvent(ee){return!!ee.changedTouches}function getEventTarget(ee){return ee.composed===!0&&isNodeShadowHost(ee.target)?ee.composedPath()[0]:ee.target}const TOLERANCE=25;function isVisualViewportFactoredIn(ee){return Math.abs(ee.pageTop-ee.offsetTop-window.scrollY)>TOLERANCE||Math.abs(ee.pageLeft-ee.offsetLeft-window.scrollX)>TOLERANCE}const convertMouseEventToLayoutCoordinates=(ee,re)=>{const te=window.visualViewport,ne={layoutViewportX:ee,layoutViewportY:re,visualViewportX:ee,visualViewportY:re};if(te)isVisualViewportFactoredIn(te)?(ne.layoutViewportX=Math.round(ee+te.offsetLeft),ne.layoutViewportY=Math.round(re+te.offsetTop)):(ne.visualViewportX=Math.round(ee-te.offsetLeft),ne.visualViewportY=Math.round(re-te.offsetTop));else return ne;return ne},getVisualViewport=ee=>({scale:ee.scale,offsetLeft:ee.offsetLeft,offsetTop:ee.offsetTop,pageLeft:ee.pageLeft,pageTop:ee.pageTop,height:ee.height,width:ee.width});function assembleIncrementalSnapshot(ee,re){return{data:{source:ee,...re},type:RecordType.IncrementalSnapshot,timestamp:timeStampNow()}}const MOUSE_MOVE_OBSERVER_THRESHOLD=50;function trackMove(ee,re){const{throttled:te,cancel:ne}=throttle$1(oe=>{const se=getEventTarget(oe);if(hasSerializedNode(se)){const ae=tryToComputeCoordinates(oe);if(!ae)return;const ue={id:getSerializedNodeId(se),timeOffset:0,x:ae.x,y:ae.y};re(assembleIncrementalSnapshot(isTouchEvent(oe)?IncrementalSource.TouchMove:IncrementalSource.MouseMove,{positions:[ue]}))}},MOUSE_MOVE_OBSERVER_THRESHOLD,{trailing:!1}),{stop:ie}=addEventListeners(ee,document,["mousemove","touchmove"],te,{capture:!0,passive:!0});return{stop:()=>{ie(),ne()}}}function tryToComputeCoordinates(ee){let{clientX:re,clientY:te}=isTouchEvent(ee)?ee.changedTouches[0]:ee;if(window.visualViewport){const{visualViewportX:ne,visualViewportY:ie}=convertMouseEventToLayoutCoordinates(re,te);re=ne,te=ie}if(!Number.isFinite(re)||!Number.isFinite(te)){ee.isTrusted&&addTelemetryDebug("mouse/touch event without x/y");return}return{x:re,y:te}}const eventTypeToMouseInteraction={pointerup:MouseInteractionType.MouseUp,mousedown:MouseInteractionType.MouseDown,click:MouseInteractionType.Click,contextmenu:MouseInteractionType.ContextMenu,dblclick:MouseInteractionType.DblClick,focus:MouseInteractionType.Focus,blur:MouseInteractionType.Blur,touchstart:MouseInteractionType.TouchStart,touchend:MouseInteractionType.TouchEnd};function trackMouseInteraction(ee,re,te){const ne=ie=>{const oe=getEventTarget(ie);if(getNodePrivacyLevel(oe,ee.defaultPrivacyLevel)===NodePrivacyLevel.HIDDEN||!hasSerializedNode(oe))return;const se=getSerializedNodeId(oe),ae=eventTypeToMouseInteraction[ie.type];let ue;if(ae!==MouseInteractionType.Blur&&ae!==MouseInteractionType.Focus){const le=tryToComputeCoordinates(ie);if(!le)return;ue={id:se,type:ae,x:le.x,y:le.y}}else ue={id:se,type:ae};const ce={id:te.getIdForEvent(ie),...assembleIncrementalSnapshot(IncrementalSource.MouseInteraction,ue)};re(ce)};return addEventListeners(ee,document,Object.keys(eventTypeToMouseInteraction),ne,{capture:!0,passive:!0})}const SCROLL_OBSERVER_THRESHOLD=100;function trackScroll(ee,re,te,ne=document){const{throttled:ie,cancel:oe}=throttle$1(ae=>{const ue=getEventTarget(ae);if(!ue||getNodePrivacyLevel(ue,ee.defaultPrivacyLevel)===NodePrivacyLevel.HIDDEN||!hasSerializedNode(ue))return;const ce=getSerializedNodeId(ue),le=ue===document?{scrollTop:getScrollY(),scrollLeft:getScrollX()}:{scrollTop:Math.round(ue.scrollTop),scrollLeft:Math.round(ue.scrollLeft)};te.set(ue,le),re(assembleIncrementalSnapshot(IncrementalSource.Scroll,{id:ce,x:le.scrollLeft,y:le.scrollTop}))},SCROLL_OBSERVER_THRESHOLD),{stop:se}=addEventListener$1(ee,ne,"scroll",ie,{capture:!0,passive:!0});return{stop:()=>{se(),oe()}}}const VISUAL_VIEWPORT_OBSERVER_THRESHOLD=200;function trackViewportResize(ee,re){const te=initViewportObservable(ee).subscribe(ne=>{re(assembleIncrementalSnapshot(IncrementalSource.ViewportResize,ne))});return{stop:()=>{te.unsubscribe()}}}function trackVisualViewportResize(ee,re){const te=window.visualViewport;if(!te)return{stop:noop$1};const{throttled:ne,cancel:ie}=throttle$1(()=>{re({data:getVisualViewport(te),type:RecordType.VisualViewport,timestamp:timeStampNow()})},VISUAL_VIEWPORT_OBSERVER_THRESHOLD,{trailing:!1}),{stop:oe}=addEventListeners(ee,te,["resize","scroll"],ne,{capture:!0,passive:!0});return{stop:()=>{oe(),ie()}}}function trackMediaInteraction(ee,re){return addEventListeners(ee,document,["play","pause"],te=>{const ne=getEventTarget(te);!ne||getNodePrivacyLevel(ne,ee.defaultPrivacyLevel)===NodePrivacyLevel.HIDDEN||!hasSerializedNode(ne)||re(assembleIncrementalSnapshot(IncrementalSource.MediaInteraction,{id:getSerializedNodeId(ne),type:te.type==="play"?MediaInteractionType.Play:MediaInteractionType.Pause}))},{capture:!0,passive:!0})}function trackStyleSheet(ee){function re(ie,oe){ie&&hasSerializedNode(ie.ownerNode)&&oe(getSerializedNodeId(ie.ownerNode))}const te=[instrumentMethod(CSSStyleSheet.prototype,"insertRule",({target:ie,parameters:[oe,se]})=>{re(ie,ae=>ee(assembleIncrementalSnapshot(IncrementalSource.StyleSheetRule,{id:ae,adds:[{rule:oe,index:se}]})))}),instrumentMethod(CSSStyleSheet.prototype,"deleteRule",({target:ie,parameters:[oe]})=>{re(ie,se=>ee(assembleIncrementalSnapshot(IncrementalSource.StyleSheetRule,{id:se,removes:[{index:oe}]})))})];typeof CSSGroupingRule<"u"?ne(CSSGroupingRule):(ne(CSSMediaRule),ne(CSSSupportsRule));function ne(ie){te.push(instrumentMethod(ie.prototype,"insertRule",({target:oe,parameters:[se,ae]})=>{re(oe.parentStyleSheet,ue=>{const ce=getPathToNestedCSSRule(oe);ce&&(ce.push(ae||0),ee(assembleIncrementalSnapshot(IncrementalSource.StyleSheetRule,{id:ue,adds:[{rule:se,index:ce}]})))})}),instrumentMethod(ie.prototype,"deleteRule",({target:oe,parameters:[se]})=>{re(oe.parentStyleSheet,ae=>{const ue=getPathToNestedCSSRule(oe);ue&&(ue.push(se),ee(assembleIncrementalSnapshot(IncrementalSource.StyleSheetRule,{id:ae,removes:[{index:ue}]})))})}))}return{stop:()=>{te.forEach(ie=>ie.stop())}}}function getPathToNestedCSSRule(ee){const re=[];let te=ee;for(;te.parentRule;){const se=Array.from(te.parentRule.cssRules).indexOf(te);re.unshift(se),te=te.parentRule}if(!te.parentStyleSheet)return;const ie=Array.from(te.parentStyleSheet.cssRules).indexOf(te);return re.unshift(ie),re}function trackFocus(ee,re){return addEventListeners(ee,window,["focus","blur"],()=>{re({data:{has_focus:document.hasFocus()},type:RecordType.Focus,timestamp:timeStampNow()})})}function trackFrustration(ee,re,te){const ne=ee.subscribe(12,ie=>{var oe,se;ie.rawRumEvent.type==="action"&&ie.rawRumEvent.action.type==="click"&&(!((se=(oe=ie.rawRumEvent.action.frustration)===null||oe===void 0?void 0:oe.type)===null||se===void 0)&&se.length)&&"events"in ie.domainContext&&ie.domainContext.events&&ie.domainContext.events.length&&re({timestamp:ie.rawRumEvent.date,type:RecordType.FrustrationRecord,data:{frustrationTypes:ie.rawRumEvent.action.frustration.type,recordIds:ie.domainContext.events.map(ae=>te.getIdForEvent(ae))}})});return{stop:()=>{ne.unsubscribe()}}}function trackViewEnd(ee,re){const te=ee.subscribe(5,()=>{re({timestamp:timeStampNow(),type:RecordType.ViewEnd})});return{stop:()=>{te.unsubscribe()}}}function trackInput(ee,re,te=document){const ne=ee.defaultPrivacyLevel,ie=new WeakMap,oe=te!==document,{stop:se}=addEventListeners(ee,te,oe?["change"]:["input","change"],le=>{const de=getEventTarget(le);(de instanceof HTMLInputElement||de instanceof HTMLTextAreaElement||de instanceof HTMLSelectElement)&&ue(de)},{capture:!0,passive:!0});let ae;if(oe)ae=noop$1;else{const le=[instrumentSetter(HTMLInputElement.prototype,"value",ue),instrumentSetter(HTMLInputElement.prototype,"checked",ue),instrumentSetter(HTMLSelectElement.prototype,"value",ue),instrumentSetter(HTMLTextAreaElement.prototype,"value",ue),instrumentSetter(HTMLSelectElement.prototype,"selectedIndex",ue)];ae=()=>{le.forEach(de=>de.stop())}}return{stop:()=>{ae(),se()}};function ue(le){const de=getNodePrivacyLevel(le,ne);if(de===NodePrivacyLevel.HIDDEN)return;const fe=le.type;let he;if(fe==="radio"||fe==="checkbox"){if(shouldMaskNode(le,de))return;he={isChecked:le.checked}}else{const ge=getElementInputValue(le,de);if(ge===void 0)return;he={text:ge}}ce(le,he);const pe=le.name;fe==="radio"&&pe&&le.checked&&document.querySelectorAll(`input[type="radio"][name="${CSS.escape(pe)}"]`).forEach(ge=>{ge!==le&&ce(ge,{isChecked:!1})})}function ce(le,de){if(!hasSerializedNode(le))return;const fe=ie.get(le);(!fe||fe.text!==de.text||fe.isChecked!==de.isChecked)&&(ie.set(le,de),re(assembleIncrementalSnapshot(IncrementalSource.Input,{id:getSerializedNodeId(le),...de})))}}const MUTATION_PROCESS_MAX_DELAY=100,MUTATION_PROCESS_MIN_DELAY=16;function createMutationBatch(ee){let re=noop$1,te=[];function ne(){re(),ee(te),te=[]}const{throttled:ie,cancel:oe}=throttle$1(ne,MUTATION_PROCESS_MIN_DELAY,{leading:!1});return{addMutations:se=>{te.length===0&&(re=requestIdleCallback(ie,{timeout:MUTATION_PROCESS_MAX_DELAY})),te.push(...se)},flush:ne,stop:()=>{re(),oe()}}}function trackMutation(ee,re,te,ne){const ie=getMutationObserverConstructor();if(!ie)return{stop:noop$1,flush:noop$1};const oe=createMutationBatch(ae=>{processMutations(ae.concat(se.takeRecords()),ee,re,te)}),se=new ie(monitor(oe.addMutations));return se.observe(ne,{attributeOldValue:!0,attributes:!0,characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0}),{stop:()=>{se.disconnect(),oe.stop()},flush:()=>{oe.flush()}}}function processMutations(ee,re,te,ne){const ie=new Map;ee.filter(de=>de.type==="childList").forEach(de=>{de.removedNodes.forEach(fe=>{traverseRemovedShadowDom(fe,ne.removeShadowRoot)})});const oe=ee.filter(de=>de.target.isConnected&&nodeAndAncestorsHaveSerializedNode(de.target)&&getNodePrivacyLevel(de.target,te.defaultPrivacyLevel,ie)!==NodePrivacyLevel.HIDDEN),{adds:se,removes:ae,hasBeenSerialized:ue}=processChildListMutations(oe.filter(de=>de.type==="childList"),te,ne,ie),ce=processCharacterDataMutations(oe.filter(de=>de.type==="characterData"&&!ue(de.target)),te,ie),le=processAttributesMutations(oe.filter(de=>de.type==="attributes"&&!ue(de.target)),te,ie);!ce.length&&!le.length&&!ae.length&&!se.length||re(assembleIncrementalSnapshot(IncrementalSource.Mutation,{adds:se,removes:ae,texts:ce,attributes:le}))}function processChildListMutations(ee,re,te,ne){const ie=new Set,oe=new Map;for(const fe of ee)fe.addedNodes.forEach(he=>{ie.add(he)}),fe.removedNodes.forEach(he=>{ie.has(he)||oe.set(he,fe.target),ie.delete(he)});const se=Array.from(ie);sortAddedAndMovedNodes(se);const ae=new Set,ue=[];for(const fe of se){if(le(fe))continue;const he=getNodePrivacyLevel(fe.parentNode,re.defaultPrivacyLevel,ne);if(he===NodePrivacyLevel.HIDDEN||he===NodePrivacyLevel.IGNORE)continue;const pe=serializeNodeWithId(fe,{serializedNodeIds:ae,parentNodePrivacyLevel:he,serializationContext:{status:2,shadowRootsController:te},configuration:re});if(!pe)continue;const ge=getParentNode(fe);ue.push({nextId:de(fe),parentId:getSerializedNodeId(ge),node:pe})}const ce=[];return oe.forEach((fe,he)=>{hasSerializedNode(he)&&ce.push({parentId:getSerializedNodeId(fe),id:getSerializedNodeId(he)})}),{adds:ue,removes:ce,hasBeenSerialized:le};function le(fe){return hasSerializedNode(fe)&&ae.has(getSerializedNodeId(fe))}function de(fe){let he=fe.nextSibling;for(;he;){if(hasSerializedNode(he))return getSerializedNodeId(he);he=he.nextSibling}return null}}function processCharacterDataMutations(ee,re,te){var ne;const ie=[],oe=new Set,se=ee.filter(ae=>oe.has(ae.target)?!1:(oe.add(ae.target),!0));for(const ae of se){if(ae.target.textContent===ae.oldValue)continue;const ce=getNodePrivacyLevel(getParentNode(ae.target),re.defaultPrivacyLevel,te);ce===NodePrivacyLevel.HIDDEN||ce===NodePrivacyLevel.IGNORE||ie.push({id:getSerializedNodeId(ae.target),value:(ne=getTextContent(ae.target,!1,ce))!==null&&ne!==void 0?ne:null})}return ie}function processAttributesMutations(ee,re,te){const ne=[],ie=new Map,oe=ee.filter(ae=>{const ue=ie.get(ae.target);return ue&&ue.has(ae.attributeName)?!1:(ue?ue.add(ae.attributeName):ie.set(ae.target,new Set([ae.attributeName])),!0)}),se=new Map;for(const ae of oe){if(ae.target.getAttribute(ae.attributeName)===ae.oldValue)continue;const ce=getNodePrivacyLevel(ae.target,re.defaultPrivacyLevel,te),le=serializeAttribute(ae.target,ce,ae.attributeName,re);let de;if(ae.attributeName==="value"){const he=getElementInputValue(ae.target,ce);if(he===void 0)continue;de=he}else typeof le=="string"?de=le:de=null;let fe=se.get(ae.target);fe||(fe={id:getSerializedNodeId(ae.target),attributes:{}},ne.push(fe),se.set(ae.target,fe)),fe.attributes[ae.attributeName]=de}return ne}function sortAddedAndMovedNodes(ee){ee.sort((re,te)=>{const ne=re.compareDocumentPosition(te);return ne&Node.DOCUMENT_POSITION_CONTAINED_BY?-1:ne&Node.DOCUMENT_POSITION_CONTAINS||ne&Node.DOCUMENT_POSITION_FOLLOWING?1:ne&Node.DOCUMENT_POSITION_PRECEDING?-1:0})}function traverseRemovedShadowDom(ee,re){isNodeShadowHost(ee)&&re(ee.shadowRoot),forEachChildNodes(ee,te=>traverseRemovedShadowDom(te,re))}function createElementsScrollPositions(){const ee=new WeakMap;return{set(re,te){re===document&&!document.scrollingElement||ee.set(re===document?document.scrollingElement:re,te)},get(re){return ee.get(re)},has(re){return ee.has(re)}}}const initShadowRootsController=(ee,re,te)=>{const ne=new Map,ie={addShadowRoot:oe=>{if(ne.has(oe))return;const se=trackMutation(re,ee,ie,oe),ae=trackInput(ee,re,oe),ue=trackScroll(ee,re,te,oe);ne.set(oe,{flush:()=>se.flush(),stop:()=>{se.stop(),ae.stop(),ue.stop()}})},removeShadowRoot:oe=>{const se=ne.get(oe);se&&(se.stop(),ne.delete(oe))},stop:()=>{ne.forEach(({stop:oe})=>oe())},flush:()=>{ne.forEach(({flush:oe})=>oe())}};return ie};function startFullSnapshots(ee,re,te,ne,ie,oe){const se=(ue=timeStampNow(),ce={status:0,elementsScrollPositions:ee,shadowRootsController:re})=>{const{width:le,height:de}=getViewportDimension(),fe=[{data:{height:de,href:window.location.href,width:le},type:RecordType.Meta,timestamp:ue},{data:{has_focus:document.hasFocus()},type:RecordType.Focus,timestamp:ue},{data:{node:serializeDocument(document,ne,ce),initialOffset:{left:getScrollX(),top:getScrollY()}},type:RecordType.FullSnapshot,timestamp:ue}];return window.visualViewport&&fe.push({data:getVisualViewport(window.visualViewport),type:RecordType.VisualViewport,timestamp:ue}),fe};oe(se());const{unsubscribe:ae}=te.subscribe(2,ue=>{ie(),oe(se(ue.startClocks.timeStamp,{shadowRootsController:re,status:1,elementsScrollPositions:ee}))});return{stop:ae}}function initRecordIds(){const ee=new WeakMap;let re=1;return{getIdForEvent(te){return ee.has(te)||ee.set(te,re++),ee.get(te)}}}function record(ee){const{emit:re,configuration:te,lifeCycle:ne}=ee;if(!re)throw new Error("emit function is required");const ie=fe=>{re(fe),sendToExtension("record",{record:fe});const he=ee.viewHistory.findView();addRecord(he.id)},oe=createElementsScrollPositions(),se=initShadowRootsController(te,ie,oe),{stop:ae}=startFullSnapshots(oe,se,ne,te,ue,fe=>fe.forEach(he=>ie(he)));function ue(){se.flush(),le.flush()}const ce=initRecordIds(),le=trackMutation(ie,te,se,document),de=[le,trackMove(te,ie),trackMouseInteraction(te,ie,ce),trackScroll(te,ie,oe,document),trackViewportResize(te,ie),trackInput(te,ie),trackMediaInteraction(te,ie),trackStyleSheet(ie),trackFocus(te,ie),trackVisualViewportResize(te,ie),trackFrustration(ne,ie,ce),trackViewEnd(ne,fe=>{ue(),ie(fe)})];return{stop:()=>{se.stop(),de.forEach(fe=>fe.stop()),ae()},flushMutations:ue,shadowRootsController:se}}function buildReplayPayload(ee,re,te){const ne=new FormData;ne.append("segment",new Blob([ee],{type:"application/octet-stream"}),`${re.session.id}-${re.start}`);const ie={raw_segment_size:te,compressed_segment_size:ee.byteLength,...re},oe=JSON.stringify(ie);return ne.append("event",new Blob([oe],{type:"application/json"})),{data:ne,bytesCount:ee.byteLength}}function createSegment({context:ee,creationReason:re,encoder:te}){let ne=0;const ie=ee.view.id,oe={start:1/0,end:-1/0,creation_reason:re,records_count:0,has_full_snapshot:!1,index_in_view:getSegmentsCount(ie),source:"browser",...ee};addSegment(ie);function se(ue,ce){oe.start=Math.min(oe.start,ue.timestamp),oe.end=Math.max(oe.end,ue.timestamp),oe.records_count+=1,oe.has_full_snapshot||(oe.has_full_snapshot=ue.type===RecordType.FullSnapshot);const le=te.isEmpty?'{"records":[':",";te.write(le+JSON.stringify(ue),de=>{ne+=de,ce(ne)})}function ae(ue){if(te.isEmpty)throw new Error("Empty segment flushed");te.write(`],${JSON.stringify(oe).slice(1)}
|
|
974
|
+
`;class AstroPayPayment extends Component{constructor(te){super({tag:"div",styles:ie=>getAstroPayPaymentStyles(ie)});Le(this,"loadingWrapper");Le(this,"componentProps");Le(this,"methodCode");this.componentProps={...te,country:te.country.trim().toUpperCase(),currency:te.currency.trim().toUpperCase()},this.methodCode="AP",AstroPayCore.registerComponent(this),AmplitudeAnalytics$1.astroPayPaymentImpression("AstroPayPayment"),this.loadingWrapper=document.createElement("div"),this.loadingWrapper.classList.add("loading-wrapper");const ne=new Loading({size:100,variant:"fetching",color:ThemeManager.getStyles().primaryColor}).element;this.loadingWrapper.append(ne),this.element.appendChild(this.loadingWrapper),DataDogTracker.trackEvent("ap_cl_astropay_payment_init"),this.createPayment()}async createPayment(){var te,ne;try{const{amount:ie,currency:oe,country:se,user:ae,order:ue}=this.componentProps,ce={country:se,currency:oe,amount:ie,user:ae,order:ue,methodCode:this.methodCode},le=await PaymentService.postCreatePayment(ce,"astropay_payment");this.renderAstroPayMethod(le)}catch(ie){const oe=ie;(ne=(te=this.componentProps)==null?void 0:te.onError)==null||ne.call(te);const se=new Typography({text:oe.description??oe.message,size:ThemeManager.getFontScale().xSmall,color:ThemeManager.getStyles().messages.error.textColor}).element;this.element.appendChild(se)}finally{this.loadingWrapper.remove()}}renderAstroPayMethod(te){const{paymentExternalId:ne,user:ie,countries:oe,benefits:se,metadata:ae}=te;this.element.innerHTML="";const ue={amount:this.componentProps.amount,currency:this.componentProps.currency},ce=new AstroPayPaymentMethod({paymentExternalId:ne,user:ie,countries:oe,benefits:se,paymentAmount:ue,actionLabel:ae==null?void 0:ae.actionLabel,onSuccess:le=>this.showSuccessContent(le)}).element;this.element.append(ce)}showSuccessContent(te){this.element.innerHTML="";const ne=document.createElement("div");if(ne.classList.add("payment-success-content"),te.forEach(ie=>ne.append(ie)),this.element.append(ne),DataDogTracker.trackEvent("ap_cl_payment_success"),this.componentProps.onSuccess){const ie=new LoadingSuccess({onSuccess:this.componentProps.onSuccess}).element;this.element.append(ie)}}render(te){if(!te)throw new Error("Container element not found");te.appendChild(this.element)}destroy(){this.element.remove(),AstroPayCore.unregisterComponent(this)}}loadFonts();const serializedNodeIds=new WeakMap;function hasSerializedNode(ee){return serializedNodeIds.has(ee)}function nodeAndAncestorsHaveSerializedNode(ee){let re=ee;for(;re;){if(!hasSerializedNode(re)&&!isNodeShadowRoot(re))return!1;re=getParentNode(re)}return!0}function getSerializedNodeId(ee){return serializedNodeIds.get(ee)}function setSerializedNodeId(ee,re){serializedNodeIds.set(ee,re)}function getElementInputValue(ee,re){const te=ee.tagName,ne=ee.value;if(shouldMaskNode(ee,re)){const ie=ee.type;return te==="INPUT"&&(ie==="button"||ie==="submit"||ie==="reset")?ne:!ne||te==="OPTION"?void 0:CENSORED_STRING_MARK}if(te==="OPTION"||te==="SELECT")return ee.value;if(!(te!=="INPUT"&&te!=="TEXTAREA"))return ne}const URL_IN_CSS_REF=/url\((?:(')([^']*)'|(")([^"]*)"|([^)]*))\)/gm,ABSOLUTE_URL=/^[A-Za-z]+:|^\/\//,DATA_URI=/^data:.*,/i;function switchToAbsoluteUrl(ee,re){return ee.replace(URL_IN_CSS_REF,(te,ne,ie,oe,se,ae)=>{const ue=ie||se||ae;if(!re||!ue||ABSOLUTE_URL.test(ue)||DATA_URI.test(ue))return te;const ce=ne||oe||"";return`url(${ce}${makeUrlAbsolute(ue,re)}${ce})`})}function makeUrlAbsolute(ee,re){try{return buildUrl(ee,re).href}catch{return ee}}const TAG_NAME_REGEX=/[^a-z1-6-_]/;function getValidTagName(ee){const re=ee.toLowerCase().trim();return TAG_NAME_REGEX.test(re)?"div":re}function censoredImageForSize(ee,re){return`data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${ee}' height='${re}' style='background-color:silver'%3E%3C/svg%3E`}const RecordType={FullSnapshot:2,IncrementalSnapshot:3,Meta:4,Focus:6,ViewEnd:7,VisualViewport:8,FrustrationRecord:9},NodeType={Document:0,DocumentType:1,Element:2,Text:3,CDATA:4,DocumentFragment:11},IncrementalSource={Mutation:0,MouseMove:1,MouseInteraction:2,Scroll:3,ViewportResize:4,Input:5,TouchMove:6,MediaInteraction:7,StyleSheetRule:8},MouseInteractionType={MouseUp:0,MouseDown:1,Click:2,ContextMenu:3,DblClick:4,Focus:5,Blur:6,TouchStart:7,TouchEnd:9},MediaInteractionType={Play:0,Pause:1};function serializeStyleSheets(ee){if(!(ee===void 0||ee.length===0))return ee.map(re=>{const te=re.cssRules||re.rules;return{cssRules:Array.from(te,oe=>oe.cssText),disabled:re.disabled||void 0,media:re.media.length>0?Array.from(re.media):void 0}})}function serializeAttribute(ee,re,te,ne){if(re===NodePrivacyLevel.HIDDEN)return null;const ie=ee.getAttribute(te);if(re===NodePrivacyLevel.MASK&&te!==PRIVACY_ATTR_NAME&&!STABLE_ATTRIBUTES.includes(te)&&te!==ne.actionNameAttribute){const oe=ee.tagName;switch(te){case"title":case"alt":case"placeholder":return CENSORED_STRING_MARK}if(oe==="IMG"&&(te==="src"||te==="srcset")){const se=ee;if(se.naturalWidth>0)return censoredImageForSize(se.naturalWidth,se.naturalHeight);const{width:ae,height:ue}=ee.getBoundingClientRect();return ae>0||ue>0?censoredImageForSize(ae,ue):CENSORED_IMG_MARK}if(oe==="SOURCE"&&(te==="src"||te==="srcset"))return CENSORED_IMG_MARK;if(oe==="A"&&te==="href"||ie&&te.startsWith("data-")||oe==="IFRAME"&&te==="srcdoc")return CENSORED_STRING_MARK}return!ie||typeof ie!="string"?ie:isLongDataUrl(ie)?sanitizeDataUrl(ie):ie}function serializeAttributes(ee,re,te){if(re===NodePrivacyLevel.HIDDEN)return{};const ne={},ie=getValidTagName(ee.tagName),oe=ee.ownerDocument;for(let le=0;le<ee.attributes.length;le+=1){const fe=ee.attributes.item(le).name,he=serializeAttribute(ee,re,fe,te.configuration);he!==null&&(ne[fe]=he)}if(ee.value&&(ie==="textarea"||ie==="select"||ie==="option"||ie==="input")){const le=getElementInputValue(ee,re);le!==void 0&&(ne.value=le)}if(ie==="option"&&re===NodePrivacyLevel.ALLOW){const le=ee;le.selected&&(ne.selected=le.selected)}if(ie==="link"){const le=Array.from(oe.styleSheets).find(fe=>fe.href===ee.href),de=getCssRulesString(le);de&&le&&(ne._cssText=de)}if(ie==="style"&&ee.sheet){const le=getCssRulesString(ee.sheet);le&&(ne._cssText=le)}const se=ee;if(ie==="input"&&(se.type==="radio"||se.type==="checkbox")&&(re===NodePrivacyLevel.ALLOW?ne.checked=!!se.checked:shouldMaskNode(se,re)&&delete ne.checked),ie==="audio"||ie==="video"){const le=ee;ne.rr_mediaState=le.paused?"paused":"played"}let ae,ue;const ce=te.serializationContext;switch(ce.status){case 0:ae=Math.round(ee.scrollTop),ue=Math.round(ee.scrollLeft),(ae||ue)&&ce.elementsScrollPositions.set(ee,{scrollTop:ae,scrollLeft:ue});break;case 1:ce.elementsScrollPositions.has(ee)&&({scrollTop:ae,scrollLeft:ue}=ce.elementsScrollPositions.get(ee));break}return ue&&(ne.rr_scrollLeft=ue),ae&&(ne.rr_scrollTop=ae),ne}function getCssRulesString(ee){if(!ee)return null;let re;try{re=ee.rules||ee.cssRules}catch{}if(!re)return null;const te=Array.from(re,isSafari()?getCssRuleStringForSafari:getCssRuleString).join("");return switchToAbsoluteUrl(te,ee.href)}function getCssRuleStringForSafari(ee){if(isCSSStyleRule(ee)&&ee.selectorText.includes(":")){const re=/(\[[\w-]+[^\\])(:[^\]]+\])/g;return ee.cssText.replace(re,"$1\\$2")}return getCssRuleString(ee)}function getCssRuleString(ee){return isCSSImportRule(ee)&&getCssRulesString(ee.styleSheet)||ee.cssText}function isCSSImportRule(ee){return"styleSheet"in ee}function isCSSStyleRule(ee){return"selectorText"in ee}function serializeNodeWithId(ee,re){const te=serializeNode(ee,re);if(!te)return null;const ne=getSerializedNodeId(ee)||generateNextId(),ie=te;return ie.id=ne,setSerializedNodeId(ee,ne),re.serializedNodeIds&&re.serializedNodeIds.add(ne),ie}let _nextId=1;function generateNextId(){return _nextId++}function serializeChildNodes(ee,re){const te=[];return forEachChildNodes(ee,ne=>{const ie=serializeNodeWithId(ne,re);ie&&te.push(ie)}),te}function serializeNode(ee,re){switch(ee.nodeType){case ee.DOCUMENT_NODE:return serializeDocumentNode(ee,re);case ee.DOCUMENT_FRAGMENT_NODE:return serializeDocumentFragmentNode(ee,re);case ee.DOCUMENT_TYPE_NODE:return serializeDocumentTypeNode(ee);case ee.ELEMENT_NODE:return serializeElementNode(ee,re);case ee.TEXT_NODE:return serializeTextNode(ee,re);case ee.CDATA_SECTION_NODE:return serializeCDataNode()}}function serializeDocumentNode(ee,re){return{type:NodeType.Document,childNodes:serializeChildNodes(ee,re),adoptedStyleSheets:serializeStyleSheets(ee.adoptedStyleSheets)}}function serializeDocumentFragmentNode(ee,re){const te=isNodeShadowRoot(ee);return te&&re.serializationContext.shadowRootsController.addShadowRoot(ee),{type:NodeType.DocumentFragment,childNodes:serializeChildNodes(ee,re),isShadowRoot:te,adoptedStyleSheets:te?serializeStyleSheets(ee.adoptedStyleSheets):void 0}}function serializeDocumentTypeNode(ee){return{type:NodeType.DocumentType,name:ee.name,publicId:ee.publicId,systemId:ee.systemId}}function serializeElementNode(ee,re){const te=getValidTagName(ee.tagName),ne=isSVGElement(ee)||void 0,ie=reducePrivacyLevel(getNodeSelfPrivacyLevel(ee),re.parentNodePrivacyLevel);if(ie===NodePrivacyLevel.HIDDEN){const{width:ae,height:ue}=ee.getBoundingClientRect();return{type:NodeType.Element,tagName:te,attributes:{rr_width:`${ae}px`,rr_height:`${ue}px`,[PRIVACY_ATTR_NAME]:PRIVACY_ATTR_VALUE_HIDDEN},childNodes:[],isSVG:ne}}if(ie===NodePrivacyLevel.IGNORE)return;const oe=serializeAttributes(ee,ie,re);let se=[];if(hasChildNodes(ee)&&te!=="style"){let ae;re.parentNodePrivacyLevel===ie&&re.ignoreWhiteSpace===(te==="head")?ae=re:ae={...re,parentNodePrivacyLevel:ie,ignoreWhiteSpace:te==="head"},se=serializeChildNodes(ee,ae)}return{type:NodeType.Element,tagName:te,attributes:oe,childNodes:se,isSVG:ne}}function isSVGElement(ee){return ee.tagName==="svg"||ee instanceof SVGElement}function serializeTextNode(ee,re){const te=getTextContent(ee,re.ignoreWhiteSpace||!1,re.parentNodePrivacyLevel);if(te!==void 0)return{type:NodeType.Text,textContent:te}}function serializeCDataNode(){return{type:NodeType.CDATA,textContent:""}}function serializeDocument(ee,re,te){return serializeNodeWithId(ee,{serializationContext:te,parentNodePrivacyLevel:re.defaultPrivacyLevel,configuration:re})}function isTouchEvent(ee){return!!ee.changedTouches}function getEventTarget(ee){return ee.composed===!0&&isNodeShadowHost(ee.target)?ee.composedPath()[0]:ee.target}const TOLERANCE=25;function isVisualViewportFactoredIn(ee){return Math.abs(ee.pageTop-ee.offsetTop-window.scrollY)>TOLERANCE||Math.abs(ee.pageLeft-ee.offsetLeft-window.scrollX)>TOLERANCE}const convertMouseEventToLayoutCoordinates=(ee,re)=>{const te=window.visualViewport,ne={layoutViewportX:ee,layoutViewportY:re,visualViewportX:ee,visualViewportY:re};if(te)isVisualViewportFactoredIn(te)?(ne.layoutViewportX=Math.round(ee+te.offsetLeft),ne.layoutViewportY=Math.round(re+te.offsetTop)):(ne.visualViewportX=Math.round(ee-te.offsetLeft),ne.visualViewportY=Math.round(re-te.offsetTop));else return ne;return ne},getVisualViewport=ee=>({scale:ee.scale,offsetLeft:ee.offsetLeft,offsetTop:ee.offsetTop,pageLeft:ee.pageLeft,pageTop:ee.pageTop,height:ee.height,width:ee.width});function assembleIncrementalSnapshot(ee,re){return{data:{source:ee,...re},type:RecordType.IncrementalSnapshot,timestamp:timeStampNow()}}const MOUSE_MOVE_OBSERVER_THRESHOLD=50;function trackMove(ee,re){const{throttled:te,cancel:ne}=throttle$1(oe=>{const se=getEventTarget(oe);if(hasSerializedNode(se)){const ae=tryToComputeCoordinates(oe);if(!ae)return;const ue={id:getSerializedNodeId(se),timeOffset:0,x:ae.x,y:ae.y};re(assembleIncrementalSnapshot(isTouchEvent(oe)?IncrementalSource.TouchMove:IncrementalSource.MouseMove,{positions:[ue]}))}},MOUSE_MOVE_OBSERVER_THRESHOLD,{trailing:!1}),{stop:ie}=addEventListeners(ee,document,["mousemove","touchmove"],te,{capture:!0,passive:!0});return{stop:()=>{ie(),ne()}}}function tryToComputeCoordinates(ee){let{clientX:re,clientY:te}=isTouchEvent(ee)?ee.changedTouches[0]:ee;if(window.visualViewport){const{visualViewportX:ne,visualViewportY:ie}=convertMouseEventToLayoutCoordinates(re,te);re=ne,te=ie}if(!Number.isFinite(re)||!Number.isFinite(te)){ee.isTrusted&&addTelemetryDebug("mouse/touch event without x/y");return}return{x:re,y:te}}const eventTypeToMouseInteraction={pointerup:MouseInteractionType.MouseUp,mousedown:MouseInteractionType.MouseDown,click:MouseInteractionType.Click,contextmenu:MouseInteractionType.ContextMenu,dblclick:MouseInteractionType.DblClick,focus:MouseInteractionType.Focus,blur:MouseInteractionType.Blur,touchstart:MouseInteractionType.TouchStart,touchend:MouseInteractionType.TouchEnd};function trackMouseInteraction(ee,re,te){const ne=ie=>{const oe=getEventTarget(ie);if(getNodePrivacyLevel(oe,ee.defaultPrivacyLevel)===NodePrivacyLevel.HIDDEN||!hasSerializedNode(oe))return;const se=getSerializedNodeId(oe),ae=eventTypeToMouseInteraction[ie.type];let ue;if(ae!==MouseInteractionType.Blur&&ae!==MouseInteractionType.Focus){const le=tryToComputeCoordinates(ie);if(!le)return;ue={id:se,type:ae,x:le.x,y:le.y}}else ue={id:se,type:ae};const ce={id:te.getIdForEvent(ie),...assembleIncrementalSnapshot(IncrementalSource.MouseInteraction,ue)};re(ce)};return addEventListeners(ee,document,Object.keys(eventTypeToMouseInteraction),ne,{capture:!0,passive:!0})}const SCROLL_OBSERVER_THRESHOLD=100;function trackScroll(ee,re,te,ne=document){const{throttled:ie,cancel:oe}=throttle$1(ae=>{const ue=getEventTarget(ae);if(!ue||getNodePrivacyLevel(ue,ee.defaultPrivacyLevel)===NodePrivacyLevel.HIDDEN||!hasSerializedNode(ue))return;const ce=getSerializedNodeId(ue),le=ue===document?{scrollTop:getScrollY(),scrollLeft:getScrollX()}:{scrollTop:Math.round(ue.scrollTop),scrollLeft:Math.round(ue.scrollLeft)};te.set(ue,le),re(assembleIncrementalSnapshot(IncrementalSource.Scroll,{id:ce,x:le.scrollLeft,y:le.scrollTop}))},SCROLL_OBSERVER_THRESHOLD),{stop:se}=addEventListener$1(ee,ne,"scroll",ie,{capture:!0,passive:!0});return{stop:()=>{se(),oe()}}}const VISUAL_VIEWPORT_OBSERVER_THRESHOLD=200;function trackViewportResize(ee,re){const te=initViewportObservable(ee).subscribe(ne=>{re(assembleIncrementalSnapshot(IncrementalSource.ViewportResize,ne))});return{stop:()=>{te.unsubscribe()}}}function trackVisualViewportResize(ee,re){const te=window.visualViewport;if(!te)return{stop:noop$1};const{throttled:ne,cancel:ie}=throttle$1(()=>{re({data:getVisualViewport(te),type:RecordType.VisualViewport,timestamp:timeStampNow()})},VISUAL_VIEWPORT_OBSERVER_THRESHOLD,{trailing:!1}),{stop:oe}=addEventListeners(ee,te,["resize","scroll"],ne,{capture:!0,passive:!0});return{stop:()=>{oe(),ie()}}}function trackMediaInteraction(ee,re){return addEventListeners(ee,document,["play","pause"],te=>{const ne=getEventTarget(te);!ne||getNodePrivacyLevel(ne,ee.defaultPrivacyLevel)===NodePrivacyLevel.HIDDEN||!hasSerializedNode(ne)||re(assembleIncrementalSnapshot(IncrementalSource.MediaInteraction,{id:getSerializedNodeId(ne),type:te.type==="play"?MediaInteractionType.Play:MediaInteractionType.Pause}))},{capture:!0,passive:!0})}function trackStyleSheet(ee){function re(ie,oe){ie&&hasSerializedNode(ie.ownerNode)&&oe(getSerializedNodeId(ie.ownerNode))}const te=[instrumentMethod(CSSStyleSheet.prototype,"insertRule",({target:ie,parameters:[oe,se]})=>{re(ie,ae=>ee(assembleIncrementalSnapshot(IncrementalSource.StyleSheetRule,{id:ae,adds:[{rule:oe,index:se}]})))}),instrumentMethod(CSSStyleSheet.prototype,"deleteRule",({target:ie,parameters:[oe]})=>{re(ie,se=>ee(assembleIncrementalSnapshot(IncrementalSource.StyleSheetRule,{id:se,removes:[{index:oe}]})))})];typeof CSSGroupingRule<"u"?ne(CSSGroupingRule):(ne(CSSMediaRule),ne(CSSSupportsRule));function ne(ie){te.push(instrumentMethod(ie.prototype,"insertRule",({target:oe,parameters:[se,ae]})=>{re(oe.parentStyleSheet,ue=>{const ce=getPathToNestedCSSRule(oe);ce&&(ce.push(ae||0),ee(assembleIncrementalSnapshot(IncrementalSource.StyleSheetRule,{id:ue,adds:[{rule:se,index:ce}]})))})}),instrumentMethod(ie.prototype,"deleteRule",({target:oe,parameters:[se]})=>{re(oe.parentStyleSheet,ae=>{const ue=getPathToNestedCSSRule(oe);ue&&(ue.push(se),ee(assembleIncrementalSnapshot(IncrementalSource.StyleSheetRule,{id:ae,removes:[{index:ue}]})))})}))}return{stop:()=>{te.forEach(ie=>ie.stop())}}}function getPathToNestedCSSRule(ee){const re=[];let te=ee;for(;te.parentRule;){const se=Array.from(te.parentRule.cssRules).indexOf(te);re.unshift(se),te=te.parentRule}if(!te.parentStyleSheet)return;const ie=Array.from(te.parentStyleSheet.cssRules).indexOf(te);return re.unshift(ie),re}function trackFocus(ee,re){return addEventListeners(ee,window,["focus","blur"],()=>{re({data:{has_focus:document.hasFocus()},type:RecordType.Focus,timestamp:timeStampNow()})})}function trackFrustration(ee,re,te){const ne=ee.subscribe(12,ie=>{var oe,se;ie.rawRumEvent.type==="action"&&ie.rawRumEvent.action.type==="click"&&(!((se=(oe=ie.rawRumEvent.action.frustration)===null||oe===void 0?void 0:oe.type)===null||se===void 0)&&se.length)&&"events"in ie.domainContext&&ie.domainContext.events&&ie.domainContext.events.length&&re({timestamp:ie.rawRumEvent.date,type:RecordType.FrustrationRecord,data:{frustrationTypes:ie.rawRumEvent.action.frustration.type,recordIds:ie.domainContext.events.map(ae=>te.getIdForEvent(ae))}})});return{stop:()=>{ne.unsubscribe()}}}function trackViewEnd(ee,re){const te=ee.subscribe(5,()=>{re({timestamp:timeStampNow(),type:RecordType.ViewEnd})});return{stop:()=>{te.unsubscribe()}}}function trackInput(ee,re,te=document){const ne=ee.defaultPrivacyLevel,ie=new WeakMap,oe=te!==document,{stop:se}=addEventListeners(ee,te,oe?["change"]:["input","change"],le=>{const de=getEventTarget(le);(de instanceof HTMLInputElement||de instanceof HTMLTextAreaElement||de instanceof HTMLSelectElement)&&ue(de)},{capture:!0,passive:!0});let ae;if(oe)ae=noop$1;else{const le=[instrumentSetter(HTMLInputElement.prototype,"value",ue),instrumentSetter(HTMLInputElement.prototype,"checked",ue),instrumentSetter(HTMLSelectElement.prototype,"value",ue),instrumentSetter(HTMLTextAreaElement.prototype,"value",ue),instrumentSetter(HTMLSelectElement.prototype,"selectedIndex",ue)];ae=()=>{le.forEach(de=>de.stop())}}return{stop:()=>{ae(),se()}};function ue(le){const de=getNodePrivacyLevel(le,ne);if(de===NodePrivacyLevel.HIDDEN)return;const fe=le.type;let he;if(fe==="radio"||fe==="checkbox"){if(shouldMaskNode(le,de))return;he={isChecked:le.checked}}else{const ge=getElementInputValue(le,de);if(ge===void 0)return;he={text:ge}}ce(le,he);const pe=le.name;fe==="radio"&&pe&&le.checked&&document.querySelectorAll(`input[type="radio"][name="${CSS.escape(pe)}"]`).forEach(ge=>{ge!==le&&ce(ge,{isChecked:!1})})}function ce(le,de){if(!hasSerializedNode(le))return;const fe=ie.get(le);(!fe||fe.text!==de.text||fe.isChecked!==de.isChecked)&&(ie.set(le,de),re(assembleIncrementalSnapshot(IncrementalSource.Input,{id:getSerializedNodeId(le),...de})))}}const MUTATION_PROCESS_MAX_DELAY=100,MUTATION_PROCESS_MIN_DELAY=16;function createMutationBatch(ee){let re=noop$1,te=[];function ne(){re(),ee(te),te=[]}const{throttled:ie,cancel:oe}=throttle$1(ne,MUTATION_PROCESS_MIN_DELAY,{leading:!1});return{addMutations:se=>{te.length===0&&(re=requestIdleCallback(ie,{timeout:MUTATION_PROCESS_MAX_DELAY})),te.push(...se)},flush:ne,stop:()=>{re(),oe()}}}function trackMutation(ee,re,te,ne){const ie=getMutationObserverConstructor();if(!ie)return{stop:noop$1,flush:noop$1};const oe=createMutationBatch(ae=>{processMutations(ae.concat(se.takeRecords()),ee,re,te)}),se=new ie(monitor(oe.addMutations));return se.observe(ne,{attributeOldValue:!0,attributes:!0,characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0}),{stop:()=>{se.disconnect(),oe.stop()},flush:()=>{oe.flush()}}}function processMutations(ee,re,te,ne){const ie=new Map;ee.filter(de=>de.type==="childList").forEach(de=>{de.removedNodes.forEach(fe=>{traverseRemovedShadowDom(fe,ne.removeShadowRoot)})});const oe=ee.filter(de=>de.target.isConnected&&nodeAndAncestorsHaveSerializedNode(de.target)&&getNodePrivacyLevel(de.target,te.defaultPrivacyLevel,ie)!==NodePrivacyLevel.HIDDEN),{adds:se,removes:ae,hasBeenSerialized:ue}=processChildListMutations(oe.filter(de=>de.type==="childList"),te,ne,ie),ce=processCharacterDataMutations(oe.filter(de=>de.type==="characterData"&&!ue(de.target)),te,ie),le=processAttributesMutations(oe.filter(de=>de.type==="attributes"&&!ue(de.target)),te,ie);!ce.length&&!le.length&&!ae.length&&!se.length||re(assembleIncrementalSnapshot(IncrementalSource.Mutation,{adds:se,removes:ae,texts:ce,attributes:le}))}function processChildListMutations(ee,re,te,ne){const ie=new Set,oe=new Map;for(const fe of ee)fe.addedNodes.forEach(he=>{ie.add(he)}),fe.removedNodes.forEach(he=>{ie.has(he)||oe.set(he,fe.target),ie.delete(he)});const se=Array.from(ie);sortAddedAndMovedNodes(se);const ae=new Set,ue=[];for(const fe of se){if(le(fe))continue;const he=getNodePrivacyLevel(fe.parentNode,re.defaultPrivacyLevel,ne);if(he===NodePrivacyLevel.HIDDEN||he===NodePrivacyLevel.IGNORE)continue;const pe=serializeNodeWithId(fe,{serializedNodeIds:ae,parentNodePrivacyLevel:he,serializationContext:{status:2,shadowRootsController:te},configuration:re});if(!pe)continue;const ge=getParentNode(fe);ue.push({nextId:de(fe),parentId:getSerializedNodeId(ge),node:pe})}const ce=[];return oe.forEach((fe,he)=>{hasSerializedNode(he)&&ce.push({parentId:getSerializedNodeId(fe),id:getSerializedNodeId(he)})}),{adds:ue,removes:ce,hasBeenSerialized:le};function le(fe){return hasSerializedNode(fe)&&ae.has(getSerializedNodeId(fe))}function de(fe){let he=fe.nextSibling;for(;he;){if(hasSerializedNode(he))return getSerializedNodeId(he);he=he.nextSibling}return null}}function processCharacterDataMutations(ee,re,te){var ne;const ie=[],oe=new Set,se=ee.filter(ae=>oe.has(ae.target)?!1:(oe.add(ae.target),!0));for(const ae of se){if(ae.target.textContent===ae.oldValue)continue;const ce=getNodePrivacyLevel(getParentNode(ae.target),re.defaultPrivacyLevel,te);ce===NodePrivacyLevel.HIDDEN||ce===NodePrivacyLevel.IGNORE||ie.push({id:getSerializedNodeId(ae.target),value:(ne=getTextContent(ae.target,!1,ce))!==null&&ne!==void 0?ne:null})}return ie}function processAttributesMutations(ee,re,te){const ne=[],ie=new Map,oe=ee.filter(ae=>{const ue=ie.get(ae.target);return ue&&ue.has(ae.attributeName)?!1:(ue?ue.add(ae.attributeName):ie.set(ae.target,new Set([ae.attributeName])),!0)}),se=new Map;for(const ae of oe){if(ae.target.getAttribute(ae.attributeName)===ae.oldValue)continue;const ce=getNodePrivacyLevel(ae.target,re.defaultPrivacyLevel,te),le=serializeAttribute(ae.target,ce,ae.attributeName,re);let de;if(ae.attributeName==="value"){const he=getElementInputValue(ae.target,ce);if(he===void 0)continue;de=he}else typeof le=="string"?de=le:de=null;let fe=se.get(ae.target);fe||(fe={id:getSerializedNodeId(ae.target),attributes:{}},ne.push(fe),se.set(ae.target,fe)),fe.attributes[ae.attributeName]=de}return ne}function sortAddedAndMovedNodes(ee){ee.sort((re,te)=>{const ne=re.compareDocumentPosition(te);return ne&Node.DOCUMENT_POSITION_CONTAINED_BY?-1:ne&Node.DOCUMENT_POSITION_CONTAINS||ne&Node.DOCUMENT_POSITION_FOLLOWING?1:ne&Node.DOCUMENT_POSITION_PRECEDING?-1:0})}function traverseRemovedShadowDom(ee,re){isNodeShadowHost(ee)&&re(ee.shadowRoot),forEachChildNodes(ee,te=>traverseRemovedShadowDom(te,re))}function createElementsScrollPositions(){const ee=new WeakMap;return{set(re,te){re===document&&!document.scrollingElement||ee.set(re===document?document.scrollingElement:re,te)},get(re){return ee.get(re)},has(re){return ee.has(re)}}}const initShadowRootsController=(ee,re,te)=>{const ne=new Map,ie={addShadowRoot:oe=>{if(ne.has(oe))return;const se=trackMutation(re,ee,ie,oe),ae=trackInput(ee,re,oe),ue=trackScroll(ee,re,te,oe);ne.set(oe,{flush:()=>se.flush(),stop:()=>{se.stop(),ae.stop(),ue.stop()}})},removeShadowRoot:oe=>{const se=ne.get(oe);se&&(se.stop(),ne.delete(oe))},stop:()=>{ne.forEach(({stop:oe})=>oe())},flush:()=>{ne.forEach(({flush:oe})=>oe())}};return ie};function startFullSnapshots(ee,re,te,ne,ie,oe){const se=(ue=timeStampNow(),ce={status:0,elementsScrollPositions:ee,shadowRootsController:re})=>{const{width:le,height:de}=getViewportDimension(),fe=[{data:{height:de,href:window.location.href,width:le},type:RecordType.Meta,timestamp:ue},{data:{has_focus:document.hasFocus()},type:RecordType.Focus,timestamp:ue},{data:{node:serializeDocument(document,ne,ce),initialOffset:{left:getScrollX(),top:getScrollY()}},type:RecordType.FullSnapshot,timestamp:ue}];return window.visualViewport&&fe.push({data:getVisualViewport(window.visualViewport),type:RecordType.VisualViewport,timestamp:ue}),fe};oe(se());const{unsubscribe:ae}=te.subscribe(2,ue=>{ie(),oe(se(ue.startClocks.timeStamp,{shadowRootsController:re,status:1,elementsScrollPositions:ee}))});return{stop:ae}}function initRecordIds(){const ee=new WeakMap;let re=1;return{getIdForEvent(te){return ee.has(te)||ee.set(te,re++),ee.get(te)}}}function record(ee){const{emit:re,configuration:te,lifeCycle:ne}=ee;if(!re)throw new Error("emit function is required");const ie=fe=>{re(fe),sendToExtension("record",{record:fe});const he=ee.viewHistory.findView();addRecord(he.id)},oe=createElementsScrollPositions(),se=initShadowRootsController(te,ie,oe),{stop:ae}=startFullSnapshots(oe,se,ne,te,ue,fe=>fe.forEach(he=>ie(he)));function ue(){se.flush(),le.flush()}const ce=initRecordIds(),le=trackMutation(ie,te,se,document),de=[le,trackMove(te,ie),trackMouseInteraction(te,ie,ce),trackScroll(te,ie,oe,document),trackViewportResize(te,ie),trackInput(te,ie),trackMediaInteraction(te,ie),trackStyleSheet(ie),trackFocus(te,ie),trackVisualViewportResize(te,ie),trackFrustration(ne,ie,ce),trackViewEnd(ne,fe=>{ue(),ie(fe)})];return{stop:()=>{se.stop(),de.forEach(fe=>fe.stop()),ae()},flushMutations:ue,shadowRootsController:se}}function buildReplayPayload(ee,re,te){const ne=new FormData;ne.append("segment",new Blob([ee],{type:"application/octet-stream"}),`${re.session.id}-${re.start}`);const ie={raw_segment_size:te,compressed_segment_size:ee.byteLength,...re},oe=JSON.stringify(ie);return ne.append("event",new Blob([oe],{type:"application/json"})),{data:ne,bytesCount:ee.byteLength}}function createSegment({context:ee,creationReason:re,encoder:te}){let ne=0;const ie=ee.view.id,oe={start:1/0,end:-1/0,creation_reason:re,records_count:0,has_full_snapshot:!1,index_in_view:getSegmentsCount(ie),source:"browser",...ee};addSegment(ie);function se(ue,ce){oe.start=Math.min(oe.start,ue.timestamp),oe.end=Math.max(oe.end,ue.timestamp),oe.records_count+=1,oe.has_full_snapshot||(oe.has_full_snapshot=ue.type===RecordType.FullSnapshot);const le=te.isEmpty?'{"records":[':",";te.write(le+JSON.stringify(ue),de=>{ne+=de,ce(ne)})}function ae(ue){if(te.isEmpty)throw new Error("Empty segment flushed");te.write(`],${JSON.stringify(oe).slice(1)}
|
|
966
975
|
`),te.finish(ce=>{addWroteData(oe.view.id,ce.rawBytesCount),ue(oe,ce)})}return{addRecord:se,flush:ae}}const SEGMENT_DURATION_LIMIT=5*ONE_SECOND;let SEGMENT_BYTES_LIMIT=6e4;function startSegmentCollection(ee,re,te,ne,ie,oe){return doStartSegmentCollection(ee,()=>computeSegmentContext(re.applicationId,te,ne),ie,oe)}function doStartSegmentCollection(ee,re,te,ne){let ie={status:0,nextSegmentCreationReason:"init"};const{unsubscribe:oe}=ee.subscribe(2,()=>{ae("view_change")}),{unsubscribe:se}=ee.subscribe(11,ue=>{ae(ue.reason)});function ae(ue){ie.status===1&&(ie.segment.flush((ce,le)=>{const de=buildReplayPayload(le.output,ce,le.rawBytesCount);isPageExitReason(ue)?te.sendOnExit(de):te.send(de)}),clearTimeout$1(ie.expirationTimeoutId)),ue!=="stop"?ie={status:0,nextSegmentCreationReason:ue}:ie={status:2}}return{addRecord:ue=>{if(ie.status!==2){if(ie.status===0){const ce=re();if(!ce)return;ie={status:1,segment:createSegment({encoder:ne,context:ce,creationReason:ie.nextSegmentCreationReason}),expirationTimeoutId:setTimeout$1(()=>{ae("segment_duration_limit")},SEGMENT_DURATION_LIMIT)}}ie.segment.addRecord(ue,ce=>{ce>SEGMENT_BYTES_LIMIT&&ae("segment_bytes_limit")})}},stop:()=>{ae("stop"),oe(),se()}}}function computeSegmentContext(ee,re,te){const ne=re.findTrackedSession(),ie=te.findView();if(!(!ne||!ie))return{application:{id:ee},session:{id:ne.id},view:{id:ie.id}}}function startRecordBridge(ee){const re=getEventBridge();return{addRecord:te=>{const ne=ee.findView();re.send("record",te,ne.id)}}}function startRecording(ee,re,te,ne,ie,oe){const se=[],ae=de=>{ee.notify(14,{error:de}),addTelemetryDebug("Error reported to customer",{"error.message":de.message})},ue=oe||createHttpRequest(re.sessionReplayEndpointBuilder,SEGMENT_BYTES_LIMIT,ae);let ce;if(canUseEventBridge())({addRecord:ce}=startRecordBridge(ne));else{const de=startSegmentCollection(ee,re,te,ne,ue,ie);ce=de.addRecord,se.push(de.stop)}const{stop:le}=record({emit:ce,configuration:re,lifeCycle:ee,viewHistory:ne});return se.push(le),{stop:()=>{se.forEach(de=>de())}}}const startRecording$1=Object.freeze(Object.defineProperty({__proto__:null,startRecording},Symbol.toStringTag,{value:"Module"}));function getNumberOfSamples(ee){let re=0;for(const te of ee)te.stackId!==void 0&&re++;return re}const registry=new Map;let enabledTime=!1;function enableLongTaskRegistry(){enabledTime=performance.now()}function disableLongTaskRegistry(){enabledTime=!1,registry.clear()}function setLongTaskId(ee,re){registry.set(re,ee)}function getLongTaskId(ee){if(!(enabledTime===!1||ee.startTime<enabledTime))return registry.get(ee.startTime)}function deleteLongTaskIdsBefore(ee){if(!(enabledTime===!1||ee<enabledTime))for(const re of registry.keys())re<ee&®istry.delete(re)}function mayStoreLongTaskIdForProfilerCorrelation({rawRumEvent:ee,startTime:re}){if(ee.type!=="long_task")return;const te=ee.long_task.id;setLongTaskId(te,re)}const sendProfile=(ee,re,te,ne)=>{const ie=buildProfileEvent(ee,re,te,ne),oe=buildProfilingPayload(ee,ie),se=re.build("fetch",oe);return addTelemetryDebug("Sending profile to public profiling intake",{profilingIntakeURL:se,applicationId:te,sessionId:ne}),fetch(se,{body:oe.data,method:"POST"})};function buildProfileEvent(ee,re,te,ne){const ie=re.tags,oe=buildProfileEventAttributes(ee,te,ne),se=buildProfileEventTags(ie),ae=new Date(ee.timeOrigin+ee.startTime),ue=new Date(ee.timeOrigin+ee.endTime);return{...oe,attachments:["wall-time.json"],start:ae.toISOString(),end:ue.toISOString(),family:"chrome",runtime:"chrome",format:"json",version:4,tags_profiler:se.join(",")}}function buildProfileEventTags(ee){return ee.concat(["language:javascript","runtime:chrome","family:chrome","host:browser"])}function buildProfilingPayload(ee,re){const te=new Blob([JSON.stringify(ee)],{type:"application/json"}),ne=new FormData;return ne.append("event",new Blob([JSON.stringify(re)],{type:"application/json"}),"event.json"),ne.append("wall-time.json",te,"wall-time.json"),{data:ne,bytesCount:0}}function buildProfileEventAttributes(ee,re,te){const ne={application:{id:re}};te&&(ne.session={id:te});const ie=Array.from(new Set(ee.views.map(se=>se.viewId)));ie.length&&(ne.view={id:ie});const oe=ee.longTasks.map(se=>getLongTaskId(se)).filter(se=>se!==void 0);return oe.length&&(ne.long_task={id:oe}),ne}const transport={sendProfile},DEFAULT_RUM_PROFILER_CONFIGURATION={sampleIntervalMs:10,collectIntervalMs:6e4,minProfileDurationMs:5e3,minNumberOfSamples:50};function createRumProfiler(ee,re,te,ne=DEFAULT_RUM_PROFILER_CONFIGURATION){const ie=supportPerformanceTimingEvent(RumPerformanceEntryType.LONG_ANIMATION_FRAME);let oe;const se=[];let ae={state:"stopped"};function ue(Ce){ae.state!=="running"&&(oe=Ce?{startTime:Ce.startClocks.relative,viewId:Ce.id,viewName:Ce.name}:void 0,se.push(addEventListener$1(ee,window,"visibilitychange",_e).stop,addEventListener$1(ee,window,"beforeunload",be).stop),de())}async function ce(){await he("stopped"),disableLongTaskRegistry(),se.forEach(Ce=>Ce())}function le(Ce){if(Ce.state==="running")return{cleanupTasks:Ce.cleanupTasks,observer:Ce.observer};const we=[];let xe;if(ee.trackLongTasks){xe=new PerformanceObserver(ye),xe.observe({entryTypes:[Ie()]});const Ue=re.subscribe(12,$e=>{mayStoreLongTaskIdForProfilerCorrelation($e)});enableLongTaskRegistry(),we.push(()=>xe==null?void 0:xe.disconnect()),we.push(Ue.unsubscribe)}const Ne=re.subscribe(2,Ue=>{pe({viewId:Ue.id,viewName:Ue.name,startTime:Ue.startClocks.relative})});return we.push(Ne.unsubscribe),{cleanupTasks:we,observer:xe}}function de(){const Ce=getGlobalObject().Profiler;if(!Ce)throw new Error("RUM Profiler is not supported in this browser.");fe(ae).catch(monitorError);const{cleanupTasks:we,observer:xe}=le(ae);let Ne;try{Ne=new Ce({sampleInterval:ne.sampleIntervalMs,maxBufferSize:Math.round(ne.collectIntervalMs*1.5/ne.sampleIntervalMs)})}catch(Ue){display.warn("[DD_RUM] Profiler startup failed. Ensure your server includes the `Document-Policy: js-profiling` response header when serving HTML pages.",Ue);return}ae={state:"running",startTime:performance.now(),profiler:Ne,timeoutId:setTimeout$1(de,ne.collectIntervalMs),longTasks:[],views:[],cleanupTasks:we,observer:xe},pe(oe),Ne.addEventListener("samplebufferfull",me)}async function fe(Ce){var we,xe;if(Ce.state!=="running")return;ve((xe=(we=Ce.observer)===null||we===void 0?void 0:we.takeRecords())!==null&&xe!==void 0?xe:[]),clearTimeout$1(Ce.timeoutId),Ce.profiler.removeEventListener("samplebufferfull",me);const{startTime:Ne,longTasks:Ue,views:$e}=Ce,Ve=performance.now();await Ce.profiler.stop().then(ze=>{const ur=performance.now(),Ge=Ue.length>0,hr=ur-Ne<ne.minProfileDurationMs,fr=getNumberOfSamples(ze.samples)<ne.minNumberOfSamples;!Ge&&(hr||fr)||(ge(Object.assign(ze,{startTime:Ne,endTime:ur,timeOrigin:performance.timeOrigin,longTasks:Ue,views:$e,sampleInterval:ne.sampleIntervalMs})),deleteLongTaskIdsBefore(Ve))}).catch(monitorError)}async function he(Ce){ae.state==="running"&&(ae.cleanupTasks.forEach(we=>we()),await fe(ae),ae={state:Ce})}function pe(Ce){ae.state!=="running"||!Ce||ae.views.push(Ce)}function ge(Ce){var we;const xe=(we=te.findTrackedSession())===null||we===void 0?void 0:we.id;transport.sendProfile(Ce,ee.profilingEndpointBuilder,ee.applicationId,xe).catch(monitorError)}function me(){de()}function ye(Ce){ve(Ce.getEntries())}function ve(Ce){if(ae.state==="running")for(const we of Ce)we.duration<ne.sampleIntervalMs||ae.longTasks.push({id:getLongTaskId(we),duration:we.duration,entryType:we.entryType,startTime:we.startTime})}function _e(){document.visibilityState==="hidden"&&ae.state==="running"?he("paused").catch(monitorError):document.visibilityState==="visible"&&ae.state==="paused"&&de()}function be(){de()}function Ie(){return ie?"long-animation-frame":"longtask"}function Te(){return ae.state==="stopped"}function Se(){return ae.state==="running"}function Re(){return ae.state==="paused"}return{start:ue,stop:ce,isStopped:Te,isRunning:Se,isPaused:Re}}const profiler=Object.freeze(Object.defineProperty({__proto__:null,DEFAULT_RUM_PROFILER_CONFIGURATION,createRumProfiler},Symbol.toStringTag,{value:"Module"}));exports.AstroPayCardPayment=AstroPayCardPayment,exports.AstroPayCore=AstroPayCore,exports.AstroPayFullCheckout=AstroPayFullCheckout,exports.AstroPayPayment=AstroPayPayment,exports.Core=AstroPayCore,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"})}));
|
|
@@ -5866,7 +5866,7 @@ class FormTemplate extends Component {
|
|
|
5866
5866
|
const RUNTIME_CONFIG = {
|
|
5867
5867
|
test: {
|
|
5868
5868
|
NAME: "@astropay/payments-lib",
|
|
5869
|
-
VERSION: "2.0.
|
|
5869
|
+
VERSION: "2.0.5",
|
|
5870
5870
|
MODE: "test",
|
|
5871
5871
|
API_BASE_URL: "https://partners-api-tst.astropay.com/api",
|
|
5872
5872
|
RESOURCES_BUCKET: "https://rs-tst.astropay.com",
|
|
@@ -5876,7 +5876,7 @@ const RUNTIME_CONFIG = {
|
|
|
5876
5876
|
},
|
|
5877
5877
|
sandbox: {
|
|
5878
5878
|
NAME: "@astropay/payments-lib",
|
|
5879
|
-
VERSION: "2.0.
|
|
5879
|
+
VERSION: "2.0.5",
|
|
5880
5880
|
MODE: "staging",
|
|
5881
5881
|
API_BASE_URL: "https://partners-api-sandbox.astropay.com/api",
|
|
5882
5882
|
RESOURCES_BUCKET: "https://rs-tst.astropay.com",
|
|
@@ -5886,7 +5886,7 @@ const RUNTIME_CONFIG = {
|
|
|
5886
5886
|
},
|
|
5887
5887
|
production: {
|
|
5888
5888
|
NAME: "@astropay/payments-lib",
|
|
5889
|
-
VERSION: "2.0.
|
|
5889
|
+
VERSION: "2.0.5",
|
|
5890
5890
|
MODE: "production",
|
|
5891
5891
|
API_BASE_URL: "https://partners-api.astropay.com/api",
|
|
5892
5892
|
RESOURCES_BUCKET: "https://rs.astropay.com",
|
|
@@ -21602,7 +21602,7 @@ async function lazyLoadRecorder(ee = importRecorder) {
|
|
|
21602
21602
|
async function importRecorder() {
|
|
21603
21603
|
return (await import(
|
|
21604
21604
|
/* webpackChunkName: "recorder" */
|
|
21605
|
-
"./startRecording-
|
|
21605
|
+
"./startRecording-DjydAa5u.js"
|
|
21606
21606
|
)).startRecording;
|
|
21607
21607
|
}
|
|
21608
21608
|
function isProfilingSupported() {
|
|
@@ -21622,7 +21622,7 @@ async function lazyLoadProfiler(ee = importProfiler) {
|
|
|
21622
21622
|
async function importProfiler() {
|
|
21623
21623
|
return (await import(
|
|
21624
21624
|
/* webpackChunkName: "profiler" */
|
|
21625
|
-
"./profiler-
|
|
21625
|
+
"./profiler-BIAivRqj.js"
|
|
21626
21626
|
)).createRumProfiler;
|
|
21627
21627
|
}
|
|
21628
21628
|
function makeProfilerApi() {
|
|
@@ -29070,8 +29070,7 @@ class PollingService {
|
|
|
29070
29070
|
handleAccepted(re) {
|
|
29071
29071
|
if (this.isPollingActive) {
|
|
29072
29072
|
if (this.remainingAttempts = re.pollingMetadata.remainingHits, this.pollingAcceptedData = re, this.remainingAttempts <= 0) {
|
|
29073
|
-
|
|
29074
|
-
this.stopPolling(), this.onError(new Error(te));
|
|
29073
|
+
this.stopPolling(), this.onError(re.timeoutInfo);
|
|
29075
29074
|
return;
|
|
29076
29075
|
}
|
|
29077
29076
|
this.executePoll();
|
|
@@ -29290,16 +29289,15 @@ class CardPaymentMethod extends Component {
|
|
|
29290
29289
|
}, this.loadingWrapper = this.createLoadingWrapper(AstroPayI18n.translate("hold_on")), this.element.append(this.loadingWrapper), sessionStorage.getItem(EStorageKey.SESSION_ID) || sessionStorage.setItem(EStorageKey.SESSION_ID, uuid()), this.fetchPaymentMethodDetail();
|
|
29291
29290
|
}
|
|
29292
29291
|
async fetchPaymentMethodDetail() {
|
|
29293
|
-
var te, ne;
|
|
29294
29292
|
try {
|
|
29295
|
-
const
|
|
29293
|
+
const te = await PaymentMethodsService.getPaymentMethodDetail({
|
|
29296
29294
|
paymentExternalId: this.componentProps.paymentExternalId,
|
|
29297
29295
|
methodCode: this.componentProps.paymentMethod.code
|
|
29298
29296
|
});
|
|
29299
|
-
this.renderCardSection(
|
|
29300
|
-
} catch (
|
|
29301
|
-
const
|
|
29302
|
-
(ne
|
|
29297
|
+
this.renderCardSection(te.fields);
|
|
29298
|
+
} catch (te) {
|
|
29299
|
+
const ne = te;
|
|
29300
|
+
this.showErrorMessage(ne.description ?? ne.message);
|
|
29303
29301
|
} finally {
|
|
29304
29302
|
this.loadingWrapper.remove();
|
|
29305
29303
|
}
|
|
@@ -29394,10 +29392,10 @@ class CardPaymentMethod extends Component {
|
|
|
29394
29392
|
(ie = this.btnPay) == null || ie.setDisabled(!ne);
|
|
29395
29393
|
}
|
|
29396
29394
|
async handleSubmit() {
|
|
29397
|
-
var te, ne, ie, oe, se
|
|
29395
|
+
var te, ne, ie, oe, se;
|
|
29398
29396
|
try {
|
|
29399
29397
|
(te = this.btnPay) == null || te.setLoading(!0);
|
|
29400
|
-
const
|
|
29398
|
+
const ae = await this.handleTokenizeCard(), ue = {
|
|
29401
29399
|
paymentMethods: [
|
|
29402
29400
|
{
|
|
29403
29401
|
methodCode: this.componentProps.paymentMethod.code,
|
|
@@ -29407,23 +29405,23 @@ class CardPaymentMethod extends Component {
|
|
|
29407
29405
|
sessionId: sessionStorage.getItem(EStorageKey.SESSION_ID) || "",
|
|
29408
29406
|
...(ne = this.requiredFieldsForm) == null ? void 0 : ne.getFormData()
|
|
29409
29407
|
},
|
|
29410
|
-
cardData:
|
|
29408
|
+
cardData: ae
|
|
29411
29409
|
}
|
|
29412
29410
|
]
|
|
29413
29411
|
};
|
|
29414
29412
|
if ((ie = this.componentProps.paymentMethod) != null && ie.uri) {
|
|
29415
|
-
const { status:
|
|
29413
|
+
const { status: ce, reason: le } = await PaymentService.postGenericPayment(
|
|
29416
29414
|
this.componentProps.paymentMethod.uri,
|
|
29417
29415
|
this.componentProps.paymentExternalId,
|
|
29418
|
-
|
|
29416
|
+
ue
|
|
29419
29417
|
);
|
|
29420
|
-
if (
|
|
29418
|
+
if (ce === ECardPayStatus.PENDING)
|
|
29421
29419
|
await this.checkPaymentStatus(), (oe = this.btnPay) == null || oe.setLoading(!1), (se = this.btnPay) == null || se.setDisabled(!0);
|
|
29422
|
-
else throw new Error(
|
|
29420
|
+
else throw new Error(le || AstroPayI18n.translate("generic_error"));
|
|
29423
29421
|
} else throw new Error(AstroPayI18n.translate("generic_error"));
|
|
29424
|
-
} catch (
|
|
29425
|
-
const
|
|
29426
|
-
console.error(
|
|
29422
|
+
} catch (ae) {
|
|
29423
|
+
const ue = ae;
|
|
29424
|
+
console.error(ue.message), this.showErrorMessage(ue.description ?? ue.message), this.renderRetryButton();
|
|
29427
29425
|
}
|
|
29428
29426
|
}
|
|
29429
29427
|
async handleTokenizeCard() {
|
|
@@ -29462,7 +29460,7 @@ class CardPaymentMethod extends Component {
|
|
|
29462
29460
|
te.pollingStatus === EPollingStatus.ACCEPTED ? this.initializePollingService(te) : te.pollingStatus === EPollingStatus.FINISHED && this.handlePaymentSuccess(te);
|
|
29463
29461
|
} catch (te) {
|
|
29464
29462
|
const ne = te;
|
|
29465
|
-
this.showErrorMessage(ne.message), this.stopPolling();
|
|
29463
|
+
this.showErrorMessage(ne.description ?? ne.message), this.stopPolling();
|
|
29466
29464
|
}
|
|
29467
29465
|
}
|
|
29468
29466
|
initializePollingService(te) {
|
|
@@ -29477,9 +29475,14 @@ class CardPaymentMethod extends Component {
|
|
|
29477
29475
|
this.pollingService && (this.pollingService.stopPolling(), this.pollingService = null);
|
|
29478
29476
|
}
|
|
29479
29477
|
handlePollingError(te) {
|
|
29480
|
-
|
|
29481
|
-
|
|
29482
|
-
|
|
29478
|
+
if (typeof te == "object" && te !== null && "text" in te) {
|
|
29479
|
+
const ie = te;
|
|
29480
|
+
this.showErrorMessage(ie.text);
|
|
29481
|
+
} else {
|
|
29482
|
+
const ie = te;
|
|
29483
|
+
this.showErrorMessage(ie.description ?? ie.message);
|
|
29484
|
+
}
|
|
29485
|
+
this.stopPolling(), this.renderRetryButton();
|
|
29483
29486
|
}
|
|
29484
29487
|
showWaitingInfo(te) {
|
|
29485
29488
|
this.element.innerHTML = "";
|
|
@@ -29632,8 +29635,8 @@ class AstroPayCardPayment extends Component {
|
|
|
29632
29635
|
ke(this, "methodCode");
|
|
29633
29636
|
this.componentProps = {
|
|
29634
29637
|
...te,
|
|
29635
|
-
country: te.country.trim(),
|
|
29636
|
-
currency: te.currency.trim()
|
|
29638
|
+
country: te.country.trim().toUpperCase(),
|
|
29639
|
+
currency: te.currency.trim().toUpperCase()
|
|
29637
29640
|
}, this.methodCode = EPaymentCode.DEBIT_CARD, AstroPayCore.registerComponent(this), AmplitudeAnalytics$1.astroPayPaymentImpression("AstroPayCardPayment"), this.loadingWrapper = document.createElement("div"), this.loadingWrapper.classList.add("loading-wrapper");
|
|
29638
29641
|
const ne = new Loading({
|
|
29639
29642
|
size: 100,
|
|
@@ -29655,7 +29658,7 @@ class AstroPayCardPayment extends Component {
|
|
|
29655
29658
|
this.renderAstroPayCardMethod(ce);
|
|
29656
29659
|
} catch (ie) {
|
|
29657
29660
|
const oe = ie;
|
|
29658
|
-
(ne = (te = this.componentProps) == null ? void 0 : te.onError) == null || ne.call(te), this.showErrorMessage(oe.message);
|
|
29661
|
+
(ne = (te = this.componentProps) == null ? void 0 : te.onError) == null || ne.call(te), this.showErrorMessage(oe.description ?? oe.message);
|
|
29659
29662
|
} finally {
|
|
29660
29663
|
this.loadingWrapper.remove();
|
|
29661
29664
|
}
|
|
@@ -31792,7 +31795,7 @@ const getAstroPayPaymentStyles$1 = () => css`
|
|
|
31792
31795
|
gap: 4px;
|
|
31793
31796
|
}
|
|
31794
31797
|
|
|
31795
|
-
.
|
|
31798
|
+
.inline-content {
|
|
31796
31799
|
display: flex;
|
|
31797
31800
|
flex-direction: row;
|
|
31798
31801
|
align-items: center;
|
|
@@ -31801,6 +31804,15 @@ const getAstroPayPaymentStyles$1 = () => css`
|
|
|
31801
31804
|
flex-wrap: wrap;
|
|
31802
31805
|
}
|
|
31803
31806
|
|
|
31807
|
+
.column-content {
|
|
31808
|
+
display: flex;
|
|
31809
|
+
flex-direction: column;
|
|
31810
|
+
align-items: center;
|
|
31811
|
+
justify-content: center;
|
|
31812
|
+
gap: 4px;
|
|
31813
|
+
flex-wrap: wrap;
|
|
31814
|
+
}
|
|
31815
|
+
|
|
31804
31816
|
.loading-pooling {
|
|
31805
31817
|
display: flex;
|
|
31806
31818
|
align-items: center;
|
|
@@ -31872,28 +31884,26 @@ class AstroPayPaymentMethod extends Component {
|
|
|
31872
31884
|
this.renderPhoneInput();
|
|
31873
31885
|
}
|
|
31874
31886
|
async fetchIdentifyUser(te, ne) {
|
|
31875
|
-
var ie
|
|
31887
|
+
var ie;
|
|
31876
31888
|
try {
|
|
31877
|
-
const
|
|
31889
|
+
const oe = {
|
|
31878
31890
|
phoneNumber: formatPhoneNumber(te)
|
|
31879
31891
|
};
|
|
31880
31892
|
if ((await PaymentService.postIdentifyUser(
|
|
31881
31893
|
this.componentProps.paymentExternalId,
|
|
31882
|
-
|
|
31894
|
+
oe
|
|
31883
31895
|
)).user.hasAccount) {
|
|
31884
31896
|
AmplitudeAnalytics$1.astroPayPaymentUserIdentified(this.componentProps.paymentExternalId), (ie = this.formCountryPhone) == null || ie.setDisable(!0), this.handleAccountFlow();
|
|
31885
31897
|
return;
|
|
31886
31898
|
}
|
|
31887
31899
|
ne == null || ne();
|
|
31888
|
-
} catch (
|
|
31889
|
-
const
|
|
31890
|
-
|
|
31891
|
-
const ce = new Typography({
|
|
31892
|
-
text: ue.message,
|
|
31900
|
+
} catch (oe) {
|
|
31901
|
+
const se = oe, ae = new Typography({
|
|
31902
|
+
text: se.description ?? se.message,
|
|
31893
31903
|
size: ThemeManager.getFontScale().xSmall,
|
|
31894
31904
|
color: ThemeManager.getStyles().messages.error.textColor
|
|
31895
31905
|
}).element;
|
|
31896
|
-
this.element.append(
|
|
31906
|
+
this.element.append(ae);
|
|
31897
31907
|
}
|
|
31898
31908
|
}
|
|
31899
31909
|
async handlePhoneNumberSubmit(te) {
|
|
@@ -31931,16 +31941,15 @@ class AstroPayPaymentMethod extends Component {
|
|
|
31931
31941
|
});
|
|
31932
31942
|
}
|
|
31933
31943
|
async checkPaymentStatus(te) {
|
|
31934
|
-
var ne, ie;
|
|
31935
31944
|
try {
|
|
31936
31945
|
this.currentFlow = te, this.stopPolling();
|
|
31937
|
-
const
|
|
31946
|
+
const ne = await PaymentService.getPaymentStatus(
|
|
31938
31947
|
this.componentProps.paymentExternalId
|
|
31939
31948
|
);
|
|
31940
|
-
|
|
31941
|
-
} catch (
|
|
31942
|
-
const
|
|
31943
|
-
this.showErrorMessage(
|
|
31949
|
+
ne.pollingStatus === EPollingStatus.ACCEPTED ? this.initializePollingService(ne) : ne.pollingStatus === EPollingStatus.FINISHED && this.handlePaymentSuccess(ne);
|
|
31950
|
+
} catch (ne) {
|
|
31951
|
+
const ie = ne;
|
|
31952
|
+
this.showErrorMessage(ie.description ?? ie.message);
|
|
31944
31953
|
}
|
|
31945
31954
|
}
|
|
31946
31955
|
initializePollingService(te) {
|
|
@@ -31955,9 +31964,22 @@ class AstroPayPaymentMethod extends Component {
|
|
|
31955
31964
|
this.currentFlow === EFlowType.GUEST && (this.pushFeedbackWrapper && this.pushFeedbackWrapper.remove(), this.pushFeedbackWrapper = document.createElement("div"), this.pushFeedbackWrapper.classList.add("feedback-message-wrapper"), this.element.append(this.pushFeedbackWrapper)), this.showAccountWaitingInfo(te);
|
|
31956
31965
|
}
|
|
31957
31966
|
handlePollingError(te) {
|
|
31958
|
-
|
|
31959
|
-
|
|
31960
|
-
|
|
31967
|
+
if (typeof te == "object" && te !== null && "text" in te) {
|
|
31968
|
+
const ie = te;
|
|
31969
|
+
this.showErrorMessage(
|
|
31970
|
+
ie.text,
|
|
31971
|
+
ie.cta ? {
|
|
31972
|
+
text: ie.cta,
|
|
31973
|
+
onClick: () => {
|
|
31974
|
+
this.checkPaymentStatus(this.currentFlow ?? EFlowType.AUTHENTICATED);
|
|
31975
|
+
}
|
|
31976
|
+
} : void 0
|
|
31977
|
+
);
|
|
31978
|
+
} else {
|
|
31979
|
+
const ie = te;
|
|
31980
|
+
this.showErrorMessage(ie.description ?? ie.message);
|
|
31981
|
+
}
|
|
31982
|
+
this.stopPolling(), this.currentFlow = null;
|
|
31961
31983
|
}
|
|
31962
31984
|
stopPolling() {
|
|
31963
31985
|
this.pollingService && (this.pollingService.stopPolling(), this.pollingService = null), this.element.querySelectorAll(".loading-pooling").forEach((ne) => ne.remove());
|
|
@@ -32035,7 +32057,7 @@ class AstroPayPaymentMethod extends Component {
|
|
|
32035
32057
|
showNoAccountWaitingInfo() {
|
|
32036
32058
|
this.pushFeedbackWrapper && this.pushFeedbackWrapper.remove(), this.pushFeedbackWrapper = document.createElement("div"), this.pushFeedbackWrapper.classList.add("feedback-message-wrapper");
|
|
32037
32059
|
const te = document.createElement("div");
|
|
32038
|
-
te.classList.add("
|
|
32060
|
+
te.classList.add("inline-content");
|
|
32039
32061
|
const ne = new Typography({
|
|
32040
32062
|
text: AstroPayI18n.translate("already_paid"),
|
|
32041
32063
|
size: "xSmall"
|
|
@@ -32044,7 +32066,7 @@ class AstroPayPaymentMethod extends Component {
|
|
|
32044
32066
|
size: "xSmall",
|
|
32045
32067
|
onClick: () => {
|
|
32046
32068
|
var oe;
|
|
32047
|
-
(oe = this.formCountryPhone) == null || oe.setDisable(!0), this.checkPaymentStatus(EFlowType.GUEST);
|
|
32069
|
+
te.remove(), (oe = this.formCountryPhone) == null || oe.setDisable(!0), this.checkPaymentStatus(EFlowType.GUEST);
|
|
32048
32070
|
}
|
|
32049
32071
|
}).element;
|
|
32050
32072
|
te.append(ne, ie), this.pushFeedbackWrapper.append(te), this.element.append(this.pushFeedbackWrapper);
|
|
@@ -32060,15 +32082,27 @@ class AstroPayPaymentMethod extends Component {
|
|
|
32060
32082
|
}).element;
|
|
32061
32083
|
ne.push(ie), this.componentProps.onSuccess ? this.componentProps.onSuccess(ne) : (this.element.innerHTML = "", ne.forEach((ae) => this.element.append(ae)));
|
|
32062
32084
|
}
|
|
32063
|
-
showErrorMessage(te) {
|
|
32085
|
+
showErrorMessage(te, ne) {
|
|
32064
32086
|
if (!this.pushFeedbackWrapper) return;
|
|
32065
|
-
const
|
|
32087
|
+
const ie = document.createElement("div");
|
|
32088
|
+
ie.classList.add("column-content");
|
|
32089
|
+
const oe = new Typography({
|
|
32066
32090
|
text: te,
|
|
32067
32091
|
size: ThemeManager.getFontScale().xSmall,
|
|
32068
32092
|
color: ThemeManager.getStyles().messages.error.textColor,
|
|
32069
32093
|
align: "center"
|
|
32070
32094
|
}).element;
|
|
32071
|
-
|
|
32095
|
+
if (ie.append(oe), ne) {
|
|
32096
|
+
const se = new Link({
|
|
32097
|
+
text: ne.text,
|
|
32098
|
+
size: "xSmall",
|
|
32099
|
+
onClick: () => {
|
|
32100
|
+
ie.remove(), ne.onClick();
|
|
32101
|
+
}
|
|
32102
|
+
}).element;
|
|
32103
|
+
ie.append(se);
|
|
32104
|
+
}
|
|
32105
|
+
this.pushFeedbackWrapper.append(ie);
|
|
32072
32106
|
}
|
|
32073
32107
|
destroy() {
|
|
32074
32108
|
this.stopPolling(), this.element.remove();
|
|
@@ -32226,21 +32260,21 @@ class PaymentMethod extends Component {
|
|
|
32226
32260
|
return te.append(ne, ie, oe), te;
|
|
32227
32261
|
}
|
|
32228
32262
|
async fetchPaymentMethodData() {
|
|
32229
|
-
var te
|
|
32263
|
+
var te;
|
|
32230
32264
|
try {
|
|
32231
32265
|
if ((te = this.componentProps.paymentMethod) != null && te.uri) {
|
|
32232
|
-
const
|
|
32266
|
+
const ne = {
|
|
32233
32267
|
methodCode: this.componentProps.paymentMethod.code
|
|
32234
|
-
},
|
|
32268
|
+
}, ie = await PaymentService.postGenericPayment(
|
|
32235
32269
|
this.componentProps.paymentMethod.uri,
|
|
32236
32270
|
this.componentProps.paymentExternalId,
|
|
32237
|
-
|
|
32271
|
+
ne
|
|
32238
32272
|
);
|
|
32239
|
-
this.renderSections(
|
|
32273
|
+
this.renderSections(ie.sections);
|
|
32240
32274
|
} else throw new Error(AstroPayI18n.translate("generic_error"));
|
|
32241
|
-
} catch (
|
|
32242
|
-
const
|
|
32243
|
-
(ie
|
|
32275
|
+
} catch (ne) {
|
|
32276
|
+
const ie = ne;
|
|
32277
|
+
this.showErrorMessage(ie.description ?? ie.message);
|
|
32244
32278
|
} finally {
|
|
32245
32279
|
this.loadingWrapper.remove();
|
|
32246
32280
|
}
|
|
@@ -32253,7 +32287,7 @@ class PaymentMethod extends Component {
|
|
|
32253
32287
|
te.pollingStatus === EPollingStatus.ACCEPTED ? this.initializePollingService(te) : te.pollingStatus === EPollingStatus.FINISHED && this.handlePaymentSuccess(te);
|
|
32254
32288
|
} catch (te) {
|
|
32255
32289
|
const ne = te;
|
|
32256
|
-
this.showErrorMessage(ne.message), this.stopTimer(), this.stopPolling();
|
|
32290
|
+
this.showErrorMessage(ne.description ?? ne.message), this.stopTimer(), this.stopPolling();
|
|
32257
32291
|
}
|
|
32258
32292
|
}
|
|
32259
32293
|
initializePollingService(te) {
|
|
@@ -32265,9 +32299,14 @@ class PaymentMethod extends Component {
|
|
|
32265
32299
|
), this.pollingService.startPolling();
|
|
32266
32300
|
}
|
|
32267
32301
|
handlePollingError(te) {
|
|
32268
|
-
|
|
32269
|
-
|
|
32270
|
-
|
|
32302
|
+
if (typeof te == "object" && te !== null && "text" in te) {
|
|
32303
|
+
const ie = te;
|
|
32304
|
+
this.showErrorMessage(ie.text);
|
|
32305
|
+
} else {
|
|
32306
|
+
const ie = te;
|
|
32307
|
+
this.showErrorMessage(ie.description ?? ie.message);
|
|
32308
|
+
}
|
|
32309
|
+
this.stopPolling();
|
|
32271
32310
|
}
|
|
32272
32311
|
stopTimer() {
|
|
32273
32312
|
this.timerInstance && (this.timerInstance.stopTimer(), this.timerInstance = null, this.timerElement = null);
|
|
@@ -32536,8 +32575,8 @@ class AstroPayFullCheckout extends Component {
|
|
|
32536
32575
|
...te,
|
|
32537
32576
|
showTitle: te.showTitle ?? !0,
|
|
32538
32577
|
showDescription: te.showDescription ?? !0,
|
|
32539
|
-
country: te.country.trim(),
|
|
32540
|
-
currency: te.currency.trim()
|
|
32578
|
+
country: te.country.trim().toUpperCase(),
|
|
32579
|
+
currency: te.currency.trim().toUpperCase()
|
|
32541
32580
|
}, AstroPayCore.registerComponent(this), AmplitudeAnalytics$1.astroPayPaymentImpression("AstroPayFullCheckout"), this.loadingWrapper = document.createElement("div"), this.loadingWrapper.classList.add("loading-wrapper");
|
|
32542
32581
|
const ne = new Loading({
|
|
32543
32582
|
size: 100,
|
|
@@ -32549,26 +32588,37 @@ class AstroPayFullCheckout extends Component {
|
|
|
32549
32588
|
async createPayment() {
|
|
32550
32589
|
var te, ne;
|
|
32551
32590
|
try {
|
|
32552
|
-
const {
|
|
32553
|
-
|
|
32591
|
+
const {
|
|
32592
|
+
amount: ie,
|
|
32593
|
+
currency: oe,
|
|
32594
|
+
country: se,
|
|
32595
|
+
user: ae,
|
|
32596
|
+
order: ue,
|
|
32597
|
+
paymentExternalId: ce,
|
|
32598
|
+
description: le,
|
|
32599
|
+
paymentLink: de
|
|
32600
|
+
} = this.componentProps;
|
|
32601
|
+
let fe;
|
|
32554
32602
|
if (ce)
|
|
32555
|
-
|
|
32603
|
+
fe = await PaymentService.getPaymentDetails(ce, "full_checkout");
|
|
32556
32604
|
else {
|
|
32557
|
-
const
|
|
32605
|
+
const he = {
|
|
32558
32606
|
country: se,
|
|
32559
32607
|
currency: oe,
|
|
32560
32608
|
amount: ie,
|
|
32561
32609
|
user: ae,
|
|
32562
|
-
order: ue
|
|
32610
|
+
order: ue,
|
|
32611
|
+
description: le,
|
|
32612
|
+
paymentLink: de
|
|
32563
32613
|
};
|
|
32564
|
-
|
|
32614
|
+
fe = await PaymentService.postCreatePayment(he, "full_checkout");
|
|
32565
32615
|
}
|
|
32566
|
-
this.renderPaymentMethods(
|
|
32616
|
+
this.renderPaymentMethods(fe);
|
|
32567
32617
|
} catch (ie) {
|
|
32568
32618
|
const oe = ie;
|
|
32569
32619
|
(ne = (te = this.componentProps) == null ? void 0 : te.onError) == null || ne.call(te);
|
|
32570
32620
|
const se = new Typography({
|
|
32571
|
-
text: oe.message,
|
|
32621
|
+
text: oe.description ?? oe.message,
|
|
32572
32622
|
size: ThemeManager.getFontScale().xSmall,
|
|
32573
32623
|
color: ThemeManager.getStyles().messages.error.textColor
|
|
32574
32624
|
}).element;
|
|
@@ -32713,8 +32763,8 @@ class AstroPayPayment extends Component {
|
|
|
32713
32763
|
ke(this, "methodCode");
|
|
32714
32764
|
this.componentProps = {
|
|
32715
32765
|
...te,
|
|
32716
|
-
country: te.country.trim(),
|
|
32717
|
-
currency: te.currency.trim()
|
|
32766
|
+
country: te.country.trim().toUpperCase(),
|
|
32767
|
+
currency: te.currency.trim().toUpperCase()
|
|
32718
32768
|
}, this.methodCode = "AP", AstroPayCore.registerComponent(this), AmplitudeAnalytics$1.astroPayPaymentImpression("AstroPayPayment"), this.loadingWrapper = document.createElement("div"), this.loadingWrapper.classList.add("loading-wrapper");
|
|
32719
32769
|
const ne = new Loading({
|
|
32720
32770
|
size: 100,
|
|
@@ -32739,7 +32789,7 @@ class AstroPayPayment extends Component {
|
|
|
32739
32789
|
const oe = ie;
|
|
32740
32790
|
(ne = (te = this.componentProps) == null ? void 0 : te.onError) == null || ne.call(te);
|
|
32741
32791
|
const se = new Typography({
|
|
32742
|
-
text: oe.message,
|
|
32792
|
+
text: oe.description ?? oe.message,
|
|
32743
32793
|
size: ThemeManager.getFontScale().xSmall,
|
|
32744
32794
|
color: ThemeManager.getStyles().messages.error.textColor
|
|
32745
32795
|
}).element;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { s as A, C, b as ft, i as Y, g as V, N as h, P as X, S as pt, a as B, c as ht, d as mt, e as St, f as q, r as gt, h as Et, j as yt, k as Tt, l as j, m as J, t as _, n as x, o as M, p as K, q as N, u as Q, v as Z, w as Nt, x as vt, y as b, z as D, A as R, B as wt, D as Mt, E as It, F as Rt, G as Ct, H as bt, I as _t, J as Lt, K as Dt, L as xt, M as Ot, O as At, Q as Vt, R as Pt, T as kt, U as zt } from "./main-
|
|
1
|
+
import { s as A, C, b as ft, i as Y, g as V, N as h, P as X, S as pt, a as B, c as ht, d as mt, e as St, f as q, r as gt, h as Et, j as yt, k as Tt, l as j, m as J, t as _, n as x, o as M, p as K, q as N, u as Q, v as Z, w as Nt, x as vt, y as b, z as D, A as R, B as wt, D as Mt, E as It, F as Rt, G as Ct, H as bt, I as _t, J as Lt, K as Dt, L as xt, M as Ot, O as At, Q as Vt, R as Pt, T as kt, U as zt } from "./main-D0Na6yuS.js";
|
|
2
2
|
const P = /* @__PURE__ */ new WeakMap();
|
|
3
3
|
function T(t) {
|
|
4
4
|
return P.has(t);
|
package/package.json
CHANGED