PageSourceSearch

https://shop.barna.com/cdn/shopifycloud/checkout-web/assets/c1/component-WalletApplePayLazy.C_tNPGcW.js

js barna.com collected 2026-09-24 17:11:41 UTC 70,112 bytes, 1 lines download raw bytes

1import{U as Yn,T as Ee,q as Q,f as on,y as Bn,h as kn}from"./esnext-vendor.BBoIVOQW.js";import{D as Ft,dy as Un,gC as an,k as Vn,gB as lt,gJ as rn,b4 as Hn,aP as xn,d5 as qn,b6 as Gn,T as G,hv as zn,a5 as ve,W as We,ah as fe,ag as te,gE as Qe,hw as Wn,hx as sn,hy as Qn,g$ as Zn,bn as He,cJ as Yt,hz as Bt,d3 as jn,d4 as $n,hA as ln,gF as xe,C as kt,b3 as Jn,hB as Kn,hC as Xn,hD as cn,hE as eo,gd as to,hF as no,aj as oo,aU as ge,w as ao,hG as ro,hH as io,hI as so,hJ as pn,hK as lo}from"./addresses-is-address-empty.ZJ1ThpFy.js";import{a as D,b as W,c as ne,W as dt,u as co}from"./cross-border-hooks.BN4C-Hww.js";import{bW as Ut,fh as po,gq as dn,gr as Ze,gs as ut,c0 as un,gt as qe,bU as uo,f as yt,o as yo,fk as ho,fW as Ao,fi as mo,g9 as ht,gu as _o,fV as Ge,cS as yn,f4 as Po,c8 as Eo,fm as ct}from"./hydrate.Tsur0pib.js";import{e as At,I as Oe,W as Vt,f as z}from"./app.CUBUOQtX.js";import{f as X,g as go,s as vo,r as Le,B as fo,P as Ht,U as So,a as Co,v as xt,w as qt,i as To,N as Gt,E as No,h as Io,x as Ro,y as bo,z as Do,A as Oo,C as Lo,F as Mo,l as zt,G as wo,H as Fo,J as Wt,K as Yo,L as Bo,j as ko,T as Qt,M as Zt,O as jt,D as $t,V as Jt,I as Kt,Q as Xt,u as Uo,m as Vo,n as Ho,R as xo,o as qo,p as mt,q as hn,t as Go}from"./wallets-deserialize-delivery-handles.CQL5bAxO.js";import{a as zo,g as Wo,i as Qo}from"./hooks-useShopPayExternalAppContext.YLtTu3k6.js";import{b as K}from"./shop-pay-installments-types._vopm3yK.js";import{a as Me,b as An,u as _t}from"./shop-pay-installments-monorail.wQxzDho3.js";import{u as je,a as Zo}from"./hooks-useWalletsThreePageVaultedReviewEscalation.C7zf4Eyx.js";import{d as jo}from"./shared-report-graphql-error.DXFM-a8I.js";import{d as $o}from"./negotiated-findSelectedDeliveryMethod.DhxHslog.js";import{u as Jo}from"./hooks-payment-button.Byb-1Rv8.js";import"./shared-permissions.DW7FOCqf.js";import"./AddressPresenter.Ce4uWLSc.js";import"./hooks-useShowShopPayOptin.BPTq9EIX.js";import"./shared-negotiation-input-redeemable.DoYPkwkm.js";const Ko={id:"1501fe0af4559751b078e255872e602b9742658e6ef2d8b73091b38649adb321",type:"query",name:"ApplePayPaymentSession",source:""},mn=5,Xo=4,ea=mn+Xo,ta=600;class _n{constructor(t){this.reason=t}}class en extends Error{constructor(){super(...arguments),this.name="ApplePaySessionCreationResponseError"}}const na=({sourceId:e,isPrefetch:t})=>t?`${e}-prefetch-${Ft()}`:`${e}-${Ft()}`,Pn=async({graphql:e,sourceId:t,validationUrl:n,asPaymentMethod:o,signal:a,observability:r,isPrefetch:i,domain:s})=>{const l=na({sourceId:t,isPrefetch:i}),m=async h=>{const{data:E,error:_}=await e.staticQuery(Ko,{cache:!1,variables:h?{pendingTask:{taskId:h}}:{applePaySessionCreate:{resourceId:l,validationUrl:n,domain:s,walletInstrumentation:{expressWalletInCheckout:!o}}}});if(_)throw r.leaveErrorBreadcrumb("[ApplePay] session creation query returned GraphQL error",{error:_}),new en("session creation query returned GraphQL error");if(!E){r.counter({name:"apple_pay_session_query_error",value:1,attributes:{reason:"no_data"}}),r.log("apple_pay_api_query","ApplePaySession: No data returned"),r.leaveErrorBreadcrumb("[ApplePay] session creation query returned no data");return}return E};function d({result:h,pollingCount:E}){r.histogram({name:"apple_pay_session_creation",value:performance.now()-g,attributes:{result:h,pollingCount:E,isPrefetch:i}})}let p="",y=0;const g=performance.now();try{do{if(a.aborted)throw new At("Apple pay signal aborted",{groupingHash:"AbortedSessionError::createPaymentSession::SignalAborted"});const h=performance.now(),E=await m(p);if(!E)return;const _=E.applePaySession;switch(_.__typename){case"ApplePaySessionCreationSuccess":return d({result:"success",pollingCount:y}),_;case"ApplePaySessionCreationFailed":{if(d({result:"failed",pollingCount:y}),r.log("apple_pay_api_session_cancelled","Apply Pay session creation failed",{pollingCount:y,error:_?.code,resourceId:l}),_.code==="FAILURE_RESPONSE_FROM_WALLET_PROVIDER")throw new Vt(`ApplePaySession Query error: fail to create apple pay session with ${_.code}`);if(_.code==="NO_PENDING_TASK"){r.counter({name:"apple_pay_no_pending_task_error",value:1,attributes:{pollingCount:y,sourceId:t,isPrefetch:i}}),r.log("apple_pay_api_session_cancelled","Apply Pay session has no pending task",{pollingCount:y,sourceId:t,isPrefetch:i}),r.leaveErrorBreadcrumb("[ApplePay] session creation failed with NO_PENDING_TASK",{pollingCount:y,sourceId:t,isPrefetch:i});return}if(i)return;throw new z(`ApplePaySession Query error: fail to create apple pay session with ${_.code}`,{groupingHash:"ApplePayAPIError::QueryError::FailToCreateSession"})}case"PendingTask":{if(!p){const P=performance.now()-h,v=ta-P;v>0&&await Ut(v)}if(p=_.taskId,y++,y>=ea)throw r.log("apple_pay_api_session_cancelled","Apple Pay polling session reached maximum amount of polls",{pollingCount:y,flightDelay:performance.now()-h}),new Oe("ApplePaySession Query error: reached maximum amount of polls");if(y<=mn)break;await Ut(_.pollDelay);break}default:Yn(_)}}while(!0)}catch(h){if(h instanceof en||h instanceof Vt)return r.counter({name:"apple_pay_session_query_error",value:1,attributes:{reason:h.name}}),new _n(`${h.name}: ${h.message}`);throw h}},oa={EG:"EG",AE:"AE"};
1function $e({subtotal:e,duties:t,taxes:n,deliveryNext:o,discountLines:a,paymentLines:r,tipLines:i,shopPromotion:s,lineItemsLabels:l,deliveryOptionGroupTypeLabels:m,deliveryMethodTitlePrefixes:d,formattedRecurringTotals:p,formattedRecurringTotalTooltip:y,merchandiseLines:g}){const h=[];g?.lines&&g.lines.forEach(c=>{h.push({label:go(c),amount:X(c.totalPrice.amount)})});const E=e===void 0?[]:[{label:l.subtotal,amount:e?X(e.amount):void 0}],_=aa({deliveryNext:o,deliveryOptionGroupTypeLabels:m,deliveryMethodTitlePrefixes:d}),P=t&&t?.status==="available_total"&&t?.totalDuty.amount!==0?[{label:l.duties,amount:X(t.totalDuty.amount)}]:[],v=n&&n.status==="available_total"&&n.totalTax.amount!==0?[{label:l.taxes,amount:X(n.totalTax.amount)}]:[],I=a&&a.lines.map(c=>{if(Vn(c)){const w=c.amount?.amount;if(w)return{label:c.title,amount:lt(X(w))}}}).filter(c=>c!==void 0)||[],f={SHOP_DISCOUNT_OFFER:l.shopDiscountOffer,SHOP_CASH_BALANCE:l.shopCashBalance,SHOP_PROMOTION:l.shopPromotion},R=new Map(s?.status==="filled"?s.promotions.map(({promotionId:c,type:w})=>[c,w]):[]),C=r?.lines.filter(c=>c.method.type==="redeemable"&&c.method.redemptionSource==="SHOP_CASH").flatMap(c=>c.method.redemptionContent?.details??[]).flatMap(c=>{const w=c.promotionType??(c.redemptionId==null?void 0:R.get(c.redemptionId)),H=c.redemptionType==="SHOP_PROMOTION"&&w==="DOORBUSTER"&&l.flashDeal?l.flashDeal:f[c.redemptionType],T=Number(c.destinationAmount.amount);return H&&T!==0?[{label:H,amount:lt(X(T))}]:[]})??[],O=r?.lines.filter(c=>c.method.type==="giftCard").map(c=>c.cost?{label:l.giftCards,amount:lt(X(c.cost.amount))}:void 0).filter(c=>c!==void 0)||[],L=i&&i[0],A=L&&L.amount.amount>0?[{label:l.tip,amount:X(L.amount.amount)}]:[],u=p?p.map(c=>({label:c,amount:"0.00",type:"pending"})):[],b=u.length>0&&y?[{label:y,amount:"0.00",type:"pending"}]:[];return[...h,...E,..._,...P,...v,...I,...C,...O,...A,...u,...b]}function aa({deliveryNext:e,deliveryOptionGroupTypeLabels:t,deliveryMethodTitlePrefixes:n}){const o=rn(e);return o?o.map(({totalCost:a})=>({label:n.SHIPPING,amount:X(a.amount)})):qn(e).map(({line:a,method:r},i,s)=>({label:ra(a,r,s.length===1,t,n),amount:X(r.cost.amount)}))}function ra(e,t,n,o,a){const r=a[t.methodType];return n?r:`${r} (${o[e.type]})`}function En({deliveryMethodTitlePrefixes:e,connectTwoShippingTitles:t,deliveryNext:n}){const o=rn(n);if(o)return o.map(({totalTitle:s,totalCostAfterDiscounts:l,deliveryMethodHandles:m,deliveryPromisePresentmentTitle:d})=>({label:s,amount:X(l.amount),detail:d?.short??"",identifier:JSON.stringify(m)}));const a=Hn(n).filter(xn).map(zo),r=Wo(a).filter(s=>s.length>0);return ia(n,r).map(s=>({label:la(s,e,t),amount:ca(s),detail:da(s,t),identifier:vo(s)}))}function ia(e,t){if(!e||e.status!=="filled"||!Gn(e))return t;const n=new Set(e.lines.reduce((a,r)=>(r.status==="available"&&r.selectedDeliveryMethodHandle&&a.add(r.selectedDeliveryMethodHandle),a),new Set)),o=t.find(a=>a.every(r=>n.has(r.handle)));return o?[o,...t.filter(a=>a!==o)]:t}const sa=", ";function gn(e,t){const n=e.values(),o=n.next();if(o.done)return"";const a=n.next();if(a.done)return o.value;let r=o.value,i=a.value;for(const s of n)r+=`${sa}${i}`,i=s;return t(r,i)}function la(e,t,n){const o=e.find(l=>l.deliveryLine.type==="ONE_TIME_PURCHASE");let a="";o&&(a=o.methodType==="PICK_UP"?t[o.methodType]:o.title);const r=e.find(l=>l.deliveryLine.type==="SUBSCRIPTION");let i="";if(r){if(r.methodType==="PICK_UP"||r.methodType==="LOCAL")return r.title;i=r.title,a=o?.title??""}const s=[...new Set([a,i])];return gn(s.filter(Boolean),n)}function ca(e){return X(e.reduce((t,n)=>t+n.costAfterDiscounts.amount,0))}function pa(e,t){return e.add(t),e}function da(e,t){return gn([...e.map(n=>{const{methodType:o,pickupLocation:a,deliveryPromisePresentmentTitle:r,description:i}=n;return o==="PICK_UP"||o==="PICKUP_POINT"?ya(a?.address)??"":r?r.short:i||""}).reduce(pa,new Set)],t)}function Je(e,t){return{label:e,amount:X(t.amount)}}function ua({phoneRequired:e,emailRequired:t,shippingRequired:n}){const o=["name","postalAddress"],a=[...e?["phone"]:[],...t?["email"]:[]];return{requiredShippingContactFields:n?[...o,...a]:a,requiredBillingContactFields:o}}function we(e){const t=e.countryCode?.toUpperCase(),n={firstName:e.givenName||void 0,lastName:e.familyName||void 0,address1:e?.addressLines?.[0],address2:e?.addressLines?.[1]||void 0,city:e.locality||void 0,postalCode:e.postalCode||void 0,zoneCode:e.administrativeArea||e.subLocality||void 0,countryCode:ee(e.countryCode),phone:e.phoneNumber||void 0};return n.countryCode==="HK"&&(n.postalCode=void 0,n.zoneCode=e.postalCode),n.countryCode&&an.includes(n.countryCode)&&(n.zoneCode=n.countryCode,n.countryCode="US"),t&&Object.keys(oa).includes(t)&&(n.zoneCode=e.locality||void 0,n.city=e.administrativeArea||e.subLocality||void 0),n.lastName||(n.lastName=n.firstName),n}function ee(e){if(!e)return"ZZ";const t=e.toUpperCase();if(Un(t))return t;const o={UK:"GB",JA:"JP"}[t];return o||(an.includes(t)?t:"ZZ")}function ya(e){if(e){const{address1:t="",address2:n="",city:o="",company:a="",zoneCode:r="",countryCode:i=""}
1=e,s=[t,n].filter(Boolean).join(" ");return[a,s,o,r,i].filter(Boolean).join(", ")}}function vn({embed:e,isCrossOriginIframeEnabled:t}){if(t&&!(typeof window>"u"||window.self===window.top))return e?.client?.embedderHostname}function ha(e){const t={brand:"",lastFourDigits:""};if(!e)return t;const n=e.split(" ");if(n.length!==2)return t;const[o,a]=n;if(o===void 0||a===void 0)return t;for(const r of o.toLowerCase())if(r<"a"||r>"z")return t;return Number.isNaN(Number(a))?t:{brand:o,lastFourDigits:a}}const Aa=new Set(["HUF","RSD"]);function ma(e){return Aa.has(e)}function Ke(e){return e!==void 0&&ma(e)}function fn(e){const t=Number(e);return Number.isFinite(t)?Math.ceil(Number(t.toFixed(2))).toFixed(2):e}function ze(e){return{...e,amount:fn(e.amount)}}function Sn(e){return{...e,amount:fn(e.amount)}}function _a(e){const{lineItems:t,shippingMethods:n}=e;return{...e,total:ze(e.total),...t&&{lineItems:t.map(ze)},...n&&{shippingMethods:n.map(Sn)}}}function Pt(e){const{newLineItems:t,newShippingMethods:n}=e;return{...e,newTotal:ze(e.newTotal),...t&&{newLineItems:t.map(ze)},...n&&{newShippingMethods:n.map(Sn)}}}function Xe(){const{i18n:e,shop:t}=G(),{name:n}=t,o=e.translate("order_summary.recurring_total_tooltip"),a=t.hasFlagEnabled(zn),r=Ee(()=>({total:n,subtotal:e.translate("order_summary.subtotal_label"),duties:e.translate("order_summary.duties_label"),taxes:e.translate("order_summary.estimated_taxes_label"),shopDiscountOffer:e.translate("order_summary.exclusive_deal"),shopCashBalance:e.translate("order_summary.shop_cash_title"),shopPromotion:e.translate("order_summary.shop_promotion"),...a&&{flashDeal:e.translate("order_summary.flash_deal")},giftCards:e.translate("order_summary.gift_card_label"),tip:e.translate("order_summary.tip_label")}),[n,e,a]),i=Ee(()=>({ONE_TIME_PURCHASE:e.translate("shipping.shipping_method_one_time_purchase_group_title"),SUBSCRIPTION:e.translate("shipping.shipping_method_subscription_group_title")}),[e]),s=Ee(()=>({SHIPPING:e.translate("wallets.shipping_line_label"),LOCAL:e.translate("shipping.local_delivery"),PICK_UP:e.translate("delivery_options.pick_up"),PICKUP_POINT:e.translate("delivery_options.pickup_point_method_definition"),RETAIL:e.translate("delivery_options.retail_method_definition"),NONE:e.translate("delivery_options.none_method_definition")}),[e]),l=Ee(()=>(m,d)=>e.translate("wallets.connect_shipping_methods",{method1:m,method2:d}),[e]);return Ee(()=>({formattedRecurringTotalTooltip:o,lineItemsLabels:r,deliveryOptionGroupTypeLabels:i,deliveryMethodTitlePrefixes:s,connectTwoShippingTitles:l}),[o,r,i,s,l])}function Pa(){const{checkout:e,observability:t}=G(),n=e.configuration.addressSettings.nonBillingAddressSettings.value,o=po(),a=ve(),r=n.isRequired("phone",{countryCode:ee(a.buyerIdentity.value?.countryCode)}),i=dn(),{value:s}=a.deliveryNext,l=We(),m=fe(),d=Ze(),{paymentDue:p,recurringTotals:y,...g}=Le(m),h=Xe(),{deliveryMethodTitlePrefixes:E,connectTwoShippingTitles:_}=h,P=a.availableDeliveryAddresses?.value,v=a.mustSelectProvidedAddress?.value,{inMemoryApplePayParts:{asPaymentMethod:I,requirePhoneOnNextAttempt:f,requireBillingPhoneOnNextAttempt:R}}=te();return Q((C,O)=>{const L=I.value,A=f.value||R.value,u=!!l.shopPayArtifact.value?.optIn,b=!!l.email.value;A&&t.counter({name:"apple_pay_phone_retry_requested",value:1,attributes:{addressSettingsPhoneRequired:r,asPaymentMethod:L}});const c=Qe({availableDeliveryAddresses:P,mustSelectProvidedAddress:v}),w=L||c,{requiredShippingContactFields:N,requiredBillingContactFields:H}=ua({phoneRequired:Ea({asPaymentMethod:L,phoneRequired:r,shouldRequestPhoneOnRetry:A,shopPayOptInExists:u}),emailRequired:ga({asPaymentMethod:L,emailRequired:o.value,shopPayOptInExists:u,proposedEmailExists:b}),shippingRequired:w?!1:i.value}),T=Je(h.lineItemsLabels.total,p),j=$e({...g,formattedRecurringTotals:d(y),...h}),U=w?[]:En({deliveryMethodTitlePrefixes:E,connectTwoShippingTitles:_,deliveryNext:s}),oe={total:T,currencyCode:p.currencyCode,countryCode:O,lineItems:j,shippingMethods:U,shippingType:"shipping",merchantCapabilities:["supports3DS"],supportedNetworks:C,requiredShippingContactFields:N,requiredBillingContactFields:H};return Ke(p.currencyCode)?_a(oe):oe},[I,f,R,_,E,s,o,P,d,h,v,g,p,r,y,i,t,l])}const Ea=({asPaymentMethod:e,phoneRequired:t,shouldRequestPhoneOnRetry:n,shopPayOptInExists:o})=>e?o:t||n,ga=({asPaymentMethod:e,emailRequired:t,shopPayOptInExists:n,proposedEmailExists:o})=>e?!o&&n:t;function va(e){const t="apple-pay-gateway.apple.com/paymentservices/startSession";return e==="CN"?`https://cn-${t}`:`https://${t}`}function fa(){const e=Me(D.ApplePay),{trackComplete:t}=je(D.ApplePay),n=ut(),{inMemoryApplePayParts:o}=te(),{checkout:a,observability:r,shop:i}=G(),s=un();return Q((l,m)=>{l.abort(),o.prefetchPaymentSession.value=void 0;const d=m.value,p=o.asPaymentMethod.value,y=p?W.PaymentMethod:W.Express;K.remove("apple-pay-sheet-load"),K.exists("apple-pay-authorization")&&t({result:"failed",durationMs:K.end("apple-pay-authorization"),walletType:y}),r.counter({name:"apple_pay_on_cancel",value:1,attributes:{completion_in_progress:d.toString(),wallet_type:y}}),r.counter({name:"wallet_sheet_cancelled",value:1,attributes:{instrument:D.ApplePay}}),r.log("apple_pay_use_on_cancel_sheet_cancelled","Apple Pay sheet cancelled",{completionInProgress:d,walletType:y}),o.requirePhoneOnNextAttempt.value&&r.counter({name:"apple_pay_cancelled_after_phone_retry",value:1,attributes:{asPaymentMethod:p}});const g=Wn(i),h=i.hasFlagEnabled(sn),E=o.subscriptionReviewTransition.value!==void 0&&Qo({applePaySubscriptionsDecelerationActive:g,applePayThreePageVaultedReviewEnabled:h,isOnePageCheckout:a.configuration.layout.isOnePage.value}),_=s.value||E;if(d)r.log("apple_pay_on_cancel_completion_in_progress","Apple Pay cancelled during completion - activeSession NOT cleared, expecting completion flow to handle cleanup",{asPaymentMethod:p,inRecoveryFlow:_}),o.paymentSheetError.value={type:"payment_cancelled_while_processing"};else{if(r.log("apple_pay_on_cancel_normal_path","Apple Pay cancelled - clearing activeSession",{asPaymentMethod:p,inRecoveryFlow:_}),a.wallets.activeSession.value?.wallet==="APPLE_PAY"&&a.wallets.clearActiveSession({invokingWallet:"APPLE_PAY"}),_)return;n()}e(ne.Cancelled)},[n,o.asPaymentMethod,o.paymentSheetError,o.subscriptionReviewTransition,o.requirePhoneOnNextAttempt,o.prefetchPaymentSession,t,e,r,i,a,s])}function Cn(){const{observability:e}
1=G(),t=An(D.ApplePay),{trackComplete:n}=je(D.ApplePay);return Q(({status:o,walletType:a,endsAuthorization:r=!0})=>{if(e.counter({name:"apple_pay_payment_status",value:1,attributes:{status:o,wallet_type:a}}),t(o,a),o===ne.Attempt)return;if(!r){K.remove("apple-pay-authorization");return}const i=o===ne.Success?"success":"failed";K.endAndRun("apple-pay-authorization",s=>{n({result:i,durationMs:s,walletType:a,attributes:{walletType:a}}),e.log("apple_pay_payment_status_updated","Apple Pay payment authorization status update received",{result:i,status:o,walletType:a})})},[e,t,n])}function Et(){const e=ut(),t=Cn(),{inMemoryApplePayParts:{asPaymentMethod:n}}=te();return Q(()=>{const o=n.value?W.PaymentMethod:W.Express;e(),t({status:ne.Failure,walletType:o})},[t,e,n])}function Se(){const e=Me(D.ApplePay),t=An(D.ApplePay),{trackComplete:n}=je(D.ApplePay),{checkout:{wallets:o},observability:a}=G(),{inMemoryApplePayParts:r}=te(),i=ut();return Q(({session:s,isProcessing:l=!1,isMessagingHandledElsewhere:m=!1,error:d,isAborted:p})=>{if(d instanceof At)return;K.remove("apple-pay-sheet-load");const y=r.asPaymentMethod.value?W.PaymentMethod:W.Express;a.counter({name:"apple_pay_session_terminated",value:1,attributes:{error_type:d.name,wallet_type:y}}),a.log("apple_pay_terminate_session_session","Apple Pay session terminated",{wallet_type:y,error_type:d.name,error_message:d.message,error_cause:d.cause,error_stack:d.stack}),K.exists("apple-pay-authorization")?(t(ne.Failure,y),n({result:"failed",durationMs:K.end("apple-pay-authorization"),walletType:y})):(e(ne.Failure,y),a.counter({name:"wallet_sheet_failed",value:1,attributes:{instrument:D.ApplePay}})),!l&&!m&&(r.paymentSheetError.value={type:"session_terminated"});const{actionable:g}=jo(d);if(d instanceof Oe?a.leaveErrorBreadcrumb(`IgnoredApplePayAPIError: ${d.message}`):g?a.error(d,{severity:"error",errorClass:qe.Api}):a.leaveErrorBreadcrumb("[ApplePay] Unactionable error",{error:d}),o.setHasActiveApplePaySubscriptionReview(!1),!p&&o.activeSession.value?.wallet==="APPLE_PAY"?o.clearActiveSession({invokingWallet:"APPLE_PAY"}):a.leaveErrorBreadcrumb("[ApplePay] clearActiveSession skipped",{activeSession:o.activeSession.value?.wallet,isAborted:p}),s)try{s.abort()}catch{}finally{i()}},[r.asPaymentMethod,r.paymentSheetError,i,a,t,n,e,o])}const Sa=["BR","KW","PA","PE","PH"];function et(e){return e.hasFlagEnabled(Qn)}function tt(e,t){if(!t)return{};const n={district:void 0,line2:void 0,subdistrict:void 0},o=e.countryCode?.toUpperCase();return!o||!Sa.includes(o)||(e.subLocality&&(n.district=e.subLocality),e.addressLines?.[1]&&(n.line2=e.addressLines[1]),e.subAdministrativeArea&&(n.subdistrict=e.subAdministrativeArea)),n}const Ca=[He.InvalidExtensionState,He.InvalidCaptcha,He.SubmittedForCompletion];class Ta extends fo{constructor(t,n,o,a){super(),this.observability=t,this.translations=n,this.inMemoryApplePayParts=o,this.persistedApplePaySignal=a}get negotiationResultMapper(){return new Ht({success:({result:t,violationActions:n,defaultMapper:o})=>{if(!("errors"in t))return o();const{firstPaymentSheetAction:r}=this.getMergedPaymentSheetAction({resultViolations:t.errors,violationActions:n});return r||o()},invalid:({result:t})=>(this.notifyInvalidResult(t,"negotiation"),this.generateAbortAction("exceptional_negotiation_status")),stale:()=>(this.observability.error(new z("Intercepted negotiation returned stale",{groupingHash:"ApplePayAPIError::InterceptedNegotiationReturned::Stale"}),{severity:"error"}),this.generateAbortAction("exceptional_negotiation_status")),denied:()=>({action:"abort"}),throttled:()=>({action:"abort"}),tooManyRequests:()=>({action:"abort"})},()=>this.mapUnhandledNegotiation(),t=>this.getNegotiationViolationActions(t))}get completionResultMapper(){return new Ht({success:({result:t,defaultMapper:n})=>"receipt"in t?{action:"submit"}:n(),failed:({result:t})=>(this.observability.log("apple_pay_payment_sheet_action_generator_failed","Apple Pay completion failed",{reason:t.reason}),this.generateAbortAction("exceptional_completion_status")),rejected:({result:t,violationActions:n,options:o})=>
1{this.getUnhandledErrors(t.violations,n).forEach(s=>{this.observability.error(new z(`violation not handled: ${s.code}`,{groupingHash:`ApplePayAPIError::ViolationNotHandled::${s.code}`}),{severity:"error",errorClass:qe.Api})});const{generatePrioritizedPaymentSheetAction:a}=this.getMergedPaymentSheetAction({resultViolations:t.violations,violationActions:n}),{action:r,violationCode:i}=a();return i&&this.observability.counter({name:"wallet_action_generator_handled_error",value:1,attributes:{violationCode:i,WalletName:D.ApplePay,action:r?.action??"abort",asPaymentMethod:!!o?.asPaymentMethod}}),r?(r.action==="decelerate"&&(this.persistedApplePaySignal.value={...this.persistedApplePaySignal.value,recoveryViolation:i},this.observability.log("apple_pay_authorization_decelerated","Apple Pay authorization decelerated during payment completion",{asPaymentMethod:!!o?.asPaymentMethod,violationCode:i,violations:t.violations.map(s=>s.code).join(",")})),r):{action:"abort"}},invalid:({result:t,options:n})=>{const a=!!n?.applePayRecoveryFlowEnabled&&t.reasons.length>0&&t.reasons.every(i=>Zn.includes(i)),r=a?"decelerate":"abort";if(this.notifyInvalidResult(t,"completion",r),a){const i=t.reasons.at(0)??"unknown";return this.persistedApplePaySignal.value={...this.persistedApplePaySignal.value,recoveryViolation:i},this.observability.counter({name:"wallet_action_generator_handled_error",value:1,attributes:{violationCode:i,WalletName:D.ApplePay,action:"decelerate",asPaymentMethod:!!n?.asPaymentMethod}}),this.observability.log("apple_pay_authorization_decelerated","Apple Pay authorization decelerated during payment completion",{asPaymentMethod:!!n?.asPaymentMethod,violationCode:i,violations:t.reasons.join(",")}),this.generateDecelerateAction()}return{action:r,effects:[()=>{this.inMemoryApplePayParts.paymentSheetError.value={type:t.reasons.includes(He.InvalidCaptcha)?"captcha_required":"exceptional_completion_status"}}]}},stale:()=>(this.observability.error(new z("Intercepted negotiation returned stale",{groupingHash:"ApplePayAPIError::InterceptedNegotiationReturned::Stale"}),{severity:"error"}),this.generateAbortAction("exceptional_completion_status")),fetch_failed:()=>this.generateAbortAction("exceptional_completion_status"),alreadyCompleted:()=>({action:"abort"}),denied:()=>({action:"abort"}),throttled:()=>({action:"abort"}),tooManyRequests:()=>({action:"abort"})},t=>this.mapUnhandledCompletion(t),(t,n)=>this.getCompletionViolationActions(t,n))}validateBilling(t){const{billingContact:n}=t;return n?{shouldPersist:!0}:{shouldPersist:!1,paymentSheetAction:{action:"abort"}}}validateShipping(t,n,o,a,r){const{shippingContact:i}=t;if(!n)return{shouldPersist:!1};if(!i)return{shouldPersist:!1,paymentSheetAction:{action:"abort"}};const s=we(i),l=[];return o&&!s.address2&&l.push(new ApplePayError("shippingContactInvalid","addressLines",this.translations.addressLine2Blank)),a&&!s.firstName&&l.push(new ApplePayError("shippingContactInvalid","name",this.translations.firstNameBlank)),r&&!s.phone&&l.push(new ApplePayError("shippingContactInvalid","phoneNumber",this.translations.phoneBlank)),l.length>0?{shouldPersist:!1,paymentSheetAction:{action:"show_error",errors:l}}:{shouldPersist:!0}}getCompletionViolationActions(t,n){return[{violations:[...Yt,"MERCHANDISE_NOT_APPLICABLE",...So,...Bt,...Co,xt,qt],generateAction:()=>({action:"abort"})},{violations:To,generateAction:()=>this.generateAbortAction("session_terminated")},{violations:Gt,generateAction:()=>this.generateAbortAction("shipping_options_changed")},{violations:No,generateAction:()=>V("emailAddress",this.translations.emailInvalidError)},{violations:["BUYER_IDENTITY_CONTACT_INFO_DOES_NOT_MATCH_CUSTOMER_PROFILE"],generateAction:()=>this.generateAbortAction("unhandled_completion_status")},{violations:Io,generateAction:()=>V("phoneNumber",this.translations.phoneInvalidError)},{violations:["BUYER_IDENTITY_MISSING_CONTACT_METHOD","BUYER_IDENTITY_EMAIL_REQUIRED"],generateAction:()=>V("emailAddress",this.translations.contactInfoBlank)},...this.getCompletionDeceleratedViolationActions(t),{violations:[...Ro],generateAction:()=>V("phoneNumber",this.translations.phoneInvalidError)},{violations:["PAYMENTS_PHONE_NUMBER_DOES_NOT_MATCH_EXPECTED_PATTERN"],generateAction:()=>q("phoneNumber",this.translations.phoneInvalidError)},...this.getCompletionShippingAddressViolationActions(t,n),{violations:[...bo,"PAYMENTS_METHOD_REQUIRED"],generateAction:()=>({action:"show_error",errors:[new ApplePayError("unknown",void 0,void 0)]})},...this.getCompletionBillingAddressViolationActions(t)]}getCompletionBillingAddressViolationActions(t){return t?.options?.applePayRecoveryFlowEnabled?[{violations:Do,generateAction:()=>this.generateDecelerateAction()}]:[{violations:Oo,generateAction:()=>q("name",this.translations.nameContainsEmojisError)},{violations:Lo,generateAction:()=>q("name",this.translations.firstNameTooLongError)},{violations:["PAYMENTS_ADDRESS1_CONTAINS_HTML_TAGS","PAYMENTS_ADDRESS1_CONTAINS_EMOJIS","PAYMENTS_ADDRESS1_CONTAINS_MATHEMATICAL_SYMBOLS","PAYMENTS_ADDRESS2_CONTAINS_EMOJIS","PAYMENTS_ADDRESS2_CONTAINS_MATHEMATICAL_SYMBOLS","PAYMENTS_COMPANY_CONTAINS_EMOJIS",...jn],generateAction:()=>q("addressLines",this.translations.invalidBillingAddressError)},{violations:["PAYMENTS_LAST_NAME_CONTAINS_HTML_TAGS","PAYMENTS_LAST_NAME_CONTAINS_URL"],generateAction:()=>q("name",this.translations.invalidBillingAddressError)},{violations:Mo,generateAction:()=>q("name",this.translations.lastNameTooLongError)},{violations:["PAYMENTS_ADDRESS1_TOO_LONG","PAYMENTS_ADDRESS2_TOO_LONG"],generateAction:()=>q("addressLines",this.translations.addressLineTooLongError)},{violations:[zt],generateAction:()=>({action:"show_error",errors:[this.createApplePayZoneError(this.translations.zoneNotFoundError,"billingContactInvalid",t?.billingCountryCode)]})},{violations:["PAYMENTS_INVALID_POSTAL_CODE_FOR_COUNTRY","PAYMENTS_INVALID_POSTAL_CODE_FOR_ZONE"],generateAction:()=>q("postalCode",this.translations.postalCodeInvalidError)},{violations:wo,generateAction:()=>q("postalCode",this.translations.postalCodeEmojiError)},{violations:Fo,generateAction:()=>q("postalCode",this.translations.postalCodeNotSupportedError)},{violations:["PAYMENTS_FIRST_NAME_REQUIRED"],generateAction:()=>q("name",this.translations.firstNameBlank)},{violations:["PAYMENTS_LAST_NAME_REQUIRED"],generateAction:()=>q("name",this.translations.lastNameBlank)},{violations:["PAYMENTS_ADDRESS1_REQUIRED"],generateAction:()=>q("addressLines",this.translations.addressLine1Blank)},{violations:["PAYMENTS_CITY_REQUIRED"],generateAction:()=>q("locality",this.translations.cityBlank)},{violations:["PAYMENTS_CITY_TOO_LONG","PAYMENTS_CITY_CONTAINS_MATHEMATICAL_SYMBOLS","PAYMENTS_CITY_CONTAINS_EMOJIS","PAYMENTS_CITY_CONTAINS_HTML_TAGS"],generateAction:()=>q("locality",this.translations.invalidBillingAddressError)},{violations:["PAYMENTS_POSTAL_CODE_REQUIRED"],generateAction:()=>q("postalCode",this.translations.postalCodeBlank)},{violations:["PAYMENTS_COUNTRY_REQUIRED"],generateAction:()=>q("country",this.translations.countryBlank)},{violations:["PAYMENTS_ZONE_REQUIRED_FOR_COUNTRY"],generateAction:()=>({action:"show_error",errors:[this.createApplePayZoneError(this.translations.deliveryZoneBlank,"billingContactInvalid",t?.billingCountryCode)]})},{violations:["PAYMENTS_SHIPPING_MUST_MATCH_BILLING"],generateAction:()=>q("postalAddress",this.translations.billingMustMatchShipping)},{violations:["PAYMENTS_PHONE_NUMBER_REQUIRED"],generateAction:()=>({action:"abort",effects:[()=>{this.inMemoryApplePayParts.paymentSheetError.value={type:"exceptional_completion_status"},this.inMemoryApplePayParts.requireBillingPhoneOnNextAttempt.value=!0}]})}]}getCompletionShippingAddressViolationActions(t,n){return t?.options?.applePayRecoveryFlowEnabled?[{violations:["DELIVERY_ZONE_NOT_FOUND","DELIVERY_COMPANY_REQUIRED",...Wt,...Yo],generateAction:()=>this.generateDecelerateAction()}]:[{violations:["DELIVERY_FIRST_NAME_REQUIRED"],generateAction:()=>V("name",this.translations.firstNameBlank)},{violations:["DELIVERY_LAST_NAME_REQUIRED"],generateAction:()=>V("name",this.translations.lastNameBlank)},{violations:["DELIVERY_ADDRESS1_REQUIRED"],generateAction:()=>V("addressLines",this.translations.addressLine1Blank)},{violations:["DELIVERY_ADDRESS2_REQUIRED"],generateAction:()=>V("addressLines",this.translations.addressLine2Blank)},{violations:["DELIVERY_CITY_REQUIRED"],generateAction:()=>V("locality",this.translations.cityBlank)},{violations:["DELIVERY_ZONE_REQUIRED_FOR_COUNTRY"],generateAction:()=>({action:"show_error",errors:[this.createApplePayZoneError(this.translations.deliveryZoneBlank,"shippingContactInvalid",t?.shippingCountryCode)]})},{violations:["DELIVERY_COUNTRY_REQUIRED"],generateAction:()=>V("country",this.translations.countryBlank)},{violations:["DELIVERY_POSTAL_CODE_REQUIRED"],generateAction:()=>V("postalCode",this.translations.postalCodeBlank)},{violations:["DELIVERY_ZONE_NOT_FOUND"],generateAction:()=>{const{shippingZone:a,shippingCountry:r}=ko(n);return{action:"show_error",errors:[this.createApplePayZoneError(this.translations.zoneNotFoundError,"shippingContactInvalid",t?.shippingCountryCode)],effects:[()=>{this.observability.log("apple_pay_payment_completion_failed","Delivery zone issue",{reason:"DELIVERY_ZONE_NOT_FOUND",shippingZone:a,shippingCountry:r})}]}}},{violations:["DELIVERY_INVALID_POSTAL_CODE_FOR_COUNTRY","DELIVERY_INVALID_POSTAL_CODE_FOR_ZONE","DELIVERY_POSTAL_CODE_NOT_SUPPORTED"],generateAction:()=>V("postalCode",this.translations.postalCodeInvalidError)},{violations:["DELIVERY_LAST_NAME_CONTAINS_HTML_TAGS","DELIVERY_FIRST_NAME_CONTAINS_HTML_TAGS","DELIVERY_LAST_NAME_CONTAINS_URL","DELIVERY_FIRST_NAME_CONTAINS_URL"],generateAction:()=>V("name",this.translations.invalidShippingAddressError)},{violations:["DELIVERY_ADDRESS1_CONTAINS_HTML_TAGS","DELIVERY_ADDRESS2_CONTAINS_HTML_TAGS","DELIVERY_ADDRESS1_CONTAINS_EMOJIS","DELIVERY_ADDRESS2_CONTAINS_EMOJIS","DELIVERY_ADDRESS2_CONTAINS_MATHEMATICAL_SYMBOLS",...$n],generateAction:()=>V("addressLines",this.translations.invalidShippingAddressError)},{violations:["DELIVERY_CITY_CONTAINS_HTML_TAGS"],generateAction:()=>V("locality",this.translations.invalidShippingAddressError)},{violations:["DELIVERY_ADDRESS1_TOO_LONG"],generateAction:()=>V("addressLines",this.translations.addressLineTooLongError)},{violations:["DELIVERY_FIRST_NAME_TOO_LONG"],generateAction:()=>V("name",this.translations.firstNameTooLongError)},{violations:["DELIVERY_LAST_NAME_TOO_LONG"],generateAction:()=>V("name",this.translations.lastNameTooLongError)},{violations:Bo,generateAction:()=>V("name",this.translations.nameContainsEmojisError)},{violations:Wt,generateAction:()=>({action:"abort",effects:[()=>{this.inMemoryApplePayParts.paymentSheetError.value={type:"exceptional_completion_status"},this.inMemoryApplePayParts.requirePhoneOnNextAttempt.value=!0}]})}]}getCompletionDeceleratedViolationActions(t){return t?.options?.applePayRecoveryFlowEnabled?[{violations:Qt,generateAction:()=>this.generateDecelerateAction({paymentSheetError:{type:"new_tax_must_be_accepted",tone:"warning"}})},{violations:[...ln,xe,...Zt,...jt,...kt,...$t,"DELIVERY_WRONG_NUMBER_OF_DELIVERY_LINES",...Jt,...Kt],generateAction:()=>this.generateDecelerateAction()}]:this.getCompletionAbortViolationActions()}getCompletionAbortViolationActions(){return[{violations:[...Qt,xe,...Zt,...kt,"DELIVERY_COMPANY_REQUIRED"],generateAction:()=>({action:"abort"})},{violations:jt,generateAction:()=>this.generateAbortAction("session_terminated")},{violations:$t,generateAction:()=>this.generateAbortAction("unusable_partial_address")},{violations:["DELIVERY_WRONG_NUMBER_OF_DELIVERY_LINES",...Jt],generateAction:()=>this.generateAbortAction("unhandled_completion_status")},{violations:Kt,generateAction:()=>this.generateAbortAction("ineligible_discount")}]}mapUnhandledCompletion(t){return this.observability.error(new z(`Intercepted completion returned unhandled status: ${t.status}`,{groupingHash:`ApplePayAPIError::InterceptedCompletionReturned::Unhandled::${t.status}`}),{severity:"error",errorClass:qe.Api}),this.generateAbortAction("unhandled_completion_status")}getNegotiationViolationActions(t){return[{violations:["MERCHANDISE_CART_AND_CURRENCY_UPDATED_BASED_ON_COUNTRY","MERCHANDISE_CART_UPDATED_BASED_ON_COUNTRY",xe,...Yt,...Bt,xt,qt],generateAction:()=>({action:"abort"})},{violations:Gt,generateAction:()=>({action:"update",errors:[new ApplePayError("addressUnserviceable")]})},...this.getNegotiationShippingAddressViolationActions(t),{violations:[zt],generateAction:()=>({action:"update",errors:[this.createApplePayZoneError(this.translations.zoneNotFoundError,"billingContactInvalid",t?.billingCountryCode)]})},{violations:["PAYMENTS_INVALID_POSTAL_CODE_FOR_COUNTRY","PAYMENTS_INVALID_POSTAL_CODE_FOR_ZONE"],generateAction:()=>({action:"update",errors:[new ApplePayError("billingContactInvalid","postalCode",this.translations.postalCodeInvalidError)]})}]}getNegotiationShippingAddressViolationActions(t){return t?.options?.applePayRecoveryFlowEnabled?[{violations:[...Xt,"DELIVERY_INVALID_POSTAL_CODE_FOR_COUNTRY","DELIVERY_INVALID_POSTAL_CODE_FOR_ZONE"],generateAction:()=>({action:"no-op"})}]:[{violations:Xt,generateAction:()=>({action:"update",errors:[this.createApplePayZoneError(this.translations.zoneNotFoundError,"shippingContactInvalid",t?.shippingCountryCode)]})},{violations:["DELIVERY_INVALID_POSTAL_CODE_FOR_COUNTRY"],generateAction:()=>this.createInvalidPostalCodeViolationAction(t?.shippingCountryCode)},{violations:["DELIVERY_INVALID_POSTAL_CODE_FOR_ZONE"],generateAction:()=>({action:"update",errors:[new ApplePayError("shippingContactInvalid","postalCode",this.translations.postalCodeInvalidError)]})}]}createInvalidPostalCodeViolationAction(t){return t==="CA"||t==="GB"?{action:"no-op"}:{action:"update",errors:[new ApplePayError("shippingContactInvalid","postalCode",this.translations.postalCodeInvalidError)]}}mapUnhandledNegotiation(){return{action:"update",errors:[]}}createApplePayZoneError(t,n,o){const a=o==="AE"?"subLocality":"administrativeArea";return new ApplePayError(n,a,o==="AE"&&t===this.translations.zoneNotFoundError?this.translations.emirateNotFoundError:t)}generateAbortAction(t){return{action:"abort",effects:[()=>{this.inMemoryApplePayParts.paymentSheetError.value={type:t}}]}}generateDecelerateAction({paymentSheetError:t={type:"recovery_notice"}}={}){return{action:"decelerate",effects:[()=>{this.inMemoryApplePayParts.paymentSheetError.value=t}]}}
1notifyInvalidResult(t,n,o){const{expectedReasons:a,unexpectedReasons:r}=[...new Set(t.reasons)].reduce((i,s)=>(Ca.includes(s)?i.expectedReasons.push(s):i.unexpectedReasons.push(s),i),{expectedReasons:[],unexpectedReasons:[]});a.length>0&&(this.observability.log("apple_pay_payment_sheet_action_generator_negotiation_rejected","wallet_rejected_negotiation",{wallet:"apple_pay",reason:"invalid",stage:n,expectedReasons:a.sort(),unexpectedReasons:r.sort(),action:o}),this.observability.counter({name:"wallet_rejected_negotiation",value:1,attributes:{wallet:"apple_pay",reason:"invalid",stage:n,expectedReasons:a.sort().join(","),hasUnexpectedReasons:!!r.length,action:o}}));for(const i of r.sort())this.observability.error(new z(`Intercepted ${n} returned invalid: ${i}`,{groupingHash:`ApplePayAPIError::InterceptedNegotiationReturned::Invalid::${i}`}),{severity:"error"})}}function q(e,t){return{action:"show_error",errors:[new ApplePayError("billingContactInvalid",e,t)]}}function V(e,t){return{action:"show_error",errors:[new ApplePayError("shippingContactInvalid",e,t)]}}function gt(){const{i18n:e,observability:t}=G(),{inMemoryApplePayParts:n,persistedApplePaySignal:o}=te(),a=Ee(()=>({postalCodeNotSupportedError:e.translate("wallets.errors.unsupported.postal_code"),billingMustMatchShipping:e.translate("wallets.errors.invalid.billing_must_match_shipping"),invalidShippingAddressError:e.translate("wallets.errors.invalid.shipping_address"),invalidBillingAddressError:e.translate("wallets.errors.invalid.billing_address"),firstNameTooLongError:e.translate("wallets.errors.formatting.first_name_too_long"),lastNameTooLongError:e.translate("wallets.errors.formatting.last_name_too_long"),nameContainsEmojisError:e.translate("wallets.errors.formatting.name_contains_emojis"),addressLineTooLongError:e.translate("wallets.errors.formatting.address_too_long"),postalCodeInvalidError:e.translate("wallets.errors.invalid.postal_code"),postalCodeEmojiError:e.translate("wallets.errors.formatting.postal_code_contains_emoji"),zoneNotFoundError:e.translate("wallets.errors.invalid.zone"),emirateNotFoundError:e.translate("wallets.errors.invalid.emirate"),emailInvalidError:e.translate("wallets.errors.invalid.email"),phoneInvalidError:e.translate("wallets.errors.invalid.phone"),firstNameBlank:e.translate("wallets.errors.missing.first_name"),lastNameBlank:e.translate("wallets.errors.missing.last_name"),addressLine1Blank:e.translate("wallets.errors.missing.address1"),addressLine2Blank:e.translate("wallets.errors.missing.address2"),cityBlank:e.translate("wallets.errors.missing.city"),postalCodeBlank:e.translate("wallets.errors.missing.zip"),countryBlank:e.translate("wallets.errors.missing.country"),deliveryZoneBlank:e.translate("wallets.errors.missing.province"),phoneBlank:e.translate("wallets.errors.missing.phone"),contactInfoBlank:e.translate("wallets.errors.missing.contact_info")}),[e]);return Q(()=>new Ta(t,a,n,o),[a,n,o,t])}function Na(){const e=gt();return Q((t,n)=>{const{completionResultMapper:o}=e();if(!o)throw new z("CompletionResultMapper not set up correctly",{groupingHash:"ApplePayAPIError::CompletionResultMapper"});return o.mapResultToPaymentSheetAction(t,n)},[e])}function Tn({canDecelerate:e,checkout:t}){return e.value&&Jn({checkout:t})}function Ia({canDecelerate:e}){const t=Kn(),{checkout:n,shop:o}=G();return on(()=>(o.hasFlagEnabled(Xn)||o.hasFlagEnabled(cn))&&Tn({canDecelerate:e,checkout:n})&&t.value)}function Ra({canDecelerate:e,asPaymentMethod:t}){const n=Ia({canDecelerate:e}),{checkout:o}=G(),a=uo();return on(()=>{const r=a!==null,i=Tn({canDecelerate:e,checkout:o});return t.value?{shouldDecelerate:!1,isABTestActive:r,isCaliforniaDeceleration:!1,hasSubscription:i}:n.value?{shouldDecelerate:!0,isABTestActive:r,isCaliforniaDeceleration:!0,hasSubscription:i}:r?eo(a)?{shouldDecelerate:i,isABTestActive:!0,isCaliforniaDeceleration:!1,hasSubscription:i}:{shouldDecelerate:!1,isABTestActive:!0,isCaliforniaDeceleration:!1,hasSubscription:i}:{shouldDecelerate:!1,isABTestActive:!1,isCaliforniaDeceleration:!1,hasSubscription:i}})}const ft=class ft extends to{};ft.type="wallet:address-replace";let pt=ft;const ba="Apple Pay active session error";function se({methodName:e,abortSignal:t,wallets:n,observability:o},a){if(t?.aborted||!n.activeSession.value){tn({observability:o},{errorName:"SessionAlreadyTerminated",methodName:e});return}try{a()}catch(r){if(r instanceof Error&&r.name==="InvalidAccessError"){tn({observability:o},{errorName:"InvalidAccessError",methodName:e});return}throw r}}function tn({observability:e},t){e.counter({name:"apple_pay_session_error",value:1,attributes:t}),e.log("apple_pay_with_active_session",ba,t),e.leaveErrorBreadcrumb("[Apple Pay] Error while calling ApplePaySession method",t,"error")}const Da=1;function Oa(e){return e.shouldDecelerate?e.isCaliforniaDeceleration?"california":"decelerated":"none"}function La(){const e=Se(),t=no(),{progress:n}=yt(),o=yo(),a=ho(),r=fe(),i=dn(),s=ve().buyerIdentity.value?.customerProfile,l=oo(),m=Ao(),d=mo("APPLE_PAY"),{inMemoryApplePayParts:{asPaymentMethod:p,requirePhoneOnNextAttempt:y,requireBillingPhoneOnNextAttempt:g,paymentSheetError:h,expiresAt:E,preCompletionHandler:_,subscriptionReviewTransition:P},persistedApplePaySignal:v,walletUsedForSubmissionSignal:I}=te(),f=gt(),R=Na(),C=Et(),O=Cn(),{source:{checkoutSessionIdentifier:L},observability:A,checkout:{wallets:u,address:{countryDetails:b},configuration:c},shop:w,events:N,client:H}=G(),T=et(w),j=c.addressSettings.nonBillingAddressSettings,U=c.layout.isOnePage,oe=_t(D.ApplePay),{trackAttempt:Y}=je(D.ApplePay),x=ht(p),F=ve(),re=F.buyerIdentity.value?.purchasingCompany,ae=F.availableDeliveryAddresses?.value,Z=F.mustSelectProvidedAddress?.value,he=Qe({availableDeliveryAddresses:ae,mustSelectProvidedAddress:Z}),{email:Ce,shippingAddress:ce,billingAddress:ye,paymentLines:Ae,deliveryLines:me}=We(),pe=Uo(),Fe=_o({shouldPersist:!0}),Te=Zo({flag:sn,onAbort:Fe,onError:Ne=>{throw Ne}}
1),Ye=Ra({canDecelerate:x,asPaymentMethod:p}),St=wa();return Q(async(Ne,de,Ct,ie,bn,Tt)=>{let nt=!1;const Nt=f(),J=p.value,_e=x.value,ue=J?W.PaymentMethod:W.Express;Y({walletType:ue}),K.start("apple-pay-authorization"),O({status:ne.Attempt,walletType:ue});function Ie(){try{se({methodName:"completePayment",abortSignal:ie,wallets:u,observability:A},()=>de.completePayment(ApplePaySession.STATUS_FAILURE)),A.leaveErrorBreadcrumb("[ApplePay] Completion flow - clearing activeSession (abort path)"),u.clearActiveSession({invokingWallet:"APPLE_PAY"}),A.log("apple_pay_authorization_aborted","Apple Pay authorization aborted during payment completion",{}),C()}catch(S){e({session:de,error:S})}finally{J||t()}}if(!ie.aborted&&u.activeSession.value&&bn?.()){A.leaveErrorBreadcrumb("ApplePay: authorization blocked by payment method reconciliation"),h.value={type:"session_terminated"},Ie();return}function Be(S,B){switch(B.effects?.forEach(k=>k()),B.action){case"submit":{const k=d.value,$=k?.walletOrderTypeIdentifier&&k?.walletServiceUrl&&k?.walletAuthenticationToken,Pe=L&&$?{status:ApplePaySession.STATUS_SUCCESS,orderDetails:{orderTypeIdentifier:k.walletOrderTypeIdentifier,orderIdentifier:L,webServiceURL:k.walletServiceUrl,authenticationToken:k.walletAuthenticationToken}}:ApplePaySession.STATUS_SUCCESS;let be=!1;try{se({methodName:"completePayment",abortSignal:ie,wallets:u,observability:A},()=>{S.completePayment(Pe),be=!0})}catch(Ve){e({session:S,error:Ve,isProcessing:!0})}finally{A.leaveErrorBreadcrumb("[ApplePay] payment completed successfully",{walletType:ue}),u.clearActiveSession({invokingWallet:"APPLE_PAY"})}return be&&O({status:ne.Success,walletType:ue}),I.value="APPLE_PAY",be}case"show_error":{const k=xo(B),$={status:ApplePaySession.STATUS_FAILURE,errors:k};A.log("apple_pay_authorization_has_errors","apple_pay_authorization_has_errors",{errors:k});try{se({methodName:"completePayment",abortSignal:ie,wallets:u,observability:A},()=>S.completePayment($)),ie.aborted||$.errors.length===0?(A.leaveErrorBreadcrumb("[ApplePay] payment failed with no errors or abort action, sheet will close"),u.clearActiveSession({invokingWallet:"APPLE_PAY"}),C()):(A.leaveErrorBreadcrumb("[ApplePay] payment failed with handled errors, sheet will remain open for retry"),C())}catch(Pe){return e({session:S,error:Pe}),!1}return!0}case"abort":return Ie(),!1;case"decelerate":{if(!_e)return Ie(),!1;const k=B.completePaymentStatus??ApplePaySession.STATUS_FAILURE;try{se({methodName:"completePayment",abortSignal:ie,wallets:u,observability:A},()=>S.completePayment(k)),u.clearActiveSession({invokingWallet:"APPLE_PAY"}),O({status:ne.Failure,walletType:ue,endsAuthorization:!1}),oe({event:dt.RecoveryFlowInitiated,walletType:ue}),U.value&&(u.setEscalatedWallet("APPLE_PAY"),o.value.currentPage?.id==="review"&&a("payment-methods",{replace:!0})),v.value={...v.value,receiptIdForPaymentFailure:void 0,recoverySubmissionAttemptCount:0},U.value?N.dispatchEvent(new pt):nt=!0}catch($){return e({session:S,error:$}),!1}return!0}default:return e({session:S,error:new z(`Missing handler for payment sheet action "${B.action}"`,{groupingHash:"ApplePayAPIError::MissingHandlerPaymentSheetAction"})}),!1}}const Dn=j.value.isRequired("address2"),On=j.value.isRequired("firstName"),{token:It,billingContact:ke,shippingContact:M}=Ne.payment,ot=j.value.isRequired("phone",{countryCode:ee(M?.countryCode)}),at=Nt.validateBilling(Ne.payment);if(at.shouldPersist&&ke&&!re){const B=!i.value&&ot||g.value?M?.phoneNumber:void 0;g.value&&M?.phoneNumber&&A.counter({name:"apple_pay_billing_phone_provided_after_retry",value:1,attributes:{asPaymentMethod:J}});const k={...ke,phoneNumber:B};T&&await b.fetch(ee(k.countryCode)),nn(ye,k,T)}if(at.paymentSheetAction){Be(de,at.paymentSheetAction);return}if(A.log("wallets_shipping_address_update","onPaymentAuthorized: decision state before shipping address update",{asPaymentMethod:J,shippingContactDefined:!!M,isShippingContactPostalCodePadded:ge(M?.postalCode,ee(M?.countryCode)),isCurrentProposedPostalCodePadded:ge(ce.value?.postalCode,ce.value?.countryCode),shippingRequired:i.value}),!J&&!he){const S=Nt.validateShipping(Ne.payment,i.value,Dn&&!_e,On,ot&&!_e);if(S.shouldPersist&&M){m({postalCode:M.postalCode,countryCode:ee(M.countryCode),city:M.locality,zoneCode:M.administrativeArea||M.subLocality},"APPLE_PAY"),T&&await b.fetch(ee(M.countryCode));
1const B={...we(M),...tt(M,T)};A.log("wallets_shipping_address_update","onPaymentAuthorized: update with complete shipping address from shippingContact",{isPostalCodePadded:ge(B.postalCode,B.countryCode),countryCode:B.countryCode}),nn(ce,M,T)}if(S.paymentSheetAction){Be(de,S.paymentSheetAction);return}}if(!J){const S=s?.email??M?.emailAddress;S&&(Ce.value=S)}M?.phoneNumber&&me.value.forEach(S=>{S.value={...S.value,deliveryMethodOptions:{...S.value.deliveryMethodOptions,phone:M.phoneNumber}}}),y.value&&M?.phoneNumber&&A.counter({name:"apple_pay_phone_provided_after_retry",value:1,attributes:{asPaymentMethod:J}}),J?pe({phone:M?.phoneNumber,email:M?.emailAddress,firstName:ke?.givenName}):pe();const Rt=r.current.fields.paymentDue.value;if(Rt&&Rt.amount>0||l.value){const S=Ae.value,{brand:B,lastFourDigits:k}=ha(It.paymentMethod.displayName);Ae.value=ao(S,{method:{type:"wallet",name:"APPLE_PAY",walletContent:{...It.paymentData,lastDigits:k,cardNetworkBrand:B,paymentMethodIdentifier:d.value?.paymentMethodIdentifier,..._e&&{expiresAt:E.value}}}})}const Re=Ye.value,bt=l.value,rt=bt?ro(H.unstable_getSerialization("experiments")):null,Ln=Tt!==void 0&&Tt===so(rt),Dt=u.activeSession.value,Mn=Re.isCaliforniaDeceleration&&Re.hasSubscription&&!J&&!ie.aborted&&Dt?.wallet==="APPLE_PAY"&&!Dt.asPaymentMethod&&Re.isABTestActive&&Ln,it={...Re,shouldDecelerate:Re.shouldDecelerate&&!Mn};if(bt){const S=rt!==null,B=Oa(it);A.counter({name:"apple_pay_subscriptions_deceleration_variant",value:1,attributes:{variant:rt??io.Control,complete_payment_status:"success",is_ab_test_active:w.hasFlagEnabled(cn),is_california_excluded:it.isCaliforniaDeceleration,has_caution_banner:!1,deceleration_scope:B,is_enrolled:S,as_payment_method:J}})}if(it.shouldDecelerate){if(U.value&&!await St(ie,Ie))return;if(u.setEscalatedWallet("APPLE_PAY"),u.setIsDecelerating(!0),!Be(de,{action:"decelerate",completePaymentStatus:ApplePaySession.STATUS_SUCCESS,effects:[]})){u.setEscalatedWallet(null),u.setIsDecelerating(!1),u.setHasActiveApplePaySubscriptionReview(!1),P.value=void 0;return}if(P.value="in_app_deceleration",u.setHasActiveApplePaySubscriptionReview(!0),nt)try{await Te({wallet:"APPLE_PAY",reason:"subscriptions",asPaymentMethod:J})}catch(B){P.value=void 0,B instanceof Error&&e({session:de,error:B})}return}const Ot=_?.value;if(Ot&&!await Ot()){A.leaveErrorBreadcrumb("ApplePay: Pre-completion handler failed",{asPaymentMethod:J}),Ie();return}Ct.value=!0;let le=0,Ue="",st="unexpected error",Lt=[];const wn=Vo(r.current.fields.deliveryNext?.value);try{A.leaveErrorBreadcrumb("ApplePay: Payment authorized negotiation",{retryCount:le});const S=ce.value;for(;;){let B=!1;if(ie.aborted||(await n("apple-pay-payment-authorized",k=>{const $=k;$.status==="rejected"&&(Lt=$.violations.map(De=>De.code),$.violations.some(De=>De.code==="BUYER_IDENTITY_MISSING_CONTACT_METHOD")&&A.log("apple_pay_on_payment_authorized","Apple Pay is missing contact method",{asPaymentMethod:p.value,proposedEmail:Ce.value||"",customerProfileEmail:s?.email||"",shippingContactEmail:M?.emailAddress||"",hasShippingContact:!!M,shippingContactPhone:M?.phoneNumber||"",allViolationCodes:$.violations.map(De=>De.code).join(","),isPhoneRequired:ot}));const Pe=$.status==="rejected"&&$.violations.some(wt=>wt.code===xe),{shouldRetry:be,retryReason:Ve,updatedDeliveryMethodHandles:Mt}=Ma($,{retryCount:le,negotiated:r,originalSelectedDeliveryMethods:wn});if(be&&!Pe){Mt&&(Ge(me,Mt),ue===W.Express&&(A.log("wallets_shipping_address_update","onPaymentAuthorized: restoring address snapshot on retry",{isSnapshotPostalCodePadded:ge(S?.postalCode,S?.countryCode),countryCode:S?.countryCode,retryCount:le}),he||(ce.value=S))),A.leaveErrorBreadcrumb(`ApplePay: retrying due to ${Ve}`,{retryCount:le}),le++,Ue=Ve,B=!ie.aborted;return}A.leaveErrorBreadcrumb("ApplePay: completed negotiation",{action:"paymentAuthorized",status:k.status,retryCount:le,retryReason:Ue});const Fn=R($,{shippingCountryCode:ee(M?.countryCode),billingCountryCode:ee(ke?.countryCode),..._e&&{options:{applePayRecoveryFlowEnabled:_e,asPaymentMethod:p.value}}});Be(de,Fn),st=k.status},{skipToCompletion:!0,customizeCompletion:ue===W.Express?Ho:void 0}),!B))break}nt&&await Te({wallet:"APPLE_PAY",reason:"submitForCompletion",asPaymentMethod:J})}catch(S){S instanceof Error&&e({session:de,error:S})}finally{Ct.value=!1,le>0&&(A.counter({name:"wallet_submit_for_completion_retry",value:1,attributes:{retry_reason:Ue||"unknown",retry_count:le,status:st,instrument:D.ApplePay}}),A.log("wallet_submit_for_completion_retry_details","[ApplePay] SubmitForCompletion retry details",{retryReason:Ue,retryCount:le,status:st,instrument:D.ApplePay,asPaymentMethod:J,lastRejectionViolationCodes:Lt}))}},[p,j,f,y,g,h,r,l,d,L,I,e,Y,O,C,t,re,ye,i,s?.email,m,ce,Ce,me,Ae,n,St,R,pe,u,A,v,x,Te,U,N,E,_,P,oe,he,Ye,b,T,H,w,o,a])}function nn(e,t,n){const o=tt(t,n),a=e.fields.line2;e.value={...we(t),...o},a&&"line2"in o&&(a.value=o.line2)}function Ma(e,{retryCount:t,negotiated:n,originalSelectedDeliveryMethods:o}){const a={shouldRetry:!1,retryReason:"",updatedDeliveryMethodHandles:void 0};if(e.status!=="rejected"||t>=Da)return a;const r=qo(e,n.current.fields.deliveryNext?.peek(),o);return r?{shouldRetry:!0,retryReason:"delivery_option_mismatch",updatedDeliveryMethodHandles:r}:a}function wa(){const{negotiate:e}=yt(),{checkout:{wallets:t},observability:n}=G();return Q(async(o,a)=>{let r=!1,i,s;try{await e({runListenersOnError:!0,fieldsToResolve:["deliveryNext"],onComplete:p=>{if(p.status==="success"||p.status==="error"||p.status==="invalid"){r=!0;return}i=p.status}})}catch(p){r||(s=p)}const l=o.aborted||!t.activeSession.value;if(r&&!l)return!0;let m="rejected";l?m="session_ended":i&&(m="unsettled_status");const d={result:"failed",reason:m,status:i??"none"};return n.counter({name:"apple_pay_pre_deceleration_negotiation_attempt",value:1,attributes:d}),n.log("apple_pay_pre_deceleration_negotiation_attempt","[ApplePay] Pre-deceleration negotiation aborted",{...d,error:String(s)}),a(),!1},[e,t,n])}function vt(){const e=gt();return Q((t,n)=>{const{negotiationResultMapper:o}=e();if(!o)throw new z("NegotiationResultMapper not set up correctly",{groupingHash:"ApplePayAPIError::NegotiationResultMapper"});return o.mapResultToPaymentSheetAction(t,n)},[e])}function Fa(e,t,{interfaceFlow:n,isConstrainedAddress:o=!1,deliveryAddressOptions:a}={}){return o?e:{...e,delivery:{...e.delivery,interfaceFlow:n,useProgressiveRates:!1,deliveryLines:(e.delivery?.deliveryLines??[]).map(r=>({...r,destination:{partialStreetAddress:$o(t,a)}}))}}}function Ya(){const{observability:e,checkout:{wallets:t,address:{countryDetails:n,extendedAddressMode:o}},checkout:a,shop:r}=G(),i=et(r),s=Se(),l=Et(),m=vt(),d=Ze(),p=fe(),y=_t(D.ApplePay),g=mt(),{formattedRecurringTotalTooltip:h,lineItemsLabels:E,deliveryOptionGroupTypeLabels:_,deliveryMethodTitlePrefixes:P}=Xe();return Q(async(v,I,f,R)=>{const{billingContact:C}=v.paymentMethod;if(!a.isShippingRequired.value&&C){e.leaveErrorBreadcrumb("ApplePay: Payment method selected negotiation");try{i&&await n.fetch(ee(C.countryCode)),await g({abortSignal:f,fieldsToResolve:["duties","taxes"],customizeNegotiation:u=>Ba(u,C,{deliveryAddressOptions:{extendedAddressMode:o},extendedAddressFieldsEnabled:i}),observability:e,onComplete:A,walletName:D.ApplePay,logPrefix:"ApplePay::useOnPaymentMethodSelected"})}catch(u){u instanceof Error&&s({session:I,error:u})}}if(I&&t.activeSession.value){if(R&&!await O(R))return;L()}async function O(u){let b=!1;try{b=await u(f)}catch(c){return c instanceof Error&&s({session:I,error:c}),!1}return f.aborted||!t.activeSession.value?(e.leaveErrorBreadcrumb("ApplePay: 
1session ended while waiting for totals to settle"),!1):(b||(e.leaveErrorBreadcrumb("ApplePay: totals did not settle before payment method selection"),s({session:I,error:new z("Payment method selection reconciliation timed out",{groupingHash:"ApplePayAPIError::PaymentMethodSelectionReconciliationTimeout"})})),b)}function L(){const{paymentDue:u,recurringTotals:b,...c}=Le(p);if(u==null)return s({session:I,error:new z("Missing negotiated payment due",{groupingHash:"ApplePayAPIError::MissingNegotiatedPaymentDue"})});const w=Ke(u.currencyCode);try{se({methodName:"completePaymentMethodSelection",abortSignal:f,wallets:t,observability:e},()=>{const N={newTotal:Je(E.total,u),newLineItems:$e({...c,formattedRecurringTotals:d(b),formattedRecurringTotalTooltip:h,lineItemsLabels:E,deliveryOptionGroupTypeLabels:_,deliveryMethodTitlePrefixes:P})};I.completePaymentMethodSelection(w?Pt(N):N)})}catch(N){N instanceof Error&&s({error:N,session:I})}}function A(u){if(t.activeSession.value&&!f.aborted&&(e.leaveErrorBreadcrumb("ApplePay: completed negotiation",{action:"paymentMethodSelected",status:u.status}),C)){const b=m(u,{billingCountryCode:ee(C.countryCode)});b.effects?.forEach(c=>c()),b.action==="abort"&&(e.log("apple_pay_on_payment_method_selected","[ApplePayButton.session.onpaymentmethodselected] session aborted due to blocking error",{errors:b.errors,session:I}),se({methodName:"abort",abortSignal:f,wallets:t,observability:e},()=>I.abort()),t.clearActiveSession({invokingWallet:"APPLE_PAY"}),l())}}a.isShippingRequired.value||K.endAndRun("apple-pay-sheet-load",u=>{y({event:dt.SheetLoaded,ttl:u}),e.histogram({name:"wallet_sheet_loaded",value:u,attributes:{instrument:D.ApplePay}})})},[t,l,P,_,d,h,m,E,p,a.isShippingRequired,e,s,y,g,o,n,i])}const Ba=(e,t,{deliveryAddressOptions:n,extendedAddressFieldsEnabled:o=!1}={})=>Fa(e,{...we(t),...tt(t,o)},{interfaceFlow:"APPLE_PAY",deliveryAddressOptions:n});function Nn(){const e=Et(),t=G(),{checkout:{wallets:n},observability:o}=t;return Q(({session:a,paymentSheetAction:r,onProceed:i,abortSignal:s})=>{switch(r.action){case"abort":se({methodName:"abort",abortSignal:s,wallets:n,observability:o},()=>a.abort()),n.clearActiveSession({invokingWallet:"APPLE_PAY"}),e();break;case"update":i(r.errors);break;case"no-op":i();break;default:throw new z(`Missing handler for payment sheet action "${r.action}"`,{groupingHash:"ApplePayAPIError::MissingHandlerPaymentSheetAction"})}},[e,n,o])}function ka(){const e=Se(),t=Ze(),n=vt(),o=fe(),a=yn(),{inMemoryApplePayParts:{initialDeliveryIdentifier:r,asPaymentMethod:i}}=te(),{deliveryLines:s,shippingAddress:l}=We(),m=mt(),d=ve(),p=d.availableDeliveryAddresses?.value,y=d.mustSelectProvidedAddress?.value,g=d.deliveryNext?.value,h=Qe({availableDeliveryAddresses:p,mustSelectProvidedAddress:y}),E=G(),{checkout:{wallets:_,address:P},observability:v}=E,{countryDetails:I,extendedAddressMode:f}=P,R=et(E.shop),{formattedRecurringTotalTooltip:C,lineItemsLabels:O,deliveryOptionGroupTypeLabels:L,deliveryMethodTitlePrefixes:A,connectTwoShippingTitles:u}=Xe(),b=Nn(),{shouldGateCrossBorder:c,crossBorderGate:w}=co(),N=ht(i);return Q(async(H,T,j)=>{const U={...we(H.shippingContact),...tt(H.shippingContact,R)};v.log("wallets_shipping_address_update","onShippingContactSelected: update with partial shipping address",{countryCode:U.countryCode,isPostalCodePadded:ge(U.postalCode,U.countryCode)});const oe=H.shippingContact.countryCode?ee(H.shippingContact.countryCode):void 0;if(Ge(s,void 0),r.value=void 0,c(oe)){v.log("apple_pay_cross_border_gate","Apple Pay shipping country creates a cross-border split. Closing the payment sheet and opening the consolidation modal.",{shippingCountryCode:oe});try{e({session:T,isMessagingHandledElsewhere:!0,error:new Oe("Session terminated due to cross-border shipping country change")})}catch(F){v.leaveErrorBreadcrumb("ApplePay: failed to abort session for cross-border gate",{errorName:F instanceof Error?F.name:"Unknown",errorMessage:F instanceof Error?F.message:String(F)})}w(()=>{l.fields.zoneCode.value=void 0,l.fields.coordinates.value=void 0,l.fields.countryCode.value=oe});return}if(h)Y(T);else{l.value=U,v.leaveErrorBreadcrumb("ApplePay: Shipping contact selected negotiation",{countryCode:U.countryCode,isPostalCodePadded:ge(U.postalCode,U.countryCode)}
1);try{R&&await I.fetch(U.countryCode),await m({abortSignal:j,fieldsToResolve:["deliveryNext","duties","taxes"],customizeNegotiation:F=>hn(F,U,{interfaceFlow:"APPLE_PAY",isPickupSelected:a.value,isConstrainedAddress:h,availableDeliveryAddresses:p,negotiatedDelivery:g,deliveryAddressOptions:{extendedAddressMode:f}}),observability:v,walletName:D.ApplePay,onComplete:x,logPrefix:"ApplePay::useOnShippingContactSelected"})}catch(F){F instanceof Error&&e({session:T,error:F})}}function Y(F,re){const{paymentDue:ae,recurringTotals:Z,deliveryNext:he,...Ce}=Le(o);if(ae==null)return e({session:F,error:new z("Missing negotiated payment due",{groupingHash:"ApplePayAPIError::MissingNegotiatedPaymentDue"})});const ce=Ke(ae.currencyCode);try{const ye={newTotal:Je(O.total,ae),newLineItems:$e({...Ce,formattedRecurringTotals:t(Z),formattedRecurringTotalTooltip:C,lineItemsLabels:O,deliveryOptionGroupTypeLabels:L,deliveryMethodTitlePrefixes:A})},Ae=En({deliveryMethodTitlePrefixes:A,connectTwoShippingTitles:u,deliveryNext:he}),me={...ye,newShippingMethods:Ae};se({methodName:"completeShippingContactSelection",abortSignal:j,wallets:_,observability:v},()=>F.completeShippingContactSelection({errors:re,...ce?Pt(me):me}));try{const pe=Ua(he,re);if(!pe)return;const Fe=Ae.find(Te=>pe.every(Ye=>Te.identifier.includes(Ye)))?.identifier;Fe&&(r.value=Fe)}catch(pe){v.error(pe)}}catch(ye){ye instanceof Error&&e({error:ye,session:F})}}function x(F){const re=N.value;if(!_.activeSession.value||j.aborted)return;v.leaveErrorBreadcrumb("ApplePay: completed negotiation",{action:"shippingContactSelected",status:F.status});const ae=n(F,{shippingCountryCode:ee(H.shippingContact.countryCode),...re&&{options:{applePayRecoveryFlowEnabled:re}}});ae.effects?.forEach(Z=>Z()),v.leaveErrorBreadcrumb("ApplePay: Payment sheet action",{action:"shippingContactSelected",paymentSheetAction:ae.action}),b({session:T,paymentSheetAction:ae,onProceed:Z=>Y(T,Z),abortSignal:j})}},[s,l,a,n,b,o,e,O,t,C,L,A,u,r,m,_,v,N,h,p,g,c,w,R,I,f])}function Ua(e,t){if(t?.length||!e||e.status!=="filled"||!e.lines?.length)return;const n=e.lines.reduce((o,a)=>(a.status==="available"&&a.selectedDeliveryMethodHandle&&o.push(a.selectedDeliveryMethodHandle),o),[]);if(!(n.length<e.lines.length))return n}function Va(){const e=Se(),t=Ze(),n=vt(),o=fe(),a=yn(),{observability:r,checkout:{wallets:i,address:{countryDetails:s,extendedAddressMode:l}},shop:m}=G(),d=et(m),{inMemoryApplePayParts:{initialDeliveryIdentifier:p}}=te(),{deliveryLines:y,shippingAddress:g}=We(),h=_t(D.ApplePay),E=mt(),_=ve(),P=_.availableDeliveryAddresses?.value,v=_.mustSelectProvidedAddress?.value,I=_.deliveryNext?.value,f=Qe({availableDeliveryAddresses:P,mustSelectProvidedAddress:v}),{formattedRecurringTotalTooltip:R,lineItemsLabels:C,deliveryOptionGroupTypeLabels:O,deliveryMethodTitlePrefixes:L}=Xe(),A=Nn();return Q(async(u,b,c)=>{const w=p.value;p.value=void 0;const N=u.shippingMethod.identifier===w;r.counter({name:"apple_pay_skip_initial_delivery_negotiation",value:1,attributes:{skippedNegotiation:N}}),!N&&w&&r.log("apple_pay_on_shipping_method_selected","Apple Pay failed to skip initial delivery negotiation",{expectedHandle:w,actualHandle:u.shippingMethod.identifier});const H=Y=>{try{return Go(Y)}catch(x){return e({session:b,error:new z("Invalid shipping method identifier",{groupingHash:"ApplePayAPIError::InvalidShippingMethodIdentifier",cause:x,metadata:{identifier:Y}})}),null}};if(N){const Y=H(w);if(Y==null)return;Ge(y,Y),U(b);return}const T=g.value,j=H(u.shippingMethod.identifier);if(j==null)return;Ge(y,j),r.leaveErrorBreadcrumb("ApplePay: Shipping method selected negotiation",{handles:JSON.stringify(j),identifier:u.shippingMethod.identifier});try{d&&await s.fetch(T.countryCode),await E({abortSignal:c,fieldsToResolve:["deliveryNext","duties","taxes"],customizeNegotiation:Y=>hn(Y,T,{interfaceFlow:"APPLE_PAY",isPickupSelected:a.value,isConstrainedAddress:f,availableDeliveryAddresses:P,negotiatedDelivery:I,deliveryAddressOptions:{extendedAddressMode:l}}),observability:r,walletName:D.ApplePay,onComplete:oe,logPrefix:"ApplePay::useOnShippingMethodSelected"})}catch(Y){e({session:b,error:Y})}function U(Y){const{paymentDue:x,recurringTotals:F,...re}=Le(o);if(x==null)return e({session:Y,error:new z("Missing negotiated payment due",{groupingHash:"ApplePayAPIError::MissingNegotiatedPaymentDue"})});const ae=Ke(x.currencyCode);try{se({methodName:"completeShippingMethodSelection",abortSignal:c,wallets:i,observability:r},()=>{const Z={newTotal:Je(C.total,x),newLineItems:$e({...re,formattedRecurringTotals:t(F),formattedRecurringTotalTooltip:R,lineItemsLabels:C,deliveryOptionGroupTypeLabels:O,deliveryMethodTitlePrefixes:L})};Y.completeShippingMethodSelection(ae?Pt(Z):Z)}),K.endAndRun("apple-pay-sheet-load",Z=>{h({event:dt.SheetLoaded,ttl:Z}),r.histogram({name:"wallet_sheet_loaded",value:Z,attributes:{instrument:D.ApplePay}})})}catch(Z){Z instanceof Error&&e({error:Z,session:Y})}}function oe(Y){if(i.activeSession.value&&!c.aborted){r.leaveErrorBreadcrumb("ApplePay: completed negotiation",{action:"shippingMethodSelected",status:Y.status});try{const x=n(Y,{shippingCountryCode:T.countryCode});x.effects?.forEach(F=>F()),r.leaveErrorBreadcrumb("ApplePay: Payment sheet action",{action:"shippingMethodSelected",paymentSheetAction:x.action}),A({session:b,paymentSheetAction:x,onProceed:()=>
1U(b),abortSignal:c})}catch(x){x instanceof Error&&e({error:x,session:b})}}}},[i,L,O,t,R,n,A,a,C,o,y,g,e,r,h,p,E,f,P,I,s,d,l])}function Ha(){const e=Me(D.ApplePay),t=Se(),{shop:n,source:{sourceId:o},observability:a,checkout:{wallets:r},embed:i,graphql:{coreGraphql:s}}=G(),l=vn({embed:i,isCrossOriginIframeEnabled:n.hasFlagEnabled(pn)}),{inMemoryApplePayParts:{prefetchPaymentSession:m}}=te(),d=Po(D.ApplePay);return Q((p,y,g,h)=>{const E=h===m.value?.prefetchUrl;a.histogram({name:"apple_pay_prefetch_session",value:K.end("apple-pay-session-begin"),attributes:{prefetch:E?"success":"retried"}}),_().then(P=>{if(m.value=void 0,P instanceof _n){a.leaveErrorBreadcrumb("[ApplePay] Validation query returned failed response",{reason:P.reason}),a.log("apple_pay_on_validate_merchant","Apple Pay session creation failed",{reason:P.reason}),t({session:p,error:new Oe(P.reason)});return}if(!P){const v=g.aborted,I=r.activeSession.value?.wallet==="APPLE_PAY";a.leaveErrorBreadcrumb("[ApplePay] Validation query returned no data",{asPaymentMethod:y,isAborted:v,isActiveApplePaySession:I});const f=v||!I?new Oe("Apple Pay session query returned no data after session was cancelled"):new z("session query returned no data");t({session:p,error:f,isAborted:v});return}e(ne.Success,y?W.PaymentMethod:W.Express),y||d(),se({methodName:"completeMerchantValidation",abortSignal:g,wallets:r,observability:a},()=>p.completeMerchantValidation(JSON.parse(P.body)))}).catch(P=>{t({error:P,session:p,isAborted:g.aborted})});async function _(){if(m.value)try{const P=await m.value.prefetchPromise;if(E&&P)return P;E&&!P?a.leaveErrorBreadcrumb("[ApplePay] session query prefetch returned no data - starting new validation query",{validationUrl:h,prefetchUrl:m.value?.prefetchUrl}):E||a.leaveErrorBreadcrumb("[ApplePay] session query prefetch URL mismatch - starting new validation query",{validationUrl:h,prefetchUrl:m.value?.prefetchUrl})}catch(P){if(P instanceof At)return;a.log("apple_pay_on_validate_merchant","Apple Pay prefetch session error",{error:P,prefetchValidationUrl:m.value?.prefetchUrl,validationUrl:h})}return a.leaveErrorBreadcrumb("[ApplePay] starting new session query",{hadPrefetch:!!m.value,validationUrl:h}),Pn({graphql:s,sourceId:o,validationUrl:h,asPaymentMethod:y,signal:g,observability:a,isPrefetch:!1,domain:l})}},[s,o,a,e,d,t,m,r,l])}function In(){const e=Se(),t=fe(),n=Me(D.ApplePay),{inMemoryApplePayParts:{asPaymentMethod:o,paymentSheetError:a,prefetchPaymentSession:r}}=te(),{shop:i,source:{sourceId:s},observability:l,embed:m,graphql:{coreGraphql:d}}=G(),{countryCode:p}=i,y=vn({embed:m,isCrossOriginIframeEnabled:i.hasFlagEnabled(pn)}),g=Pa(),h=Eo().geolocation.country.code,E=va(h),_=fa(),P=Ha(),v=Ya(),I=Va(),f=ka(),R=La();return Q(({asPaymentMethod:C=!1,supportedNetworks:O,waitForTotalsToSettle:L,isPaymentAuthorizationBlocked:A,subscriptionConsent:u})=>{K.start("apple-pay-session-begin"),a.value=void 0,o.value=C;const b=Bn(!1),c=new AbortController,{paymentDue:w}=Le(t);if(!w)return n(ne.Failure,C?W.PaymentMethod:W.Express),a.value={type:"session_terminated"},l.error(new z("Missing paymentDue",{groupingHash:"ApplePayAPIError::MissingPaymentDue"}),{severity:"error",errorClass:qe.Api}),{session:void 0,error:"no_payment_due"};r.value||(r.value={prefetchPromise:(async()=>(await Promise.resolve(),Pn({graphql:d,sourceId:s,validationUrl:E,asPaymentMethod:C,signal:c.signal,observability:l,isPrefetch:!0,domain:y})))(),prefetchUrl:E});let N;const H=g(O,p);try{N=new ApplePaySession(lo,H)}catch(T){return T instanceof Error&&e({error:T}),{session:void 0,error:"session_creation_failed"}}return N.oncancel=()=>_(c,b),N.onvalidatemerchant=T=>P(N,C,c.signal,T.validationURL),N.onpaymentmethodselected=T=>v(T,N,c.signal,L),N.onshippingmethodselected=T=>I(T,N,c.signal),N.onshippingcontactselected=T=>f(T,N,c.signal),N.onpaymentauthorized=T=>R(T,N,b,c.signal,A,u),{session:N,error:void 0}},[o,g,t,a,_,R,v,f,I,P,p,e,n,r,E,d,l,s,y])}const xa=5e3;function qa(e,t){return t.aborted?Promise.resolve(!1):e.value?new Promise(n=>{let o=!1,a=()=>{};const r=l=>{o||(o=!0,a(),t.removeEventListener("abort",i),clearTimeout(s),n(l))},i=()=>r(!1);t.addEventListener("abort",i,{once:!0});const s=setTimeout(i,xa);a=e.subscribe(l=>{l||r(!0)}),o&&a(),t.aborted&&i()}):Promise.resolve(!0)}function Rn(){const{inMemoryApplePayParts:{asPaymentMethod:e,expiresAt:t}}=te(),{observability:n,checkout:{wallets:o}}=G(),a=ht(e);return Q(r=>{if(r){K.start("apple-pay-sheet-load"),n.counter({name:"apple_pay_button_click",value:1,attributes:{wallet_type:e.value?W.PaymentMethod:W.Express}}),n.counter({name:"wallet_sheet_clicked",value:1,attributes:{instrument:D.ApplePay}});try{r.begin()}catch(i){if(i instanceof Error&&i.name==="InvalidAccessError"){n.log("apple_pay_session_begin_error","Apple Pay session.begin() failed from insecure context",{errorName:"InvalidAccessError"});return}throw i}a.value&&(t.value=new Date(Date.now()+300*1e3).toISOString()),o.setActiveSession({newValue:"APPLE_PAY",asPaymentMethod:e.value})}},[e,n,o,a,t])}const Ga=new Set(ln);function za(){const{negotiate:e}=yt(),{observability:t,shopPay:n,checkout:{wallets:o,identity:a}}=G(),r=a.current.value==="shopPay",{inMemoryApplePayParts:{isLoadingPaymentSheet:i,paymentSheetError:s}}=te(),l=r?D.ShopPayApplePay:D.ApplePay,m=In(),d=Me(l),p=Jo(),y=un(),{shopOfferReconciliationPending:g}=n,h=Rn(),P=ve().paymentMethods?.value?.find(f=>f.type==="wallet"&&f.name==="APPLE_PAY")?.supportedNetworks,v=async f=>{i.value=!0;try{if(r){if(!f||!f())return!1;p()}const R=await new Promise((O,L)=>{e({runListenersOnError:!0,negotiationStage:"completion",include:["deliveryNext"],onComplete:O}).catch(L)}),C=y.value&&R.status==="error"&&R.violations.length>0&&R.violations.every(({code:O})=>Ga.has(O));return C&&(t.counter({name:"apple_pay_silenced_violations_requiring_new_token",value:1}),t.log("apple_pay_silenced_violations","PayWithApplePayButton: silenced violations",{violations:R.violations})),R.status==="success"||C}catch{return s.value={type:"failed_to_create_session"},!1}finally{i.value=!1}},I=f=>{if(!g.value)return Promise.resolve(!0);t.counter({name:"apple_pay_shop_offer_reconciliation_wait",value:1});const R=Date.now();return qa(g,f).then(C=>(t.histogram({name:"apple_pay_shop_offer_reconciliation_wait_duration",value:Date.now()-R,attributes:{reconciled:C}}),C))};
1return async({disabled:f=!1,isMountedRef:R,validateButtonPress:C})=>{if(!f){d(ne.Clicked,W.PaymentMethod);try{const O=m({asPaymentMethod:!0,supportedNetworks:P||[],waitForTotalsToSettle:I,isPaymentAuthorizationBlocked:()=>g.value}),L=await v(C),A=R?R.current:!0;L&&!o.activeSession.value&&A&&h(O.session)}catch(O){t.leaveErrorBreadcrumb("Failed to create Apple Pay session",{error:O,shopPay:r}),s.value={type:"failed_to_create_session"},o.activeSession.value?.wallet==="APPLE_PAY"&&o.clearActiveSession({invokingWallet:"APPLE_PAY"})}}}}function cr(){const{applePaySessionHandler:e,inMemoryApplePayParts:t}=te(),n=ct(za()),o=ct(In()),a=ct(Rn());return kn(()=>{if(t.sessionLoadFailed.value)return;const r={onClickHandler:(...i)=>n.current(...i),createSession:(...i)=>o.current(...i),showApplePayPaymentSheet:(...i)=>a.current(...i)};return e.value=r,()=>{e.value=void 0}},[e,n,o,a,t]),null}export{cr as ApplePaySessionLoader};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.