@getopenpay/openpay-js 0.2.2-alpha.60a8026 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -22,4 +22,4 @@ Error: ${de(e)}`),new Error(t)}},va=r=>(r==null?void 0:r["op-pockyt-3ds-url"])!=
22
22
  Error: ${de(e)}`),new Error(t)}},xa=async(r,e)=>{const t=Ea(e),n=await gn({url:t["op-airwallex-3ds-url"],baseUrl:r}),s=Ca(n.href??""),o=t["op-airwallex-initial-intent-id"];if(o!==s){const c="Unable to process your credit card. Please contact support for assistance.",u=`Intent ID from callback (${s}) does not match the initial intent ID (${o}).`;throw pr(u),new Error(c)}return{existing_cc:{initial_intent_id:s,consent_id:t["op-airwallex-consent-id"]}}},{log__:M,err__:bn}=D("common-cc"),{log__:kn}=D("stripe-cc");i.array(i.object({our_existing_pm_id:i.string()})).length(1);const Pa=Ye(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:s})=>{var l;M("├ Running common CC flow...",{checkoutPaymentMethod:e});const o=r.anyCdeConnection,a=await pe(o);M(`├ Validating non-CDE form fields [Mode: ${a.mode}]`);const c=We(t,n.get.onValidationError),u={session_id:r.elementsSessionId,checkout_payment_method:e,non_cde_form_fields:c,extra_metadata:{}};try{M(`├ Tokenizing card info in CDE [Session: ${r.elementsSessionId}]`);const d=await Ui(s.currentCdeConnections,{session_id:r.elementsSessionId});if(ra(d,n.get.onValidationError),a.mode==="setup"){M(`├ Setting up payment method in CDE [Token: ${a.token}]`);const h=await $i(o,u);return M(`╰ Setup completed successfully [PM ID: ${h.payment_method_id}]`),{mode:"setup",result:h}}else{M(`├ Initial checkout flow. Checking out card info in CDE [Session: ${r.elementsSessionId}]`);const h=await an(o,u);return M("╰ Checkout completed successfully."),{mode:"checkout",result:h}}}catch(d){if(d instanceof on&&d.originalErrorMessage.includes("3DS_REQUIRED")){M("├ Card requires 3DS, starting non-legacy payment flow"),M("Received 3DS error response headers:",d.response.headers);const h=va(d.response.headers);if(h){M("├ Pockyt 3DS case detected. Going through Pockyt 3DS flow.");const C=await wa(r.baseUrl,d.response.headers);u.extra_metadata.pockyt=C}const b=Sa(d.response.headers);if(b){M("├ Airwallex 3DS case detected. Going through Airwallex 3DS flow.");const C=await xa(r.baseUrl,d.response.headers);u.extra_metadata.airwallex=C}const m=await Ni(o,u);M("├ Payment flow result:",m);const v=h||b,E=((l=d.response.headers)==null?void 0:l["op-should-use-new-flow"])!=="true";v?M("├ Pre-start 3DS is successful, other 3DS flows will be skipped."):E?(M("├ Using stripe 3DS flow"),await Ra(m)):(M("├ Using common 3DS flow"),await Ia(m,r.baseUrl));const I=m.cc_pm_id;if(a.mode==="setup"){M(`├ Confirming payment flow [cc_pm_id: ${I}]`);const C=await Ee(o,{secure_token:a.token,existing_cc_pm_id:I});M("├ Confirm payment flow result received Result:",C);const A=Ft(C);return M(`╰ Setup completed successfully [PM ID: ${A.payment_method_id}]`),{mode:"setup",result:A}}else{M(`├ Checking out after 3DS flow [Flow: ${E?"legacy":"new"}]`);const C=await an(o,{...u,existing_cc_pm_id:I,do_not_use_legacy_cc_flow:E});return M("╰ Checkout completed successfully."),{mode:"checkout",result:C}}}throw bn("╰ Error checking out card info in CDE"),bn(d),d}}),Aa=r=>{const e=r.required_user_actions.find(t=>t.type==="stripe_3ds");if(!e)throw new Error("No stripe 3DS action found");return xo.parse(e)},Ta=r=>{const e=r.required_user_actions.find(t=>t.type==="airwallex_payment_consent");if(!e)throw new Error("No common 3DS action found");return ko.parse(e)},Ia=async(r,e)=>{const t=Ta(r);M(`├ Using common 3DS flow [URL: ${t.redirect_url}]`);const{status:n}=await Zt({url:t.redirect_url,baseUrl:e});if(M(`╰ 3DS verification completed [Status: ${n}]`),n===Q.CANCELLED)throw new Error("3DS verification cancelled");if(n===Q.FAILURE)throw new Error("3DS verification failed")},Ra=async r=>{const e=Aa(r);kn(`├ Using stripe 3DS flow [Client Secret: ${e.client_secret.substring(0,8)}...]`),await Mo(e),kn("╰ Stripe 3DS flow completed successfully")},{log__:z,err__:Oa}=D("stripe-pr"),Na=i.object({provider:i.union([i.literal("apple_pay"),i.literal("google_pay")]),processor_name:i.literal("stripe"),metadata:i.object({stripe_pk:i.string()})}),Ma=$t(async({context:r})=>{z("Checking if there are any CPMs for Stripe PR...");const e=Ge(r.checkoutPaymentMethods,Na);z("Initializing Stripe PR flow...");const t=r.anyCdeConnection,n=await pe(t),s=n.mode==="setup";z("Getting initial preview amount");const o=await jt(t,n.token,s,void 0),a=await Io(e.metadata.stripe_pk,o.amountAtom,o.currency,s);z("Checking if can make payment");const c=await a.canMakePayment();return c===null?(Oa("canMakePayment returned null"),{isAvailable:!1,reason:"canMakePayment returned null"}):(z("Stripe PR flow initialized successfully. Can make payment",c),{isAvailable:!0,pr:a,availableProviders:{applePay:c.applePay,googlePay:c.googlePay}})}),ja=Ye(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n,customParams:s,initResult:o})=>{if(z("Running Stripe PR flow..."),s.provider!==e.provider)throw new Error(`Provider mismatch. Expected ${s.provider}, got ${e.provider}`);const a=r.anyCdeConnection,c=o.pr;if(s!=null&&s.overridePaymentRequest){const v=s.overridePaymentRequest;z("Overriding PR amount with",v),La(c,v.amount,v.pending,v.stripeApplePay)}z("Showing PR dialog..."),c.show();const u=await Oo(c);z("Stripe PM added event:",u),z("Merging PM fields with form fields...");const l=Da(t,u),d=We(l,n.get.onValidationError);z("PR dialog finished. Starting payment flow...",d);const h=await Mi(a,{fields:d,checkoutPaymentMethod:e}),b=Ua(h);z("Confirming PR with Stripe..."),await No(b,u);const m=await pe(a);if(m.mode==="setup"){z("Confirming payment flow for setup...");const v=await Ee(a,{secure_token:m.token});return{mode:"setup",result:Ft(v)}}else{z("Performing checkout...");const v={secure_token:m.token,payment_input:{provider_type:e.provider},customer_first_name:d[f.FIRST_NAME],customer_last_name:d[f.LAST_NAME],customer_email:d[f.EMAIL],customer_zip_code:d[f.ZIP_CODE],customer_country:d[f.COUNTRY],promotion_code:d[f.PROMOTION_CODE],line_items:m.line_items,total_amount_atom:m.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e};return{mode:"checkout",result:await _t(a,v)}}}),Da=(r,e)=>{var u,l,d,h;const t={...r},[n,...s]=((l=(u=e.payerName)==null?void 0:u.trim())==null?void 0:l.split(/\s+/))??[],o=s.join(" ")||void 0,a=(h=(d=e.paymentMethod)==null?void 0:d.billing_details)==null?void 0:h.address,c=e.shippingAddress;return t[f.FIRST_NAME]=t[f.FIRST_NAME]||n||"_OP_UNKNOWN",t[f.LAST_NAME]=t[f.LAST_NAME]||o||"_OP_UNKNOWN",t[f.EMAIL]=t[f.EMAIL]||e.payerEmail||"op_unfilled@getopenpay.com",t[f.ZIP_CODE]=t[f.ZIP_CODE]||(a==null?void 0:a.postal_code)||(c==null?void 0:c.postalCode)||"00000",t[f.COUNTRY]=t[f.COUNTRY]||(a==null?void 0:a.country)||(c==null?void 0:c.country)||"US",z("Final form inputs:",t),t},La=(r,e,t,n)=>{r.update({total:{amount:e.amountAtom,label:"Total",pending:t},currency:e.currency,applePay:n})},Ua=r=>{if(r.required_user_actions.length!==1)throw new Error(`Error occurred.
23
23
  Details: got ${r.required_user_actions.length} required user actions`);return Po.parse(r.required_user_actions[0])},{log__:fe}=D("pockyt-paypal"),$a=i.object({processor_name:i.literal("pockyt"),provider:i.literal("paypal")}),Fa=i.array(i.object({paypal_iframe_url:i.string(),verify_token:i.string()})).length(1),Za=Ye(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n})=>{fe("Running Pockyt Paypal flow...");const s=r.anyCdeConnection,o=await pe(s);fe("Verifying CPM...");const a=$a.parse(e);fe("├ Validating non-CDE form fields");const c=We(t,n.get.onValidationError),u=Qi(c);fe("Starting payment flow...");const l=await Mt(s,{payment_provider:a.provider,checkout_payment_method:a,...u});fe("Start payment flow response",l);const d=Fa.parse(l.required_user_actions)[0];fe("Opening paypal iframe...");const h=await ma("PayPal",s,d.verify_token,d.paypal_iframe_url);fe("Paypal flow result",h);const b=wn(h.href);fe(`Confirming payment flow using vault ID ${b}`);const m=await Ee(s,{secure_token:o.token,their_pm_id:b});return fe("Confirm payment flow result",m),await ea("pockyt-paypal",s,a,c,m)}),fr=({gateway:r,gatewayMerchantId:e,merchantName:t,merchantId:n,initialPreview:s})=>{var c;const o={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:[{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"],billingAddressRequired:!0,billingAddressParameters:{format:"FULL"},allowCreditCards:!0,allowPrepaidCards:!0},tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:r,gatewayMerchantId:e}}}],emailRequired:!0,merchantInfo:{merchantId:n,merchantName:t}};if(!s)return o;const a=Math.max(s.amountAtom/100,0);return{...o,transactionInfo:{countryCode:"US",currencyCode:((c=s.currency)==null?void 0:c.toUpperCase())??"USD",totalPriceStatus:"FINAL",totalPrice:a.toFixed(2)}}},Va=()=>new Promise((r,e)=>{const t=document.createElement("script");t.src="https://pay.google.com/gp/p/js/pay.js",t.async=!0,t.onload=()=>r(),t.onerror=()=>e(new Error("Failed to load Google Pay SDK")),document.body.appendChild(t)}),za=r=>{const e=r.required_user_actions.find(t=>t.type==="airwallex_payment_consent");return e?Zr.parse(e):null},Ba=(r,e)=>{var s,o,a,c;const t={...r},n=(o=(s=e.paymentMethodData)==null?void 0:s.info)==null?void 0:o.billingAddress;if(n){const[u,...l]=((c=(a=n.name)==null?void 0:a.trim())==null?void 0:c.split(/\s+/))??[],d=l.join(" ")||void 0;t[f.EMAIL]=t[f.EMAIL]||e.email||"op_unfilled@getopenpay.com",t[f.COUNTRY]=t[f.COUNTRY]||n.countryCode||"US",t[f.ADDRESS]=t[f.ADDRESS]||n.address1||"",t[f.CITY]=t[f.CITY]||n.locality||"",t[f.ZIP_CODE]=t[f.ZIP_CODE]||n.postalCode||"00000",t[f.STATE]=t[f.STATE]||n.administrativeArea||"",t[f.FIRST_NAME]=t[f.FIRST_NAME]||u||"_OP_UNKNOWN",t[f.LAST_NAME]=t[f.LAST_NAME]||d||"_OP_UNKNOWN"}return t},{log__:W,err__:wt}=D("gpay");let hr=null;const En=r=>{const e=r===je?"PRODUCTION":"TEST";return hr===null&&(hr=new window.google.payments.api.PaymentsClient({environment:e,merchantInfo:fr({gateway:"airwallex",gatewayMerchantId:"",merchantName:""}).merchantInfo})),hr},Sn=i.object({provider:i.literal("google_pay"),processor_name:i.literal("airwallex"),metadata:i.object({processor_account_id:i.string(),processor_account_name:i.string()})}),qa=$t(async({context:r,formCallbacks:e})=>{var o,a;const t=Ge(r.checkoutPaymentMethods,Sn);if(!t)return{isAvailable:!1};W("Google Pay CPM",t);const n=t.metadata;if(!n.processor_account_id)return wt("No gateway merchant ID found in processor account"),{isAvailable:!1};if(W("Loading Google Pay SDK..."),await Va(),!((a=(o=window.google)==null?void 0:o.payments)!=null&&a.api))return wt("Google Pay SDK not loaded properly"),{isAvailable:!1};W("Google Pay SDK loaded",window.google.payments);try{const{result:c}=await En(r.baseUrl).isReadyToPay(fr({gateway:"airwallex",gatewayMerchantId:n.processor_account_id,merchantName:n.processor_account_name,merchantId:"",initialPreview:void 0}));if(!c)return W("Google Pay is not available for this user"),{isAvailable:!1}}catch(c){return wt("Error checking Google Pay availability",c),{isAvailable:!1}}return{isAvailable:!0,startFlow:async()=>{try{ee.airwallexGooglePay.run({context:r,checkoutPaymentMethod:t,nonCdeFormInputs:ze(r.formDiv),formCallbacks:e,customParams:void 0,initResult:void 0})}catch(c){wt("Google Pay payment error",c),e.get.onCheckoutError((c==null?void 0:c.message)??"Unknown error")}}}}),Ya=Ye(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,formCallbacks:n})=>{var d,h,b,m,v,E,I;W("Starting Google Pay flow...");const s=Ge(r.checkoutPaymentMethods,Sn),o=En(r.baseUrl),a=r.anyCdeConnection,c=await pe(a),u=s.metadata;if(!u.processor_account_id)throw new Error("No gateway merchant ID found in processor account");const l=fr({gateway:"airwallex",gatewayMerchantId:u.processor_account_id,merchantName:u.processor_account_name,merchantId:"",initialPreview:await jt(a,c.token,c.mode==="setup",void 0)});try{const C=await o.loadPaymentData(l);W("Google Pay Payment data",C);const A=Ba(t,C),T=We(A,n.get.onValidationError),ye=(h=(d=C.paymentMethodData)==null?void 0:d.tokenizationData)==null?void 0:h.token;if(!ye)throw new Error("No payment token received from Google Pay");const xe=await Mt(a,{payment_provider:e.provider,checkout_payment_method:e,new_customer_email:T[f.EMAIL],new_customer_first_name:T[f.FIRST_NAME],new_customer_last_name:T[f.LAST_NAME],new_customer_address:{postal_code:T[f.ZIP_CODE],country_code:T[f.COUNTRY]}}),Pe=za(xe);W("Start flow next actions",Pe);const Ne=await Ee(a,{secure_token:c.token,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:Pe==null?void 0:Pe.consent_id,airwallex_payment_method_data:{type:"googlepay",googlepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:ye}}}});W("[1st] Confirm payment flow response",Ne);let kt=(m=(b=Ne.payment_methods)==null?void 0:b[0])==null?void 0:m.id;const Me=(v=Ne.required_user_actions)==null?void 0:v.find(ce=>ce.type==="airwallex_payment_consent");if(Me&&Me.redirect_url){W("3DS Required, starting verification...",Me);const{status:ce}=await Zt({url:Me.redirect_url,baseUrl:r.baseUrl});if(W(`╰ 3DS verification completed [Status: ${ce}]`),ce===Q.CANCELLED)throw new Error("3DS verification cancelled");if(ce===Q.FAILURE)throw new Error("3DS verification failed")}if(Me&&!kt){const ce=await Ee(a,{secure_token:c.token,their_pm_id:Me.their_pm_id,processor_specific_metadata:{payment_provider:e.provider,airwallex_consent_id:Me.consent_id}});W("[2nd] Confirm payment flow response",ce),kt=(I=(E=ce.payment_methods)==null?void 0:E[0])==null?void 0:I.id}if(!kt)throw new Error("No PM ID found");if(c.mode==="setup")return{mode:"setup",result:{payment_method_id:kt}};{W("Starting one-time payment flow...");const ce={secure_token:c.token,payment_input:{provider_type:e.provider},do_not_use_legacy_cc_flow:!0,use_confirmed_pm_id:kt,line_items:c.line_items,total_amount_atom:c.amount_total_atom,cancel_at_end:!1,checkout_payment_method:e,customer_email:T[f.EMAIL],customer_zip_code:T[f.ZIP_CODE],customer_country:T[f.COUNTRY],promotion_code:T[f.PROMOTION_CODE],customer_first_name:T[f.FIRST_NAME],customer_last_name:T[f.LAST_NAME]};return{mode:"checkout",result:await _t(a,ce)}}}catch(C){throw wt("Google Pay payment error",C),new Error((C==null?void 0:C.message)??"Unknown error")}}),Ga=()=>new Promise((r,e)=>{const t=document.createElement("script");t.src="https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",t.crossOrigin="anonymous",t.async=!0,t.onload=()=>r(),t.onerror=()=>e(new Error("Failed to load Apple Pay SDK")),document.body.appendChild(t)}),Wa=(r,e)=>{var n;const t={...r};return e&&(t[f.EMAIL]=t[f.EMAIL]||e.emailAddress||"op_unfilled@getopenpay.com",t[f.COUNTRY]=t[f.COUNTRY]||e.countryCode||"US",t[f.ADDRESS]=t[f.ADDRESS]||((n=e.addressLines)==null?void 0:n[0])||"",t[f.CITY]=t[f.CITY]||e.locality||"",t[f.ZIP_CODE]=t[f.ZIP_CODE]||e.postalCode||"00000",t[f.STATE]=t[f.STATE]||e.administrativeArea||"",t[f.FIRST_NAME]=t[f.FIRST_NAME]||e.givenName||"_OP_UNKNOWN",t[f.LAST_NAME]=t[f.LAST_NAME]||e.familyName||"_OP_UNKNOWN"),t},{log__:Vt}=D("applepay-session");async function Ha(r,e){try{const n=(await Mt(e.connection,{payment_provider:e.checkoutPaymentMethod.provider,checkout_payment_method:e.checkoutPaymentMethod,new_customer_email:e.nonCdeFormInputs[f.EMAIL],new_customer_first_name:e.nonCdeFormInputs[f.FIRST_NAME],new_customer_last_name:e.nonCdeFormInputs[f.LAST_NAME],processor_specific_metadata:{airwallex_payment_session:{validation_url:r.validationURL,initiative_context:window.location.hostname,their_account_id:e.processorAccount.processor_account_id}}})).required_user_actions[0],s=n.payment_session,o=n.consent_id;if(!s)throw new Error("No session data received from payment flow");if(!o)throw new Error("No consent ID received from payment flow");return e.session.completeMerchantValidation(s),o}catch(t){throw e.session.abort(),t}}async function Ka(r,e){var s,o;if(!r.redirect_url)throw new Error("No redirect URL found");Vt("3DS Required, starting verification...",r);const{status:t}=await Zt({url:r.redirect_url,baseUrl:e.baseUrl});if(Vt(`╰ 3DS verification completed [Status: ${t}]`),t===Q.CANCELLED)throw new Error("3DS verification cancelled");if(t===Q.FAILURE)throw new Error("3DS verification failed");const n=await Ee(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{their_pm_id:r.their_pm_id,airwallex_consent_id:r.consent_id,payment_provider:e.checkoutPaymentMethod.provider}});return Vt("[2nd] Confirm payment flow response",n),(o=(s=n.payment_methods)==null?void 0:s[0])==null?void 0:o.id}async function Ja(r,e,t){return{mode:"checkout",result:await _t(t.connection,{secure_token:t.prefill.token,payment_input:{provider_type:t.checkoutPaymentMethod.provider},do_not_use_legacy_cc_flow:!0,use_confirmed_pm_id:r,line_items:t.prefill.line_items,total_amount_atom:t.prefill.amount_total_atom,cancel_at_end:!1,checkout_payment_method:t.checkoutPaymentMethod,customer_email:e[f.EMAIL],customer_zip_code:e[f.ZIP_CODE],customer_country:e[f.COUNTRY],promotion_code:e[f.PROMOTION_CODE]})}}async function Xa(r,e,t){var n,s,o;try{const a=r.payment,c=Wa(e.nonCdeFormInputs,a.billingContact),u=We(c,e.formCallbacks.get.onValidationError),l=await Ee(e.connection,{secure_token:e.prefill.token,processor_specific_metadata:{payment_provider:e.checkoutPaymentMethod.provider,airwallex_consent_id:t,airwallex_payment_method_data:{type:"applepay",applepay:{payment_data_type:"encrypted_payment_token",encrypted_payment_token:JSON.stringify(a.token)}}}});Vt("[1st] Confirm payment flow response",l);let d=(s=(n=l.payment_methods)==null?void 0:n[0])==null?void 0:s.id;const h=(o=l.required_user_actions)==null?void 0:o.find(m=>m.type==="airwallex_payment_consent");if(h!=null&&h.redirect_url&&h.consent_id&&h.their_pm_id&&(d=await Ka(h,e)),!d)throw new Error("No PM ID found");const b={status:ApplePaySession.STATUS_SUCCESS};return e.session.completePayment(b),e.isSetupMode?{mode:"setup",result:{payment_method_id:d}}:await Ja(d,u,e)}catch(a){const c={status:ApplePaySession.STATUS_FAILURE};throw e.session.completePayment(c),a}}const{log__:Y,err__:mr}=D("applepay"),Cn=i.object({provider:i.literal("apple_pay"),processor_name:i.literal("airwallex"),metadata:i.object({processor_account_id:i.string(),processor_account_name:i.string()})}),Qa=$t(async({context:r,formCallbacks:e})=>{const t=Ge(r.checkoutPaymentMethods,Cn);if(!t)return{isAvailable:!1};Y("Loading Apple Pay SDK...");try{await Ga(),Y("Apple Pay SDK loaded successfully")}catch(d){return mr("Failed to load Apple Pay SDK",d),{isAvailable:!1}}if(!window.ApplePaySession||!ApplePaySession.canMakePayments())return Y("Apple Pay is not available on this device/browser"),{isAvailable:!1};if(Y("Apple Pay Loaded"),!await ApplePaySession.canMakePayments())return Y("No active cards available for Apple Pay"),{isAvailable:!1};const s=r.anyCdeConnection,o=await pe(s),a=o.mode==="setup",c=await jt(s,o.token,a,void 0),u=t.metadata;if(Y("processorAccount",u),!u.processor_account_id)throw new Error("No gateway merchant ID found in processor account");return{isAvailable:!0,startFlow:async()=>{try{await ee.airwallexApplePay.run({context:r,checkoutPaymentMethod:t,nonCdeFormInputs:ze(r.formDiv),formCallbacks:e,customParams:{initialPreview:c,isSetupMode:a,prefill:o},initResult:void 0})}catch(d){mr("Apple Pay payment error",d),e.get.onCheckoutError((d==null?void 0:d.message)??"Unknown error")}}}}),ec=Ye(async({context:r,checkoutPaymentMethod:e,nonCdeFormInputs:t,customParams:n,formCallbacks:s})=>{var v;const o=Ge(r.checkoutPaymentMethods,Cn),{initialPreview:a,isSetupMode:c,prefill:u}=n,l={label:c?"Setup Payment":"Payment Total",amount:c?"0.00":(a.amountAtom/100).toFixed(2),type:"final"},d={countryCode:"US",currencyCode:((v=a.currency)==null?void 0:v.toUpperCase())??"USD",supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS","supportsCredit","supportsDebit","supportsEMV"],total:l};Y("Payment Request",d);const h=new ApplePaySession(3,d);Y("ApplePaySession",h);const b={session:h,connection:r.anyCdeConnection,checkoutPaymentMethod:e,nonCdeFormInputs:t,processorAccount:o.metadata,prefill:u,isSetupMode:c,baseUrl:r.baseUrl,formCallbacks:s};let m;return new Promise((E,I)=>{h.oncancel=()=>{Y("Payment cancelled by user"),I(new Error("Payment cancelled by user"))},h.onvalidatemerchant=async C=>{try{m=await Ha(C,b)}catch(A){I(A)}},h.onshippingmethodselected=C=>{Y("Shipping method selected",C.shippingMethod)},h.onshippingmethodselected=C=>{Y("Shipping method selected",C.shippingMethod);const A={};h.completeShippingMethodSelection(A)},h.onshippingcontactselected=C=>{Y("Shipping contact selected",C.shippingContact);const A={};h.completeShippingContactSelection(A)},h.onpaymentmethodselected=C=>{Y("Payment method selected",C.paymentMethod);const A={newTotal:{...l}};h.completePaymentMethodSelection(A)},h.onpaymentauthorized=async C=>{try{const A=await Xa(C,b,m);E(A)}catch(A){I(A)}},h.begin()}).catch(E=>{throw mr("Apple Pay payment error",E),E})}),yr=(r,e,t)=>{const n=r.filter(s=>{const o=t===void 0?!0:s.processor_name===t,a=s.provider===e;return o&&a});if(n.length===0)throw console.error("CPMs list",r),new Error(`No CPMs found with provider '${e}' and processor '${t}'`);if(n.length!==1)throw console.error("CPMs list",r),new Error(`More than one CPM found with provider '${e}' and processor '${t}'`);return n[0]},ee={commonCC:{init:async()=>{},run:Pa},stripePR:{init:Ma,run:ja},stripeLink:{init:ia,run:aa},pockytPaypal:{run:Za},airwallexGooglePay:{init:qa,run:Ya},airwallexApplePay:{init:Qa,run:ec}};var _r=function(r,e){return _r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])},_r(r,e)};function Se(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");_r(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function tc(r,e,t,n){function s(o){return o instanceof t?o:new t(function(a){a(o)})}return new(t||(t=Promise))(function(o,a){function c(d){try{l(n.next(d))}catch(h){a(h)}}function u(d){try{l(n.throw(d))}catch(h){a(h)}}function l(d){d.done?o(d.value):s(d.value).then(c,u)}l((n=n.apply(r,e||[])).next())})}function xn(r,e){var t={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,s,o,a=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return a.next=c(0),a.throw=c(1),a.return=c(2),typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function c(l){return function(d){return u([l,d])}}function u(l){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,l[0]&&(t=0)),t;)try{if(n=1,s&&(o=l[0]&2?s.return:l[0]?s.throw||((o=s.return)&&o.call(s),0):s.next)&&!(o=o.call(s,l[1])).done)return o;switch(s=0,o&&(l=[l[0]&2,o.value]),l[0]){case 0:case 1:o=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,s=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!o||l[1]>o[0]&&l[1]<o[3])){t.label=l[1];break}if(l[0]===6&&t.label<o[1]){t.label=o[1],o=l;break}if(o&&t.label<o[2]){t.label=o[2],t.ops.push(l);break}o[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(d){l=[6,d],s=0}finally{n=o=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function He(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function zt(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(c){a={error:c}}finally{try{s&&!s.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o}function Bt(r,e,t){if(t||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return r.concat(o||Array.prototype.slice.call(e))}function Ke(r){return this instanceof Ke?(this.v=r,this):new Ke(r)}function rc(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(r,e||[]),s,o=[];return s=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),c("next"),c("throw"),c("return",a),s[Symbol.asyncIterator]=function(){return this},s;function a(m){return function(v){return Promise.resolve(v).then(m,h)}}function c(m,v){n[m]&&(s[m]=function(E){return new Promise(function(I,C){o.push([m,E,I,C])>1||u(m,E)})},v&&(s[m]=v(s[m])))}function u(m,v){try{l(n[m](v))}catch(E){b(o[0][3],E)}}function l(m){m.value instanceof Ke?Promise.resolve(m.value.v).then(d,h):b(o[0][2],m)}function d(m){u("next",m)}function h(m){u("throw",m)}function b(m,v){m(v),o.shift(),o.length&&u(o[0][0],o[0][1])}}function nc(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof He=="function"?He(r):r[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(o){t[o]=r[o]&&function(a){return new Promise(function(c,u){a=r[o](a),s(c,u,a.done,a.value)})}}function s(o,a,c,u){Promise.resolve(u).then(function(l){o({value:l,done:c})},a)}}typeof SuppressedError=="function"&&SuppressedError;function $(r){return typeof r=="function"}function qt(r){var e=function(n){Error.call(n),n.stack=new Error().stack},t=r(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var gr=qt(function(r){return function(t){r(this),this.message=t?t.length+` errors occurred during unsubscription:
24
24
  `+t.map(function(n,s){return s+1+") "+n.toString()}).join(`
25
- `):"",this.name="UnsubscriptionError",this.errors=t}});function Yt(r,e){if(r){var t=r.indexOf(e);0<=t&&r.splice(t,1)}}var bt=function(){function r(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return r.prototype.unsubscribe=function(){var e,t,n,s,o;if(!this.closed){this.closed=!0;var a=this._parentage;if(a)if(this._parentage=null,Array.isArray(a))try{for(var c=He(a),u=c.next();!u.done;u=c.next()){var l=u.value;l.remove(this)}}catch(E){e={error:E}}finally{try{u&&!u.done&&(t=c.return)&&t.call(c)}finally{if(e)throw e.error}}else a.remove(this);var d=this.initialTeardown;if($(d))try{d()}catch(E){o=E instanceof gr?E.errors:[E]}var h=this._finalizers;if(h){this._finalizers=null;try{for(var b=He(h),m=b.next();!m.done;m=b.next()){var v=m.value;try{Tn(v)}catch(E){o=o??[],E instanceof gr?o=Bt(Bt([],zt(o)),zt(E.errors)):o.push(E)}}}catch(E){n={error:E}}finally{try{m&&!m.done&&(s=b.return)&&s.call(b)}finally{if(n)throw n.error}}}if(o)throw new gr(o)}},r.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)Tn(e);else{if(e instanceof r){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},r.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},r.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},r.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&Yt(t,e)},r.prototype.remove=function(e){var t=this._finalizers;t&&Yt(t,e),e instanceof r&&e._removeParent(this)},r.EMPTY=function(){var e=new r;return e.closed=!0,e}(),r}(),Pn=bt.EMPTY;function An(r){return r instanceof bt||r&&"closed"in r&&$(r.remove)&&$(r.add)&&$(r.unsubscribe)}function Tn(r){$(r)?r():r.unsubscribe()}var In={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},Rn={setTimeout:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setTimeout.apply(void 0,Bt([r,e],zt(t)))},clearTimeout:function(r){var e=Rn.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(r)},delegate:void 0};function On(r){Rn.setTimeout(function(){throw r})}function Nn(){}function Gt(r){r()}var vr=function(r){Se(e,r);function e(t){var n=r.call(this)||this;return n.isStopped=!1,t?(n.destination=t,An(t)&&t.add(n)):n.destination=ac,n}return e.create=function(t,n,s){return new br(t,n,s)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,r.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(bt),sc=Function.prototype.bind;function wr(r,e){return sc.call(r,e)}var oc=function(){function r(e){this.partialObserver=e}return r.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(n){Wt(n)}},r.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(n){Wt(n)}else Wt(e)},r.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){Wt(t)}},r}(),br=function(r){Se(e,r);function e(t,n,s){var o=r.call(this)||this,a;if($(t)||!t)a={next:t??void 0,error:n??void 0,complete:s??void 0};else{var c;o&&In.useDeprecatedNextContext?(c=Object.create(t),c.unsubscribe=function(){return o.unsubscribe()},a={next:t.next&&wr(t.next,c),error:t.error&&wr(t.error,c),complete:t.complete&&wr(t.complete,c)}):a=t}return o.destination=new oc(a),o}return e}(vr);function Wt(r){On(r)}function ic(r){throw r}var ac={closed:!0,next:Nn,error:ic,complete:Nn},kr=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function cc(r){return r}function lc(r){return r.length===0?cc:r.length===1?r[0]:function(t){return r.reduce(function(n,s){return s(n)},t)}}var he=function(){function r(e){e&&(this._subscribe=e)}return r.prototype.lift=function(e){var t=new r;return t.source=this,t.operator=e,t},r.prototype.subscribe=function(e,t,n){var s=this,o=dc(e)?e:new br(e,t,n);return Gt(function(){var a=s,c=a.operator,u=a.source;o.add(c?c.call(o,u):u?s._subscribe(o):s._trySubscribe(o))}),o},r.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},r.prototype.forEach=function(e,t){var n=this;return t=Mn(t),new t(function(s,o){var a=new br({next:function(c){try{e(c)}catch(u){o(u),a.unsubscribe()}},error:o,complete:s});n.subscribe(a)})},r.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},r.prototype[kr]=function(){return this},r.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return lc(e)(this)},r.prototype.toPromise=function(e){var t=this;return e=Mn(e),new e(function(n,s){var o;t.subscribe(function(a){return o=a},function(a){return s(a)},function(){return n(o)})})},r.create=function(e){return new r(e)},r}();function Mn(r){var e;return(e=r??In.Promise)!==null&&e!==void 0?e:Promise}function uc(r){return r&&$(r.next)&&$(r.error)&&$(r.complete)}function dc(r){return r&&r instanceof vr||uc(r)&&An(r)}function pc(r){return $(r==null?void 0:r.lift)}function fc(r){return function(e){if(pc(e))return e.lift(function(t){try{return r(t,this)}catch(n){this.error(n)}});throw new TypeError("Unable to lift unknown Observable type")}}function hc(r,e,t,n,s){return new mc(r,e,t,n,s)}var mc=function(r){Se(e,r);function e(t,n,s,o,a,c){var u=r.call(this,t)||this;return u.onFinalize=a,u.shouldUnsubscribe=c,u._next=n?function(l){try{n(l)}catch(d){t.error(d)}}:r.prototype._next,u._error=o?function(l){try{o(l)}catch(d){t.error(d)}finally{this.unsubscribe()}}:r.prototype._error,u._complete=s?function(){try{s()}catch(l){t.error(l)}finally{this.unsubscribe()}}:r.prototype._complete,u}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;r.prototype.unsubscribe.call(this),!n&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e}(vr),yc=qt(function(r){return function(){r(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),jn=function(r){Se(e,r);function e(){var t=r.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return e.prototype.lift=function(t){var n=new Dn(this,this);return n.operator=t,n},e.prototype._throwIfClosed=function(){if(this.closed)throw new yc},e.prototype.next=function(t){var n=this;Gt(function(){var s,o;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var a=He(n.currentObservers),c=a.next();!c.done;c=a.next()){var u=c.value;u.next(t)}}catch(l){s={error:l}}finally{try{c&&!c.done&&(o=a.return)&&o.call(a)}finally{if(s)throw s.error}}}})},e.prototype.error=function(t){var n=this;Gt(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=t;for(var s=n.observers;s.length;)s.shift().error(t)}})},e.prototype.complete=function(){var t=this;Gt(function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var n=t.observers;n.length;)n.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var t;return((t=this.observers)===null||t===void 0?void 0:t.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),r.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var n=this,s=this,o=s.hasError,a=s.isStopped,c=s.observers;return o||a?Pn:(this.currentObservers=null,c.push(t),new bt(function(){n.currentObservers=null,Yt(c,t)}))},e.prototype._checkFinalizedStatuses=function(t){var n=this,s=n.hasError,o=n.thrownError,a=n.isStopped;s?t.error(o):a&&t.complete()},e.prototype.asObservable=function(){var t=new he;return t.source=this,t},e.create=function(t,n){return new Dn(t,n)},e}(he),Dn=function(r){Se(e,r);function e(t,n){var s=r.call(this)||this;return s.destination=t,s.source=n,s}return e.prototype.next=function(t){var n,s;(s=(n=this.destination)===null||n===void 0?void 0:n.next)===null||s===void 0||s.call(n,t)},e.prototype.error=function(t){var n,s;(s=(n=this.destination)===null||n===void 0?void 0:n.error)===null||s===void 0||s.call(n,t)},e.prototype.complete=function(){var t,n;(n=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||n===void 0||n.call(t)},e.prototype._subscribe=function(t){var n,s;return(s=(n=this.source)===null||n===void 0?void 0:n.subscribe(t))!==null&&s!==void 0?s:Pn},e}(jn),_c={now:function(){return Date.now()},delegate:void 0},gc=function(r){Se(e,r);function e(t,n){return r.call(this)||this}return e.prototype.schedule=function(t,n){return this},e}(bt),Ln={setInterval:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setInterval.apply(void 0,Bt([r,e],zt(t)))},clearInterval:function(r){return clearInterval(r)},delegate:void 0},vc=function(r){Se(e,r);function e(t,n){var s=r.call(this,t,n)||this;return s.scheduler=t,s.work=n,s.pending=!1,s}return e.prototype.schedule=function(t,n){var s;if(n===void 0&&(n=0),this.closed)return this;this.state=t;var o=this.id,a=this.scheduler;return o!=null&&(this.id=this.recycleAsyncId(a,o,n)),this.pending=!0,this.delay=n,this.id=(s=this.id)!==null&&s!==void 0?s:this.requestAsyncId(a,this.id,n),this},e.prototype.requestAsyncId=function(t,n,s){return s===void 0&&(s=0),Ln.setInterval(t.flush.bind(t,this),s)},e.prototype.recycleAsyncId=function(t,n,s){if(s===void 0&&(s=0),s!=null&&this.delay===s&&this.pending===!1)return n;n!=null&&Ln.clearInterval(n)},e.prototype.execute=function(t,n){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var s=this._execute(t,n);if(s)return s;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(t,n){var s=!1,o;try{this.work(t)}catch(a){s=!0,o=a||new Error("Scheduled action threw falsy error")}if(s)return this.unsubscribe(),o},e.prototype.unsubscribe=function(){if(!this.closed){var t=this,n=t.id,s=t.scheduler,o=s.actions;this.work=this.state=this.scheduler=null,this.pending=!1,Yt(o,this),n!=null&&(this.id=this.recycleAsyncId(s,n,null)),this.delay=null,r.prototype.unsubscribe.call(this)}},e}(gc),Un=function(){function r(e,t){t===void 0&&(t=r.now),this.schedulerActionCtor=e,this.now=t}return r.prototype.schedule=function(e,t,n){return t===void 0&&(t=0),new this.schedulerActionCtor(this,e).schedule(n,t)},r.now=_c.now,r}(),wc=function(r){Se(e,r);function e(t,n){n===void 0&&(n=Un.now);var s=r.call(this,t,n)||this;return s.actions=[],s._active=!1,s}return e.prototype.flush=function(t){var n=this.actions;if(this._active){n.push(t);return}var s;this._active=!0;do if(s=t.execute(t.state,t.delay))break;while(t=n.shift());if(this._active=!1,s){for(;t=n.shift();)t.unsubscribe();throw s}},e}(Un),bc=new wc(vc),kc=function(r){return r&&typeof r.length=="number"&&typeof r!="function"};function Ec(r){return $(r==null?void 0:r.then)}function Sc(r){return $(r[kr])}function Cc(r){return Symbol.asyncIterator&&$(r==null?void 0:r[Symbol.asyncIterator])}function xc(r){return new TypeError("You provided "+(r!==null&&typeof r=="object"?"an invalid object":"'"+r+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Pc(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var Ac=Pc();function Tc(r){return $(r==null?void 0:r[Ac])}function Ic(r){return rc(this,arguments,function(){var t,n,s,o;return xn(this,function(a){switch(a.label){case 0:t=r.getReader(),a.label=1;case 1:a.trys.push([1,,9,10]),a.label=2;case 2:return[4,Ke(t.read())];case 3:return n=a.sent(),s=n.value,o=n.done,o?[4,Ke(void 0)]:[3,5];case 4:return[2,a.sent()];case 5:return[4,Ke(s)];case 6:return[4,a.sent()];case 7:return a.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function Rc(r){return $(r==null?void 0:r.getReader)}function Oc(r){if(r instanceof he)return r;if(r!=null){if(Sc(r))return Nc(r);if(kc(r))return Mc(r);if(Ec(r))return jc(r);if(Cc(r))return $n(r);if(Tc(r))return Dc(r);if(Rc(r))return Lc(r)}throw xc(r)}function Nc(r){return new he(function(e){var t=r[kr]();if($(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Mc(r){return new he(function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()})}function jc(r){return new he(function(e){r.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,On)})}function Dc(r){return new he(function(e){var t,n;try{for(var s=He(r),o=s.next();!o.done;o=s.next()){var a=o.value;if(e.next(a),e.closed)return}}catch(c){t={error:c}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}e.complete()})}function $n(r){return new he(function(e){Uc(r,e).catch(function(t){return e.error(t)})})}function Lc(r){return $n(Ic(r))}function Uc(r,e){var t,n,s,o;return tc(this,void 0,void 0,function(){var a,c;return xn(this,function(u){switch(u.label){case 0:u.trys.push([0,5,6,11]),t=nc(r),u.label=1;case 1:return[4,t.next()];case 2:if(n=u.sent(),!!n.done)return[3,4];if(a=n.value,e.next(a),e.closed)return[2];u.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return c=u.sent(),s={error:c},[3,11];case 6:return u.trys.push([6,,9,10]),n&&!n.done&&(o=t.return)?[4,o.call(t)]:[3,8];case 7:u.sent(),u.label=8;case 8:return[3,10];case 9:if(s)throw s.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function $c(r,e,t,n,s){n===void 0&&(n=0),s===void 0&&(s=!1);var o=e.schedule(function(){t(),s?r.add(this.schedule(null,n)):this.unsubscribe()},n);if(r.add(o),!s)return o}function Fc(r,e){var t=$(r)?r:function(){return r},n=function(s){return s.error(t())};return new he(n)}var Zc=qt(function(r){return function(){r(this),this.name="EmptyError",this.message="no elements in sequence"}});function Vc(r,e){return new Promise(function(t,n){var s=!1,o;r.subscribe({next:function(a){o=a,s=!0},error:n,complete:function(){s?t(o):n(new Zc)}})})}function zc(r){return r instanceof Date&&!isNaN(r)}var Bc=qt(function(r){return function(t){t===void 0&&(t=null),r(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}});function qc(r,e){var t=zc(r)?{first:r}:typeof r=="number"?{each:r}:r,n=t.first,s=t.each,o=t.with,a=o===void 0?Yc:o,c=t.scheduler,u=c===void 0?bc:c,l=t.meta,d=l===void 0?null:l;if(n==null&&s==null)throw new TypeError("No timeout provided.");return fc(function(h,b){var m,v,E=null,I=0,C=function(A){v=$c(b,u,function(){try{m.unsubscribe(),Oc(a({meta:d,lastValue:E,seen:I})).subscribe(b)}catch(T){b.error(T)}},A)};m=h.subscribe(hc(b,function(A){v==null||v.unsubscribe(),I++,b.next(E=A),s>0&&C(s)},void 0,void 0,function(){v!=null&&v.closed||v==null||v.unsubscribe(),E=null})),!I&&C(n!=null?typeof n=="number"?n:+n-u.now():s)})}function Yc(r){throw new Bc(r)}class Ht{constructor(){this.set=e=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"success",isSuccess:!0,loadedValue:e},this._subject.next(e),this._subject.complete()},this.throw=(e,t)=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"error",isSuccess:!1,error:e,errMsg:t},this._subject.error(e)},this.getValueIfLoadedElse=e=>this._current.status==="success"?this._current.loadedValue:e,this.subscribe=e=>{if(this._current.status==="success"){e(this._current);return}this._current.status==="error"&&e(this._current);const t=this._subject.subscribe({next:()=>{if(this._current.status!=="success")throw new Error("Invalid state (next): please make sure to update _current before the subject");e(this._current),t.unsubscribe()},error:()=>{if(this._current.status!=="error")throw new Error("Invalid state (error): please make sure to update _current before the subject");e(this._current)}})},this.waitForLoad=e=>{if(this._current.status==="success")return Promise.resolve(this._current.loadedValue);if(this._current.status==="error")return Promise.reject(this._current.error);this._current.status!=="initial"&&ar(this._current);const t={first:e.timeoutSec*1e3,with:()=>Fc(()=>new Error(e.timeoutErrMsg))};return Vc(this._subject.pipe(qc(t)))},this._current={status:"initial",isSuccess:!1},this._subject=new jn}get current(){return this._current}}const{log__:Gc,err__:Wc}=D("init-flows"),Kt=(r,e)=>{const t=new Ht;return{publisher:t,initialize:async n=>{try{if(t.current.isSuccess)throw new Error("This flow has already been initialized.");const s=await e(n);Gc(`✔ ${r} flow initialized successfully. Result:`,s),t.set(s)}catch(s){Wc(`𝙭 ${r} flow initialization failed. Error:`,de(s),"Details:",s),t.throw(s,de(s))}}}},Hc=async(r,e,t)=>{await Promise.all(Object.values(r).map(n=>n.initialize({context:e,formCallbacks:t})))},Kc=()=>({stripePR:Kt("Stripe PR",ee.stripePR.init),stripeLink:Kt("Stripe Link",ee.stripeLink.init),airwallexGooglePay:Kt("Airwallex GPay",ee.airwallexGooglePay.init),airwallexApplePay:Kt("Airwallex ApplePay",ee.airwallexApplePay.init)}),{err__:Jc}=D("form-callbacks"),te=i.function().optional(),Fn=i.object({onFocus:te,onBlur:te,onChange:te,onLoad:te,onLoadError:te,onValidationError:te,onCheckoutStarted:te,onCheckoutSuccess:te,onSetupPaymentMethodSuccess:te,onCheckoutError:te,onPaymentRequestLoad:te}),ae=class ae{constructor(){this.setCallbacks=e=>{this._callbacks=ae.createEmptyCallbacks(),Object.entries(e).forEach(([t,n])=>{const s=Hs(t,n??ae.NOOP,Jc);this._callbacks[t]=s})},this._callbacks=ae.createEmptyCallbacks()}get get(){return{...this._callbacks}}};ae.NOOP=()=>{},ae.createEmptyCallbacks=()=>{const e={};return Object.keys(Fn.keyof().enum).forEach(t=>{e[t]=ae.NOOP}),e},ae.fromObject=e=>{const t=new ae;return t.setCallbacks(Fn.parse(e)),t};let Er=ae;class Xc{constructor(e,t,n,s){this.handleMessage=o=>{if(!o.source)throw new Error("No source found");if(Zn(o.origin)!==Zn(this.baseUrl)||typeof o.data=="object"&&o.data.penpal)return;const a=Zo(JSON.parse(o.data));if(!this.validateEvent(a))return;const{elementId:u,payload:l}=a,d=l.type;switch(d){case"LAYOUT":this.internalCallbacks.setFormHeight(l.height?`${l.height}px`:"100%");break;case"FOCUS":this.formCallbacks.get.onFocus(u,l.elementType);break;case"BLUR":this.formCallbacks.get.onBlur(u,l.elementType);break;case"CHANGE":this.formCallbacks.get.onChange(u,l.elementType,l.errors);break;case"LOADED":this.eventTargets[u]=o.source,this.internalCallbacks.onCdeLoaded(l);break;case"LOAD_ERROR":this.internalCallbacks.onCdeLoadError(l.message);break;case"VALIDATION_ERROR":this.formCallbacks.get.onValidationError(l.elementType,l.errors,u);break;default:console.warn("[form] Unhandled event type:",d)}},this.validateEvent=o=>o.formId!==this.formId||!o.elementId?(console.log("[OJS] formId",this.formId,o.formId),console.warn("[form] Ignoring unknown event:",o),!1):this.nonces.has(o.nonce)?(console.warn("[form] Ignoring duplicate event:",o),!1):(this.nonces.add(o.nonce),!0),this.eventTargets={},this.nonces=new Set,this.formId=e,this.baseUrl=t,this.formCallbacks=n,this.internalCallbacks=s}}const Zn=r=>new URL(r).origin;async function Qc(r,e){const n=await Wr({iframe:r,debug:!1,childOrigin:e}).promise,s=await li(n);if(!ui(n,s))throw new Error("Got invalid CDE connection object");return n}class el{constructor(){this.connections=new Map}addConnection(e,t){this.connections.set(e,t)}getConnection(){const e=this.connections.values().next().value;if(!e)throw new Error("Connection not found");return e}getAllConnections(){return this.connections}}const tl=(r,e,t)=>{const{stripePR:n}=r;n.publisher.subscribe(s=>{if(s.isSuccess){const o=s.loadedValue,a=o.isAvailable&&o.availableProviders.applePay,c=o.isAvailable&&o.availableProviders.googlePay,u={apple_pay:{isLoading:!1,isAvailable:a,startFlow:async l=>{a&&Vn("apple_pay",o,e,t,l)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async l=>{c&&Vn("google_pay",o,e,t,l)}}};t.get.onPaymentRequestLoad(u)}})},Vn=(r,e,t,n,s)=>ee.stripePR.run({context:t,checkoutPaymentMethod:yr(t.checkoutPaymentMethods,r),nonCdeFormInputs:ze(t.formDiv),formCallbacks:n,customParams:{provider:r,overridePaymentRequest:s==null?void 0:s.overridePaymentRequest},initResult:e}),zn="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__:Ce,err__:Jt}=D("op-form"),me=class me{constructor(e){this.cdeLoadEvent=new Ht,this.anyCdeConn=new Ht,this.context=new Ht,this.initFlows=Kc(),this.startFormInit=async()=>{try{Ce("Initializing OpenPay form:"),Ce("├ Waiting for CDE load event...");const t=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:zn});Ce("├ CDE load event received"),Ce("├ Waiting for CDE connection...");const n=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:zn});Ce("├ CDE connection received"),Ce("├ Creating OJS context, setting up handlers...");const s=me.buildOjsFlowContext(this.config,t,n,this.getFormDiv());this.context.set(s),tl(this.initFlows,s,this.formCallbacks),Ce("├ Starting OJS init flows..."),await Hc(this.initFlows,s,this.formCallbacks),this.formCallbacks.get.onLoad(t.totalAmountAtoms,t.currency),Ce("╰ Done initializing OJS flows.")}catch(t){const n=de(t);Jt("╰ Error initializing OP form:",n),this.formCallbacks.get.onLoadError(n)}},this.setFormHeight=t=>{this.formProperties.height=t,this.registeredElements&&Object.values(this.registeredElements).forEach(n=>{n&&(n.node.style.height=t)})},this.onCdeLoaded=t=>{this.cdeLoadEvent.current.isSuccess||this.cdeLoadEvent.set(t)},this.onCdeLoadError=t=>{this.cdeLoadEvent.current.isSuccess||this.cdeLoadEvent.throw(new Error(t),t)},this.createElement=(t,n={})=>{if(!this.config)throw new Error("OpenPay form not initialized");const s=Ks.parse(t),o=document.createElement("iframe"),a=this.buildQueryString(n);o.name=`${s}-element`;const c=new URL(`/app/v1/${o.name}/`,this.config.baseUrl);return c.search=a.toString(),o.src=c.href,o.style.border="none",o.style.width="100%",this.registerIframe(s,o)},this.registerIframe=(t,n)=>{const s={type:t,node:n,mount:o=>{var a;return(a=document.querySelector(o))==null?void 0:a.appendChild(n)}};return this.connectToElement({type:s.type,node:s.node}),this.registeredElements||(this.registeredElements={[Ve.CARD]:void 0,[Ve.CARD_NUMBER]:void 0,[Ve.CARD_EXPIRY]:void 0,[Ve.CARD_CVC]:void 0}),this.registeredElements[t]=s,s},this.buildQueryString=t=>{const n=new URLSearchParams;return n.append("referer",this.referrer),n.append("formId",this.formId),t.styles&&n.append("styles",jo(t.styles)),n.append("secureToken",this.config.checkoutSecureToken),n},this.connectToElement=t=>{Qc(t.node).then(n=>{this.connectionManager.addConnection(t.type,n),this.anyCdeConn.current.isSuccess||this.anyCdeConn.set(n)}).catch(n=>Jt("[FORM] Error connecting to CDE iframe",n))},this.getFormDiv=()=>document.querySelector(this.formTarget)??document.body,this.submitCard=()=>{const t=this.context.getValueIfLoadedElse(null);if(!t){Jt("Please wait for the form to finish loading before submitting.");return}ee.commonCC.run({context:t,checkoutPaymentMethod:yr(t.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:ze(t.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections()},initResult:void 0})},this.generalSubmit=t=>{const n=this.context.getValueIfLoadedElse(null);if(!n){Jt("Please wait for the form to finish loading before submitting.");return}switch(t){case"pockyt-paypal":return ee.pockytPaypal.run({context:n,checkoutPaymentMethod:yr(n.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:ze(n.formDiv),formCallbacks:this.formCallbacks,customParams:void 0,initResult:void 0});case"airwallex-google-pay":return this.initFlows.airwallexGooglePay.publisher.subscribe(s=>{s.isSuccess&&s.loadedValue.isAvailable&&s.loadedValue.startFlow()});case"airwallex-apple-pay":return this.initFlows.airwallexApplePay.publisher.subscribe(s=>{s.isSuccess&&s.loadedValue.isAvailable&&s.loadedValue.startFlow()});default:ar(t)}},this.submit=this.submitCard,this.destroy=()=>{for(const t of Object.values(this.registeredElements??{}))t&&t.node.remove();window.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.registeredElements=null,delete window.ojs},this.updateCallbacks=t=>{this.formCallbacks.setCallbacks(t)},me.assignAsSingleton(this),this.ojsVersion="0.2.2",this.ojsReleaseVersion="0.2.2-alpha.60a8026",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=Er.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${Fo()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new el,this.eventHandler=new Xc(this.formId,this.baseUrl,this.formCallbacks,{setFormHeight:this.setFormHeight,onCdeLoaded:this.onCdeLoaded,onCdeLoadError:this.onCdeLoadError}),window.addEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.startFormInit()}get checkoutSecureToken(){return this.config.checkoutSecureToken}};me.ojsFlows=ee,me.assignAsSingleton=e=>{if(me.getInstance())throw new Error("OpenPay instance already exists. Only one instance is allowed.");window.ojs=e},me.getInstance=()=>window.ojs??null,me.buildOjsFlowContext=(e,t,n,s)=>({checkoutSecureToken:e.checkoutSecureToken,baseUrl:new URL(e.baseUrl??je).origin,formDiv:s,elementsSessionId:t.sessionId,checkoutPaymentMethods:t.checkoutPaymentMethods,anyCdeConnection:n,customInitParams:e.customInitParams??{}});let Sr=me;Ae.FieldName=f,Ae.OpenPayForm=Sr,Object.defineProperty(Ae,Symbol.toStringTag,{value:"Module"})});
25
+ `):"",this.name="UnsubscriptionError",this.errors=t}});function Yt(r,e){if(r){var t=r.indexOf(e);0<=t&&r.splice(t,1)}}var bt=function(){function r(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return r.prototype.unsubscribe=function(){var e,t,n,s,o;if(!this.closed){this.closed=!0;var a=this._parentage;if(a)if(this._parentage=null,Array.isArray(a))try{for(var c=He(a),u=c.next();!u.done;u=c.next()){var l=u.value;l.remove(this)}}catch(E){e={error:E}}finally{try{u&&!u.done&&(t=c.return)&&t.call(c)}finally{if(e)throw e.error}}else a.remove(this);var d=this.initialTeardown;if($(d))try{d()}catch(E){o=E instanceof gr?E.errors:[E]}var h=this._finalizers;if(h){this._finalizers=null;try{for(var b=He(h),m=b.next();!m.done;m=b.next()){var v=m.value;try{Tn(v)}catch(E){o=o??[],E instanceof gr?o=Bt(Bt([],zt(o)),zt(E.errors)):o.push(E)}}}catch(E){n={error:E}}finally{try{m&&!m.done&&(s=b.return)&&s.call(b)}finally{if(n)throw n.error}}}if(o)throw new gr(o)}},r.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)Tn(e);else{if(e instanceof r){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},r.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},r.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},r.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&Yt(t,e)},r.prototype.remove=function(e){var t=this._finalizers;t&&Yt(t,e),e instanceof r&&e._removeParent(this)},r.EMPTY=function(){var e=new r;return e.closed=!0,e}(),r}(),Pn=bt.EMPTY;function An(r){return r instanceof bt||r&&"closed"in r&&$(r.remove)&&$(r.add)&&$(r.unsubscribe)}function Tn(r){$(r)?r():r.unsubscribe()}var In={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},Rn={setTimeout:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setTimeout.apply(void 0,Bt([r,e],zt(t)))},clearTimeout:function(r){var e=Rn.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(r)},delegate:void 0};function On(r){Rn.setTimeout(function(){throw r})}function Nn(){}function Gt(r){r()}var vr=function(r){Se(e,r);function e(t){var n=r.call(this)||this;return n.isStopped=!1,t?(n.destination=t,An(t)&&t.add(n)):n.destination=ac,n}return e.create=function(t,n,s){return new br(t,n,s)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,r.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(bt),sc=Function.prototype.bind;function wr(r,e){return sc.call(r,e)}var oc=function(){function r(e){this.partialObserver=e}return r.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(n){Wt(n)}},r.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(n){Wt(n)}else Wt(e)},r.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){Wt(t)}},r}(),br=function(r){Se(e,r);function e(t,n,s){var o=r.call(this)||this,a;if($(t)||!t)a={next:t??void 0,error:n??void 0,complete:s??void 0};else{var c;o&&In.useDeprecatedNextContext?(c=Object.create(t),c.unsubscribe=function(){return o.unsubscribe()},a={next:t.next&&wr(t.next,c),error:t.error&&wr(t.error,c),complete:t.complete&&wr(t.complete,c)}):a=t}return o.destination=new oc(a),o}return e}(vr);function Wt(r){On(r)}function ic(r){throw r}var ac={closed:!0,next:Nn,error:ic,complete:Nn},kr=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function cc(r){return r}function lc(r){return r.length===0?cc:r.length===1?r[0]:function(t){return r.reduce(function(n,s){return s(n)},t)}}var he=function(){function r(e){e&&(this._subscribe=e)}return r.prototype.lift=function(e){var t=new r;return t.source=this,t.operator=e,t},r.prototype.subscribe=function(e,t,n){var s=this,o=dc(e)?e:new br(e,t,n);return Gt(function(){var a=s,c=a.operator,u=a.source;o.add(c?c.call(o,u):u?s._subscribe(o):s._trySubscribe(o))}),o},r.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},r.prototype.forEach=function(e,t){var n=this;return t=Mn(t),new t(function(s,o){var a=new br({next:function(c){try{e(c)}catch(u){o(u),a.unsubscribe()}},error:o,complete:s});n.subscribe(a)})},r.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},r.prototype[kr]=function(){return this},r.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return lc(e)(this)},r.prototype.toPromise=function(e){var t=this;return e=Mn(e),new e(function(n,s){var o;t.subscribe(function(a){return o=a},function(a){return s(a)},function(){return n(o)})})},r.create=function(e){return new r(e)},r}();function Mn(r){var e;return(e=r??In.Promise)!==null&&e!==void 0?e:Promise}function uc(r){return r&&$(r.next)&&$(r.error)&&$(r.complete)}function dc(r){return r&&r instanceof vr||uc(r)&&An(r)}function pc(r){return $(r==null?void 0:r.lift)}function fc(r){return function(e){if(pc(e))return e.lift(function(t){try{return r(t,this)}catch(n){this.error(n)}});throw new TypeError("Unable to lift unknown Observable type")}}function hc(r,e,t,n,s){return new mc(r,e,t,n,s)}var mc=function(r){Se(e,r);function e(t,n,s,o,a,c){var u=r.call(this,t)||this;return u.onFinalize=a,u.shouldUnsubscribe=c,u._next=n?function(l){try{n(l)}catch(d){t.error(d)}}:r.prototype._next,u._error=o?function(l){try{o(l)}catch(d){t.error(d)}finally{this.unsubscribe()}}:r.prototype._error,u._complete=s?function(){try{s()}catch(l){t.error(l)}finally{this.unsubscribe()}}:r.prototype._complete,u}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;r.prototype.unsubscribe.call(this),!n&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e}(vr),yc=qt(function(r){return function(){r(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),jn=function(r){Se(e,r);function e(){var t=r.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return e.prototype.lift=function(t){var n=new Dn(this,this);return n.operator=t,n},e.prototype._throwIfClosed=function(){if(this.closed)throw new yc},e.prototype.next=function(t){var n=this;Gt(function(){var s,o;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var a=He(n.currentObservers),c=a.next();!c.done;c=a.next()){var u=c.value;u.next(t)}}catch(l){s={error:l}}finally{try{c&&!c.done&&(o=a.return)&&o.call(a)}finally{if(s)throw s.error}}}})},e.prototype.error=function(t){var n=this;Gt(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=t;for(var s=n.observers;s.length;)s.shift().error(t)}})},e.prototype.complete=function(){var t=this;Gt(function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var n=t.observers;n.length;)n.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var t;return((t=this.observers)===null||t===void 0?void 0:t.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),r.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var n=this,s=this,o=s.hasError,a=s.isStopped,c=s.observers;return o||a?Pn:(this.currentObservers=null,c.push(t),new bt(function(){n.currentObservers=null,Yt(c,t)}))},e.prototype._checkFinalizedStatuses=function(t){var n=this,s=n.hasError,o=n.thrownError,a=n.isStopped;s?t.error(o):a&&t.complete()},e.prototype.asObservable=function(){var t=new he;return t.source=this,t},e.create=function(t,n){return new Dn(t,n)},e}(he),Dn=function(r){Se(e,r);function e(t,n){var s=r.call(this)||this;return s.destination=t,s.source=n,s}return e.prototype.next=function(t){var n,s;(s=(n=this.destination)===null||n===void 0?void 0:n.next)===null||s===void 0||s.call(n,t)},e.prototype.error=function(t){var n,s;(s=(n=this.destination)===null||n===void 0?void 0:n.error)===null||s===void 0||s.call(n,t)},e.prototype.complete=function(){var t,n;(n=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||n===void 0||n.call(t)},e.prototype._subscribe=function(t){var n,s;return(s=(n=this.source)===null||n===void 0?void 0:n.subscribe(t))!==null&&s!==void 0?s:Pn},e}(jn),_c={now:function(){return Date.now()},delegate:void 0},gc=function(r){Se(e,r);function e(t,n){return r.call(this)||this}return e.prototype.schedule=function(t,n){return this},e}(bt),Ln={setInterval:function(r,e){for(var t=[],n=2;n<arguments.length;n++)t[n-2]=arguments[n];return setInterval.apply(void 0,Bt([r,e],zt(t)))},clearInterval:function(r){return clearInterval(r)},delegate:void 0},vc=function(r){Se(e,r);function e(t,n){var s=r.call(this,t,n)||this;return s.scheduler=t,s.work=n,s.pending=!1,s}return e.prototype.schedule=function(t,n){var s;if(n===void 0&&(n=0),this.closed)return this;this.state=t;var o=this.id,a=this.scheduler;return o!=null&&(this.id=this.recycleAsyncId(a,o,n)),this.pending=!0,this.delay=n,this.id=(s=this.id)!==null&&s!==void 0?s:this.requestAsyncId(a,this.id,n),this},e.prototype.requestAsyncId=function(t,n,s){return s===void 0&&(s=0),Ln.setInterval(t.flush.bind(t,this),s)},e.prototype.recycleAsyncId=function(t,n,s){if(s===void 0&&(s=0),s!=null&&this.delay===s&&this.pending===!1)return n;n!=null&&Ln.clearInterval(n)},e.prototype.execute=function(t,n){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var s=this._execute(t,n);if(s)return s;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(t,n){var s=!1,o;try{this.work(t)}catch(a){s=!0,o=a||new Error("Scheduled action threw falsy error")}if(s)return this.unsubscribe(),o},e.prototype.unsubscribe=function(){if(!this.closed){var t=this,n=t.id,s=t.scheduler,o=s.actions;this.work=this.state=this.scheduler=null,this.pending=!1,Yt(o,this),n!=null&&(this.id=this.recycleAsyncId(s,n,null)),this.delay=null,r.prototype.unsubscribe.call(this)}},e}(gc),Un=function(){function r(e,t){t===void 0&&(t=r.now),this.schedulerActionCtor=e,this.now=t}return r.prototype.schedule=function(e,t,n){return t===void 0&&(t=0),new this.schedulerActionCtor(this,e).schedule(n,t)},r.now=_c.now,r}(),wc=function(r){Se(e,r);function e(t,n){n===void 0&&(n=Un.now);var s=r.call(this,t,n)||this;return s.actions=[],s._active=!1,s}return e.prototype.flush=function(t){var n=this.actions;if(this._active){n.push(t);return}var s;this._active=!0;do if(s=t.execute(t.state,t.delay))break;while(t=n.shift());if(this._active=!1,s){for(;t=n.shift();)t.unsubscribe();throw s}},e}(Un),bc=new wc(vc),kc=function(r){return r&&typeof r.length=="number"&&typeof r!="function"};function Ec(r){return $(r==null?void 0:r.then)}function Sc(r){return $(r[kr])}function Cc(r){return Symbol.asyncIterator&&$(r==null?void 0:r[Symbol.asyncIterator])}function xc(r){return new TypeError("You provided "+(r!==null&&typeof r=="object"?"an invalid object":"'"+r+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Pc(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var Ac=Pc();function Tc(r){return $(r==null?void 0:r[Ac])}function Ic(r){return rc(this,arguments,function(){var t,n,s,o;return xn(this,function(a){switch(a.label){case 0:t=r.getReader(),a.label=1;case 1:a.trys.push([1,,9,10]),a.label=2;case 2:return[4,Ke(t.read())];case 3:return n=a.sent(),s=n.value,o=n.done,o?[4,Ke(void 0)]:[3,5];case 4:return[2,a.sent()];case 5:return[4,Ke(s)];case 6:return[4,a.sent()];case 7:return a.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function Rc(r){return $(r==null?void 0:r.getReader)}function Oc(r){if(r instanceof he)return r;if(r!=null){if(Sc(r))return Nc(r);if(kc(r))return Mc(r);if(Ec(r))return jc(r);if(Cc(r))return $n(r);if(Tc(r))return Dc(r);if(Rc(r))return Lc(r)}throw xc(r)}function Nc(r){return new he(function(e){var t=r[kr]();if($(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Mc(r){return new he(function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()})}function jc(r){return new he(function(e){r.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,On)})}function Dc(r){return new he(function(e){var t,n;try{for(var s=He(r),o=s.next();!o.done;o=s.next()){var a=o.value;if(e.next(a),e.closed)return}}catch(c){t={error:c}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}e.complete()})}function $n(r){return new he(function(e){Uc(r,e).catch(function(t){return e.error(t)})})}function Lc(r){return $n(Ic(r))}function Uc(r,e){var t,n,s,o;return tc(this,void 0,void 0,function(){var a,c;return xn(this,function(u){switch(u.label){case 0:u.trys.push([0,5,6,11]),t=nc(r),u.label=1;case 1:return[4,t.next()];case 2:if(n=u.sent(),!!n.done)return[3,4];if(a=n.value,e.next(a),e.closed)return[2];u.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return c=u.sent(),s={error:c},[3,11];case 6:return u.trys.push([6,,9,10]),n&&!n.done&&(o=t.return)?[4,o.call(t)]:[3,8];case 7:u.sent(),u.label=8;case 8:return[3,10];case 9:if(s)throw s.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function $c(r,e,t,n,s){n===void 0&&(n=0),s===void 0&&(s=!1);var o=e.schedule(function(){t(),s?r.add(this.schedule(null,n)):this.unsubscribe()},n);if(r.add(o),!s)return o}function Fc(r,e){var t=$(r)?r:function(){return r},n=function(s){return s.error(t())};return new he(n)}var Zc=qt(function(r){return function(){r(this),this.name="EmptyError",this.message="no elements in sequence"}});function Vc(r,e){return new Promise(function(t,n){var s=!1,o;r.subscribe({next:function(a){o=a,s=!0},error:n,complete:function(){s?t(o):n(new Zc)}})})}function zc(r){return r instanceof Date&&!isNaN(r)}var Bc=qt(function(r){return function(t){t===void 0&&(t=null),r(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}});function qc(r,e){var t=zc(r)?{first:r}:typeof r=="number"?{each:r}:r,n=t.first,s=t.each,o=t.with,a=o===void 0?Yc:o,c=t.scheduler,u=c===void 0?bc:c,l=t.meta,d=l===void 0?null:l;if(n==null&&s==null)throw new TypeError("No timeout provided.");return fc(function(h,b){var m,v,E=null,I=0,C=function(A){v=$c(b,u,function(){try{m.unsubscribe(),Oc(a({meta:d,lastValue:E,seen:I})).subscribe(b)}catch(T){b.error(T)}},A)};m=h.subscribe(hc(b,function(A){v==null||v.unsubscribe(),I++,b.next(E=A),s>0&&C(s)},void 0,void 0,function(){v!=null&&v.closed||v==null||v.unsubscribe(),E=null})),!I&&C(n!=null?typeof n=="number"?n:+n-u.now():s)})}function Yc(r){throw new Bc(r)}class Ht{constructor(){this.set=e=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"success",isSuccess:!0,loadedValue:e},this._subject.next(e),this._subject.complete()},this.throw=(e,t)=>{if(this._current.status==="success")throw new Error("LoadedOnce is already in success state");this._current={status:"error",isSuccess:!1,error:e,errMsg:t},this._subject.error(e)},this.getValueIfLoadedElse=e=>this._current.status==="success"?this._current.loadedValue:e,this.subscribe=e=>{if(this._current.status==="success"){e(this._current);return}this._current.status==="error"&&e(this._current);const t=this._subject.subscribe({next:()=>{if(this._current.status!=="success")throw new Error("Invalid state (next): please make sure to update _current before the subject");e(this._current),t.unsubscribe()},error:()=>{if(this._current.status!=="error")throw new Error("Invalid state (error): please make sure to update _current before the subject");e(this._current)}})},this.waitForLoad=e=>{if(this._current.status==="success")return Promise.resolve(this._current.loadedValue);if(this._current.status==="error")return Promise.reject(this._current.error);this._current.status!=="initial"&&ar(this._current);const t={first:e.timeoutSec*1e3,with:()=>Fc(()=>new Error(e.timeoutErrMsg))};return Vc(this._subject.pipe(qc(t)))},this._current={status:"initial",isSuccess:!1},this._subject=new jn}get current(){return this._current}}const{log__:Gc,err__:Wc}=D("init-flows"),Kt=(r,e)=>{const t=new Ht;return{publisher:t,initialize:async n=>{try{if(t.current.isSuccess)throw new Error("This flow has already been initialized.");const s=await e(n);Gc(`✔ ${r} flow initialized successfully. Result:`,s),t.set(s)}catch(s){Wc(`𝙭 ${r} flow initialization failed. Error:`,de(s),"Details:",s),t.throw(s,de(s))}}}},Hc=async(r,e,t)=>{await Promise.all(Object.values(r).map(n=>n.initialize({context:e,formCallbacks:t})))},Kc=()=>({stripePR:Kt("Stripe PR",ee.stripePR.init),stripeLink:Kt("Stripe Link",ee.stripeLink.init),airwallexGooglePay:Kt("Airwallex GPay",ee.airwallexGooglePay.init),airwallexApplePay:Kt("Airwallex ApplePay",ee.airwallexApplePay.init)}),{err__:Jc}=D("form-callbacks"),te=i.function().optional(),Fn=i.object({onFocus:te,onBlur:te,onChange:te,onLoad:te,onLoadError:te,onValidationError:te,onCheckoutStarted:te,onCheckoutSuccess:te,onSetupPaymentMethodSuccess:te,onCheckoutError:te,onPaymentRequestLoad:te}),ae=class ae{constructor(){this.setCallbacks=e=>{this._callbacks=ae.createEmptyCallbacks(),Object.entries(e).forEach(([t,n])=>{const s=Hs(t,n??ae.NOOP,Jc);this._callbacks[t]=s})},this._callbacks=ae.createEmptyCallbacks()}get get(){return{...this._callbacks}}};ae.NOOP=()=>{},ae.createEmptyCallbacks=()=>{const e={};return Object.keys(Fn.keyof().enum).forEach(t=>{e[t]=ae.NOOP}),e},ae.fromObject=e=>{const t=new ae;return t.setCallbacks(Fn.parse(e)),t};let Er=ae;class Xc{constructor(e,t,n,s){this.handleMessage=o=>{if(!o.source)throw new Error("No source found");if(Zn(o.origin)!==Zn(this.baseUrl)||typeof o.data=="object"&&o.data.penpal)return;const a=Zo(JSON.parse(o.data));if(!this.validateEvent(a))return;const{elementId:u,payload:l}=a,d=l.type;switch(d){case"LAYOUT":this.internalCallbacks.setFormHeight(l.height?`${l.height}px`:"100%");break;case"FOCUS":this.formCallbacks.get.onFocus(u,l.elementType);break;case"BLUR":this.formCallbacks.get.onBlur(u,l.elementType);break;case"CHANGE":this.formCallbacks.get.onChange(u,l.elementType,l.errors);break;case"LOADED":this.eventTargets[u]=o.source,this.internalCallbacks.onCdeLoaded(l);break;case"LOAD_ERROR":this.internalCallbacks.onCdeLoadError(l.message);break;case"VALIDATION_ERROR":this.formCallbacks.get.onValidationError(l.elementType,l.errors,u);break;default:console.warn("[form] Unhandled event type:",d)}},this.validateEvent=o=>o.formId!==this.formId||!o.elementId?(console.log("[OJS] formId",this.formId,o.formId),console.warn("[form] Ignoring unknown event:",o),!1):this.nonces.has(o.nonce)?(console.warn("[form] Ignoring duplicate event:",o),!1):(this.nonces.add(o.nonce),!0),this.eventTargets={},this.nonces=new Set,this.formId=e,this.baseUrl=t,this.formCallbacks=n,this.internalCallbacks=s}}const Zn=r=>new URL(r).origin;async function Qc(r,e){const n=await Wr({iframe:r,debug:!1,childOrigin:e}).promise,s=await li(n);if(!ui(n,s))throw new Error("Got invalid CDE connection object");return n}class el{constructor(){this.connections=new Map}addConnection(e,t){this.connections.set(e,t)}getConnection(){const e=this.connections.values().next().value;if(!e)throw new Error("Connection not found");return e}getAllConnections(){return this.connections}}const tl=(r,e,t)=>{const{stripePR:n}=r;n.publisher.subscribe(s=>{if(s.isSuccess){const o=s.loadedValue,a=o.isAvailable&&o.availableProviders.applePay,c=o.isAvailable&&o.availableProviders.googlePay,u={apple_pay:{isLoading:!1,isAvailable:a,startFlow:async l=>{a&&Vn("apple_pay",o,e,t,l)}},google_pay:{isLoading:!1,isAvailable:c,startFlow:async l=>{c&&Vn("google_pay",o,e,t,l)}}};t.get.onPaymentRequestLoad(u)}})},Vn=(r,e,t,n,s)=>ee.stripePR.run({context:t,checkoutPaymentMethod:yr(t.checkoutPaymentMethods,r),nonCdeFormInputs:ze(t.formDiv),formCallbacks:n,customParams:{provider:r,overridePaymentRequest:s==null?void 0:s.overridePaymentRequest},initResult:e}),zn="The secure form failed to load properly. Please check your internet connection, or try again later.",{log__:Ce,err__:Jt}=D("op-form"),me=class me{constructor(e){this.cdeLoadEvent=new Ht,this.anyCdeConn=new Ht,this.context=new Ht,this.initFlows=Kc(),this.startFormInit=async()=>{try{Ce("Initializing OpenPay form:"),Ce("├ Waiting for CDE load event...");const t=await this.cdeLoadEvent.waitForLoad({timeoutSec:120,timeoutErrMsg:zn});Ce("├ CDE load event received"),Ce("├ Waiting for CDE connection...");const n=await this.anyCdeConn.waitForLoad({timeoutSec:120,timeoutErrMsg:zn});Ce("├ CDE connection received"),Ce("├ Creating OJS context, setting up handlers...");const s=me.buildOjsFlowContext(this.config,t,n,this.getFormDiv());this.context.set(s),tl(this.initFlows,s,this.formCallbacks),Ce("├ Starting OJS init flows..."),await Hc(this.initFlows,s,this.formCallbacks),this.formCallbacks.get.onLoad(t.totalAmountAtoms,t.currency),Ce("╰ Done initializing OJS flows.")}catch(t){const n=de(t);Jt("╰ Error initializing OP form:",n),this.formCallbacks.get.onLoadError(n)}},this.setFormHeight=t=>{this.formProperties.height=t,this.registeredElements&&Object.values(this.registeredElements).forEach(n=>{n&&(n.node.style.height=t)})},this.onCdeLoaded=t=>{this.cdeLoadEvent.current.isSuccess||this.cdeLoadEvent.set(t)},this.onCdeLoadError=t=>{this.cdeLoadEvent.current.isSuccess||this.cdeLoadEvent.throw(new Error(t),t)},this.createElement=(t,n={})=>{if(!this.config)throw new Error("OpenPay form not initialized");const s=Ks.parse(t),o=document.createElement("iframe"),a=this.buildQueryString(n);o.name=`${s}-element`;const c=new URL(`/app/v1/${o.name}/`,this.config.baseUrl);return c.search=a.toString(),o.src=c.href,o.style.border="none",o.style.width="100%",this.registerIframe(s,o)},this.registerIframe=(t,n)=>{const s={type:t,node:n,mount:o=>{var a;return(a=document.querySelector(o))==null?void 0:a.appendChild(n)}};return this.connectToElement({type:s.type,node:s.node}),this.registeredElements||(this.registeredElements={[Ve.CARD]:void 0,[Ve.CARD_NUMBER]:void 0,[Ve.CARD_EXPIRY]:void 0,[Ve.CARD_CVC]:void 0}),this.registeredElements[t]=s,s},this.buildQueryString=t=>{const n=new URLSearchParams;return n.append("referer",this.referrer),n.append("formId",this.formId),t.styles&&n.append("styles",jo(t.styles)),n.append("secureToken",this.config.checkoutSecureToken),n},this.connectToElement=t=>{Qc(t.node).then(n=>{this.connectionManager.addConnection(t.type,n),this.anyCdeConn.current.isSuccess||this.anyCdeConn.set(n)}).catch(n=>Jt("[FORM] Error connecting to CDE iframe",n))},this.getFormDiv=()=>document.querySelector(this.formTarget)??document.body,this.submitCard=()=>{const t=this.context.getValueIfLoadedElse(null);if(!t){Jt("Please wait for the form to finish loading before submitting.");return}ee.commonCC.run({context:t,checkoutPaymentMethod:yr(t.checkoutPaymentMethods,"credit_card"),nonCdeFormInputs:ze(t.formDiv),formCallbacks:this.formCallbacks,customParams:{currentCdeConnections:this.connectionManager.getAllConnections()},initResult:void 0})},this.generalSubmit=t=>{const n=this.context.getValueIfLoadedElse(null);if(!n){Jt("Please wait for the form to finish loading before submitting.");return}switch(t){case"pockyt-paypal":return ee.pockytPaypal.run({context:n,checkoutPaymentMethod:yr(n.checkoutPaymentMethods,"paypal","pockyt"),nonCdeFormInputs:ze(n.formDiv),formCallbacks:this.formCallbacks,customParams:void 0,initResult:void 0});case"airwallex-google-pay":return this.initFlows.airwallexGooglePay.publisher.subscribe(s=>{s.isSuccess&&s.loadedValue.isAvailable&&s.loadedValue.startFlow()});case"airwallex-apple-pay":return this.initFlows.airwallexApplePay.publisher.subscribe(s=>{s.isSuccess&&s.loadedValue.isAvailable&&s.loadedValue.startFlow()});default:ar(t)}},this.submit=this.submitCard,this.destroy=()=>{for(const t of Object.values(this.registeredElements??{}))t&&t.node.remove();window.removeEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.registeredElements=null,delete window.ojs},this.updateCallbacks=t=>{this.formCallbacks.setCallbacks(t)},me.assignAsSingleton(this),this.ojsVersion="0.2.2",this.ojsReleaseVersion="0.2.2",this.baseUrl=e.baseUrl??"https://cde.getopenpay.com",this.config={...e,baseUrl:this.baseUrl},this.formCallbacks=Er.fromObject(e),this.registeredElements=null,this.formId=`opjs-form-${Fo()}`,this.referrer=window.location.origin,this.formTarget=e.formTarget??"body",this.formProperties={height:"1px"},this.connectionManager=new el,this.eventHandler=new Xc(this.formId,this.baseUrl,this.formCallbacks,{setFormHeight:this.setFormHeight,onCdeLoaded:this.onCdeLoaded,onCdeLoadError:this.onCdeLoadError}),window.addEventListener("message",this.eventHandler.handleMessage.bind(this.eventHandler)),this.startFormInit()}get checkoutSecureToken(){return this.config.checkoutSecureToken}};me.ojsFlows=ee,me.assignAsSingleton=e=>{if(me.getInstance())throw new Error("OpenPay instance already exists. Only one instance is allowed.");window.ojs=e},me.getInstance=()=>window.ojs??null,me.buildOjsFlowContext=(e,t,n,s)=>({checkoutSecureToken:e.checkoutSecureToken,baseUrl:new URL(e.baseUrl??je).origin,formDiv:s,elementsSessionId:t.sessionId,checkoutPaymentMethods:t.checkoutPaymentMethods,anyCdeConnection:n,customInitParams:e.customInitParams??{}});let Sr=me;Ae.FieldName=f,Ae.OpenPayForm=Sr,Object.defineProperty(Ae,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getopenpay/openpay-js",
3
- "version": "0.2.2-alpha.60a8026",
3
+ "version": "0.2.2",
4
4
  "description": "Accept payments through OpenPay, right on your site",
5
5
  "author": "OpenPay <info@getopenpay.com> (https://getopenpay.com)",
6
6
  "license": "ISC",