PageSourceSearch

https://hobbywarehouse.com.au/cdn/shopifycloud/checkout-web/assets/c1/component-WalletApplePayLazy.B_1tAl3E.js

js hobbywarehouse.com.au collected 2026-09-26 07:44:55 UTC 70,312 bytes, 1 lines download raw bytes

1import{U as Yn,V as Ft,T as Ee,q as Q,f as an,y as Bn,h as kn}from"./esnext-vendor.B9Da21W6.js";import{B as Yt,dH as Un,gL as on,gK as lt,gS as rn,b1 as Vn,aL as Hn,dn as xn,b2 as qn,S as G,hE as Gn,a4 as ve,T as We,af as fe,ae as te,gN as Qe,hF as zn,hG as sn,hH as Wn,h9 as Qn,bk as He,cP as Bt,hI as kt,dl as Zn,dm as jn,hJ as ln,gO as xe,C as Ut,a$ as $n,hK as Jn,hL as Kn,hM as cn,hN as Xn,gu as ea,hO as ta,ag as na,aP as ge,v as aa,hP as oa,hQ as ra,hR as ia,hS as pn,hT as sa}from"./addresses-is-address-empty.Bn2lNY_L.js";import{a as D,b as W,c as ne,W as dt,u as la}from"./cross-border-hooks.xPE4TSQ5.js";import{f as ut,I as Oe,W as Vt,h as z}from"./app.DbSrjjlA.js";import{i as ca}from"./graphql-PaymentSessionMutation.CAXCwUvV.js";import{f as X,g as pa,s as da,r as Le,B as ua,P as Ht,U as ya,a as ha,w as xt,x as qt,i as ma,N as Gt,E as Aa,h as _a,y as Pa,z as Ea,A as ga,C as va,F as fa,G as Sa,l as zt,H as Ca,J as Ta,K as Wt,L as Na,M as Ia,j as Ra,T as Qt,O as Zt,Q as jt,D as $t,V as Jt,I as Kt,R as Xt,u as ba,m as Da,n as Oa,o as La,W as Ma,p as wa,q as yt,t as dn,v as Fa}from"./wallets-deserialize-delivery-handles.BOkgrwan.js";import{a as Ya,g as Ba,i as ka}from"./hooks-useShopPayExternalAppContext.DWwMuRnz.js";import{fz as Ua,gF as un,gG as Ze,gH as ht,c9 as yn,fx as K,gI as qe,c2 as Va,f as mt,n as Ha,fC as xa,gb as qa,fA as Ga,go as At,gJ as za,ga as Ge,c_ as hn,fl as Wa,ch as Qa,fE as ct}from"./hydrate.DZ4YTm7p.js";import{a as Me,e as mn,u as _t}from"./PayButton-helpers.Cc_ffyKs.js";import{u as je,a as Za}from"./hooks-useWalletsThreePageVaultedReviewEscalation.DI1pRNwr.js";import{d as ja}from"./shared-report-graphql-error.0sJ2-gTk.js";import{d as $a}from"./MarketsProDisclaimer.BqGHM17j.js";import{u as Ja}from"./hooks-payment-button.CEm7ZXVs.js";import"./AddressPresenter.BIgrto4P.js";import"./hooks-useShowShopPayOptin.Br0M25ky.js";import"./hooks-useReplaceShopPayInHistory.DPpLejwu.js";import"./shared-buyer-consent.B_gDyRCR.js";const Ka={id:"1501fe0af4559751b078e255872e602b9742658e6ef2d8b73091b38649adb321",type:"query",name:"ApplePayPaymentSession",source:""},An=5,Xa=4,eo=An+Xa,to=600;class _n{constructor(t){this.reason=t}}class en extends Error{constructor(){super(...arguments),this.name="ApplePaySessionCreationResponseError"}}const no=({sourceId:e,isPrefetch:t})=>t?`${e}-prefetch-${Yt()}`:`${e}-${Yt()}`,Pn=async({graphql:e,sourceId:t,validationUrl:n,asPaymentMethod:a,signal:r,observability:o,isPrefetch:i,domain:s})=>{const l=no({sourceId:t,isPrefetch:i}),A=async h=>{const{data:E,error:_}=await e.staticQuery(Ka,{cache:!1,variables:h?{pendingTask:{taskId:h}}:{applePaySessionCreate:{resourceId:l,validationUrl:n,domain:s,walletInstrumentation:{expressWalletInCheckout:!a}}}});if(_)throw o.leaveErrorBreadcrumb("[ApplePay] session creation query returned GraphQL error",{error:_}),new en("session creation query returned GraphQL error");if(!E){o.counter({name:"apple_pay_session_query_error",value:1,attributes:{reason:"no_data"}}),o.log("apple_pay_api_query","ApplePaySession: No data returned"),o.leaveErrorBreadcrumb("[ApplePay] session creation query returned no data");return}return E};function d({result:h,pollingCount:E}){o.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(r.aborted)throw new ut("Apple pay signal aborted",{groupingHash:"AbortedSessionError::createPaymentSession::SignalAborted"});const h=performance.now(),E=await A(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}),o.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"){o.counter({name:"apple_pay_no_pending_task_error",value:1,attributes:{pollingCount:y,sourceId:t,isPrefetch:i}}),o.log("apple_pay_api_session_cancelled","Apply Pay session has no pending task",{pollingCount:y,sourceId:t,isPrefetch:i}),o.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=to-P;v>0&&await Ft(v)}if(p=_.taskId,y++,y>=eo)throw o.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<=An)break;await Ft(_.pollDelay);break}default:Yn(_)}}while(!0)}catch(h){if(h instanceof en||h instanceof Vt)return o.counter({name:"apple_pay_session_query_error",value:1,attributes:{reason:h.name}}),new _n(`${h.name}: ${h.message}`);throw h}},ao={EG:"EG",AE:"AE"};
1function $e({subtotal:e,duties:t,taxes:n,deliveryNext:a,discountLines:r,paymentLines:o,tipLines:i,shopPromotion:s,lineItemsLabels:l,deliveryOptionGroupTypeLabels:A,deliveryMethodTitlePrefixes:d,formattedRecurringTotals:p,formattedRecurringTotalTooltip:y,merchandiseLines:g}){const h=[];g?.lines&&g.lines.forEach(c=>{h.push({label:pa(c),amount:X(c.totalPrice.amount)})});const E=e===void 0?[]:[{label:l.subtotal,amount:e?X(e.amount):void 0}],_=oo({deliveryNext:a,deliveryOptionGroupTypeLabels:A,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=r&&r.lines.map(c=>{if(ca(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=o?.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=o?.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],m=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,...m,...u,...b]}function oo({deliveryNext:e,deliveryOptionGroupTypeLabels:t,deliveryMethodTitlePrefixes:n}){const a=rn(e);return a?a.map(({totalCost:r})=>({label:n.SHIPPING,amount:X(r.amount)})):xn(e).map(({line:r,method:o},i,s)=>({label:ro(r,o,s.length===1,t,n),amount:X(o.cost.amount)}))}function ro(e,t,n,a,r){const o=r[t.methodType];return n?o:`${o} (${a[e.type]})`}function En({deliveryMethodTitlePrefixes:e,connectTwoShippingTitles:t,deliveryNext:n}){const a=rn(n);if(a)return a.map(({totalTitle:s,totalCostAfterDiscounts:l,deliveryMethodHandles:A,deliveryPromisePresentmentTitle:d})=>({label:s,amount:X(l.amount),detail:d?.short??"",identifier:JSON.stringify(A)}));const r=Vn(n).filter(Hn).map(Ya),o=Ba(r).filter(s=>s.length>0);return io(n,o).map(s=>({label:lo(s,e,t),amount:co(s),detail:uo(s,t),identifier:da(s)}))}function io(e,t){if(!e||e.status!=="filled"||!qn(e))return t;const n=new Set(e.lines.reduce((r,o)=>(o.status==="available"&&o.selectedDeliveryMethodHandle&&r.add(o.selectedDeliveryMethodHandle),r),new Set)),a=t.find(r=>r.every(o=>n.has(o.handle)));return a?[a,...t.filter(r=>r!==a)]:t}const so=", ";function gn(e,t){const n=e.values(),a=n.next();if(a.done)return"";const r=n.next();if(r.done)return a.value;let o=a.value,i=r.value;for(const s of n)o+=`${so}${i}`,i=s;return t(o,i)}function lo(e,t,n){const a=e.find(l=>l.deliveryLine.type==="ONE_TIME_PURCHASE");let r="";a&&(r=a.methodType==="PICK_UP"?t[a.methodType]:a.title);const o=e.find(l=>l.deliveryLine.type==="SUBSCRIPTION");let i="";if(o){if(o.methodType==="PICK_UP"||o.methodType==="LOCAL")return o.title;i=o.title,r=a?.title??""}const s=[...new Set([r,i])];return gn(s.filter(Boolean),n)}function co(e){return X(e.reduce((t,n)=>t+n.costAfterDiscounts.amount,0))}function po(e,t){return e.add(t),e}function uo(e,t){return gn([...e.map(n=>{const{methodType:a,pickupLocation:r,deliveryPromisePresentmentTitle:o,description:i}=n;return a==="PICK_UP"||a==="PICKUP_POINT"?ho(r?.address)??"":o?o.short:i||""}).reduce(po,new Set)],t)}function Je(e,t){return{label:e,amount:X(t.amount)}}function yo({phoneRequired:e,emailRequired:t,shippingRequired:n}){const a=["name","postalAddress"],r=[...e?["phone"]:[],...t?["email"]:[]];return{requiredShippingContactFields:n?[...a,...r]:r,requiredBillingContactFields:a}}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&&on.includes(n.countryCode)&&(n.zoneCode=n.countryCode,n.countryCode="US"),t&&Object.keys(ao).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 a={UK:"GB",JA:"JP"}[t];return a||(on.includes(t)?t:"ZZ")}function ho(e){if(e){const{address1:t="",address2:n="",city:a="",company:r="",zoneCode:o="",countryCode:i=""}
1=e,s=[t,n].filter(Boolean).join(" ");return[r,s,a,o,i].filter(Boolean).join(", ")}}function vn({embed:e,isCrossOriginIframeEnabled:t}){if(t&&!(typeof window>"u"||window.self===window.top))return e?.client?.embedderHostname}function mo(e){const t={brand:"",lastFourDigits:""};if(!e)return t;const n=e.split(" ");if(n.length!==2)return t;const[a,r]=n;if(a===void 0||r===void 0)return t;for(const o of a.toLowerCase())if(o<"a"||o>"z")return t;return Number.isNaN(Number(r))?t:{brand:a,lastFourDigits:r}}const Ao=new Set(["HUF","RSD"]);function _o(e){return Ao.has(e)}function Ke(e){return e!==void 0&&_o(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 Po(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,a=e.translate("order_summary.recurring_total_tooltip"),r=t.hasFlagEnabled(Gn),o=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"),...r&&{flashDeal:e.translate("order_summary.flash_deal")},giftCards:e.translate("order_summary.gift_card_label"),tip:e.translate("order_summary.tip_label")}),[n,e,r]),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(()=>(A,d)=>e.translate("wallets.connect_shipping_methods",{method1:A,method2:d}),[e]);return Ee(()=>({formattedRecurringTotalTooltip:a,lineItemsLabels:o,deliveryOptionGroupTypeLabels:i,deliveryMethodTitlePrefixes:s,connectTwoShippingTitles:l}),[a,o,i,s,l])}function Eo(){const{checkout:e,observability:t}=G(),n=e.configuration.addressSettings.nonBillingAddressSettings.value,a=Ua(),r=ve(),o=n.isRequired("phone",{countryCode:ee(r.buyerIdentity.value?.countryCode)}),i=un(),{value:s}=r.deliveryNext,l=We(),A=fe(),d=Ze(),{paymentDue:p,recurringTotals:y,...g}=Le(A),h=Xe(),{deliveryMethodTitlePrefixes:E,connectTwoShippingTitles:_}=h,P=r.availableDeliveryAddresses?.value,v=r.mustSelectProvidedAddress?.value,{inMemoryApplePayParts:{asPaymentMethod:I,requirePhoneOnNextAttempt:f,requireBillingPhoneOnNextAttempt:R}}=te();return Q((C,O)=>{const L=I.value,m=f.value||R.value,u=!!l.shopPayArtifact.value?.optIn,b=!!l.email.value;m&&t.counter({name:"apple_pay_phone_retry_requested",value:1,attributes:{addressSettingsPhoneRequired:o,asPaymentMethod:L}});const c=Qe({availableDeliveryAddresses:P,mustSelectProvidedAddress:v}),w=L||c,{requiredShippingContactFields:N,requiredBillingContactFields:H}=yo({phoneRequired:go({asPaymentMethod:L,phoneRequired:o,shouldRequestPhoneOnRetry:m,shopPayOptInExists:u}),emailRequired:vo({asPaymentMethod:L,emailRequired:a.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}),ae={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)?Po(ae):ae},[I,f,R,_,E,s,a,P,d,h,v,g,p,o,y,i,t,l])}const go=({asPaymentMethod:e,phoneRequired:t,shouldRequestPhoneOnRetry:n,shopPayOptInExists:a})=>e?a:t||n,vo=({asPaymentMethod:e,emailRequired:t,shopPayOptInExists:n,proposedEmailExists:a})=>e?!a&&n:t;function fo(e){const t="apple-pay-gateway.apple.com/paymentservices/startSession";return e==="CN"?`https://cn-${t}`:`https://${t}`}function So(){const e=Me(D.ApplePay),{trackComplete:t}=je(D.ApplePay),n=ht(),{inMemoryApplePayParts:a}=te(),{checkout:r,observability:o,shop:i}=G(),s=yn();return Q((l,A)=>{l.abort(),a.prefetchPaymentSession.value=void 0;const d=A.value,p=a.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}),o.counter({name:"apple_pay_on_cancel",value:1,attributes:{completion_in_progress:d.toString(),wallet_type:y}}),o.counter({name:"wallet_sheet_cancelled",value:1,attributes:{instrument:D.ApplePay}}),o.log("apple_pay_use_on_cancel_sheet_cancelled","Apple Pay sheet cancelled",{completionInProgress:d,walletType:y}),a.requirePhoneOnNextAttempt.value&&o.counter({name:"apple_pay_cancelled_after_phone_retry",value:1,attributes:{asPaymentMethod:p}});const g=zn(i),h=i.hasFlagEnabled(sn),E=a.subscriptionReviewTransition.value!==void 0&&ka({applePaySubscriptionsDecelerationActive:g,applePayThreePageVaultedReviewEnabled:h,isOnePageCheckout:r.configuration.layout.isOnePage.value}),_=s.value||E;if(d)o.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:_}),a.paymentSheetError.value={type:"payment_cancelled_while_processing"};else{if(o.log("apple_pay_on_cancel_normal_path","Apple Pay cancelled - clearing activeSession",{asPaymentMethod:p,inRecoveryFlow:_}),r.wallets.activeSession.value?.wallet==="APPLE_PAY"&&r.wallets.clearActiveSession({invokingWallet:"APPLE_PAY"}),_)return;n()}e(ne.Cancelled)},[n,a.asPaymentMethod,a.paymentSheetError,a.subscriptionReviewTransition,a.requirePhoneOnNextAttempt,a.prefetchPaymentSession,t,e,o,i,r,s])}function Cn(){const{observability:e}
1=G(),t=mn(D.ApplePay),{trackComplete:n}=je(D.ApplePay);return Q(({status:a,walletType:r,endsAuthorization:o=!0})=>{if(e.counter({name:"apple_pay_payment_status",value:1,attributes:{status:a,wallet_type:r}}),t(a,r),a===ne.Attempt)return;if(!o){K.remove("apple-pay-authorization");return}const i=a===ne.Success?"success":"failed";K.endAndRun("apple-pay-authorization",s=>{n({result:i,durationMs:s,walletType:r,attributes:{walletType:r}}),e.log("apple_pay_payment_status_updated","Apple Pay payment authorization status update received",{result:i,status:a,walletType:r})})},[e,t,n])}function Et(){const e=ht(),t=Cn(),{inMemoryApplePayParts:{asPaymentMethod:n}}=te();return Q(()=>{const a=n.value?W.PaymentMethod:W.Express;e(),t({status:ne.Failure,walletType:a})},[t,e,n])}function Se(){const e=Me(D.ApplePay),t=mn(D.ApplePay),{trackComplete:n}=je(D.ApplePay),{checkout:{wallets:a},observability:r}=G(),{inMemoryApplePayParts:o}=te(),i=ht();return Q(({session:s,isProcessing:l=!1,isMessagingHandledElsewhere:A=!1,error:d,isAborted:p})=>{if(d instanceof ut)return;K.remove("apple-pay-sheet-load");const y=o.asPaymentMethod.value?W.PaymentMethod:W.Express;r.counter({name:"apple_pay_session_terminated",value:1,attributes:{error_type:d.name,wallet_type:y}}),r.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),r.counter({name:"wallet_sheet_failed",value:1,attributes:{instrument:D.ApplePay}})),!l&&!A&&(o.paymentSheetError.value={type:"session_terminated"});const{actionable:g}=ja(d);if(d instanceof Oe?r.leaveErrorBreadcrumb(`IgnoredApplePayAPIError: ${d.message}`):g?r.error(d,{severity:"error",errorClass:qe.Api}):r.leaveErrorBreadcrumb("[ApplePay] Unactionable error",{error:d}),a.setHasActiveApplePaySubscriptionReview(!1),!p&&a.activeSession.value?.wallet==="APPLE_PAY"?a.clearActiveSession({invokingWallet:"APPLE_PAY"}):r.leaveErrorBreadcrumb("[ApplePay] clearActiveSession skipped",{activeSession:a.activeSession.value?.wallet,isAborted:p}),s)try{s.abort()}catch{}finally{i()}},[o.asPaymentMethod,o.paymentSheetError,i,r,t,n,e,a])}const Co=["BR","KW","PA","PE","PH"];function et(e){return e.hasFlagEnabled(Wn)}function tt(e,t){if(!t)return{};const n={district:void 0,line2:void 0,subdistrict:void 0},a=e.countryCode?.toUpperCase();return!a||!Co.includes(a)||(e.subLocality&&(n.district=e.subLocality),e.addressLines?.[1]&&(n.line2=e.addressLines[1]),e.subAdministrativeArea&&(n.subdistrict=e.subAdministrativeArea)),n}const To=[He.InvalidExtensionState,He.InvalidCaptcha,He.SubmittedForCompletion];class No extends ua{constructor(t,n,a,r,o){super(),this.observability=t,this.translations=n,this.inMemoryApplePayParts=a,this.persistedApplePaySignal=r,this.reportAddressRequirementMismatch=o}get negotiationResultMapper(){return new Ht({success:({result:t,violationActions:n,defaultMapper:a})=>{if(!("errors"in t))return a();const{firstPaymentSheetAction:o}=this.getMergedPaymentSheetAction({resultViolations:t.errors,violationActions:n});return o||a()},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:a})=>
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:r}=this.getMergedPaymentSheetAction({resultViolations:t.violations,violationActions:n}),{action:o,violationCode:i}=r();return i&&this.observability.counter({name:"wallet_action_generator_handled_error",value:1,attributes:{violationCode:i,WalletName:D.ApplePay,action:o?.action??"abort",asPaymentMethod:!!a?.asPaymentMethod}}),this.reportAddressRequirementMismatch({violationCode:i,wallet:D.ApplePay,asPaymentMethod:this.inMemoryApplePayParts.asPaymentMethod.value,outcome:o?.action??"abort"}),o?(o.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:!!a?.asPaymentMethod,violationCode:i,violations:t.violations.map(s=>s.code).join(",")})),o):{action:"abort"}},invalid:({result:t,options:n})=>{const r=!!n?.applePayRecoveryFlowEnabled&&t.reasons.length>0&&t.reasons.every(i=>Qn.includes(i)),o=r?"decelerate":"abort";if(this.notifyInvalidResult(t,"completion",o),r){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:o,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,a,r,o){const{shippingContact:i}=t;if(!n)return{shouldPersist:!1};if(!i)return{shouldPersist:!1,paymentSheetAction:{action:"abort"}};const s=we(i),l=[];return a&&!s.address2&&l.push(new ApplePayError("shippingContactInvalid","addressLines",this.translations.addressLine2Blank)),r&&!s.firstName&&l.push(new ApplePayError("shippingContactInvalid","name",this.translations.firstNameBlank)),o&&!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:[...Bt,"MERCHANDISE_NOT_APPLICABLE",...ya,...kt,...ha,xt,qt],generateAction:()=>({action:"abort"})},{violations:ma,generateAction:()=>this.generateAbortAction("session_terminated")},{violations:Gt,generateAction:()=>this.generateAbortAction("shipping_options_changed")},{violations:Aa,generateAction:()=>V("emailAddress",this.translations.emailInvalidError)},{violations:["BUYER_IDENTITY_CONTACT_INFO_DOES_NOT_MATCH_CUSTOMER_PROFILE"],generateAction:()=>this.generateAbortAction("unhandled_completion_status")},{violations:_a,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:[...Pa],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:[...Ea,"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:ga,generateAction:()=>this.generateDecelerateAction()}]:[{violations:va,generateAction:()=>q("name",this.translations.nameContainsEmojisError)},{violations:fa,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",...Zn],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:Sa,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:Ca,generateAction:()=>q("postalCode",this.translations.postalCodeEmojiError)},{violations:Ta,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,...Na],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:r,shippingCountry:o}=Ra(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:r,shippingCountry:o})}]}}},{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",...jn],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:Ia,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,...Ut,...$t,"DELIVERY_WRONG_NUMBER_OF_DELIVERY_LINES",...Jt,...Kt],generateAction:()=>this.generateDecelerateAction()}]:this.getCompletionAbortViolationActions()}getCompletionAbortViolationActions(){return[{violations:[...Qt,xe,...Zt,...Ut,"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,...Bt,...kt,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,a){const r=a==="AE"?"subLocality":"administrativeArea";return new ApplePayError(n,r,a==="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,a){const{expectedReasons:r,unexpectedReasons:o}=[...new Set(t.reasons)].reduce((i,s)=>(To.includes(s)?i.expectedReasons.push(s):i.unexpectedReasons.push(s),i),{expectedReasons:[],unexpectedReasons:[]});r.length>0&&(this.observability.log("apple_pay_payment_sheet_action_generator_negotiation_rejected","wallet_rejected_negotiation",{wallet:"apple_pay",reason:"invalid",stage:n,expectedReasons:r.sort(),unexpectedReasons:o.sort(),action:a}),this.observability.counter({name:"wallet_rejected_negotiation",value:1,attributes:{wallet:"apple_pay",reason:"invalid",stage:n,expectedReasons:r.sort().join(","),hasUnexpectedReasons:!!o.length,action:a}}));for(const i of o.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:a}=te(),r=ba(),o=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 No(t,o,n,a,r),[o,n,a,t,r])}function Io(){const e=gt();return Q((t,n)=>{const{completionResultMapper:a}=e();if(!a)throw new z("CompletionResultMapper not set up correctly",{groupingHash:"ApplePayAPIError::CompletionResultMapper"});return a.mapResultToPaymentSheetAction(t,n)},[e])}function Tn({canDecelerate:e,checkout:t}){return e.value&&$n({checkout:t})}function Ro({canDecelerate:e}){const t=Jn(),{checkout:n,shop:a}=G();return an(()=>(a.hasFlagEnabled(Kn)||a.hasFlagEnabled(cn))&&Tn({canDecelerate:e,checkout:n})&&t.value)}function bo({canDecelerate:e,asPaymentMethod:t}){const n=Ro({canDecelerate:e}),{checkout:a}=G(),r=Va();return an(()=>{const o=r!==null,i=Tn({canDecelerate:e,checkout:a});return t.value?{shouldDecelerate:!1,isABTestActive:o,isCaliforniaDeceleration:!1,hasSubscription:i}:n.value?{shouldDecelerate:!0,isABTestActive:o,isCaliforniaDeceleration:!0,hasSubscription:i}:o?Xn(r)?{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 ea{};ft.type="wallet:address-replace";let pt=ft;const Do="Apple Pay active session error";function se({methodName:e,abortSignal:t,wallets:n,observability:a},r){if(t?.aborted||!n.activeSession.value){tn({observability:a},{errorName:"SessionAlreadyTerminated",methodName:e});return}try{r()}catch(o){if(o instanceof Error&&o.name==="InvalidAccessError"){tn({observability:a},{errorName:"InvalidAccessError",methodName:e});return}throw o}}function tn({observability:e},t){e.counter({name:"apple_pay_session_error",value:1,attributes:t}),e.log("apple_pay_with_active_session",Do,t),e.leaveErrorBreadcrumb("[Apple Pay] Error while calling ApplePaySession method",t,"error")}const Oo=1;function Lo(e){return e.shouldDecelerate?e.isCaliforniaDeceleration?"california":"decelerated":"none"}function Mo(){const e=Se(),t=ta(),{progress:n}=mt(),a=Ha(),r=xa(),o=fe(),i=un(),s=ve().buyerIdentity.value?.customerProfile,l=na(),A=qa(),d=Ga("APPLE_PAY"),{inMemoryApplePayParts:{asPaymentMethod:p,requirePhoneOnNextAttempt:y,requireBillingPhoneOnNextAttempt:g,paymentSheetError:h,expiresAt:E,preCompletionHandler:_,subscriptionReviewTransition:P},persistedApplePaySignal:v,walletUsedForSubmissionSignal:I}=te(),f=gt(),R=Io(),C=Et(),O=Cn(),{source:{checkoutSessionIdentifier:L},observability:m,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,ae=_t(D.ApplePay),{trackAttempt:Y}=je(D.ApplePay),x=At(p),F=ve(),re=F.buyerIdentity.value?.purchasingCompany,oe=F.availableDeliveryAddresses?.value,Z=F.mustSelectProvidedAddress?.value,he=Qe({availableDeliveryAddresses:oe,mustSelectProvidedAddress:Z}),{email:Ce,shippingAddress:ce,billingAddress:ye,paymentLines:me,deliveryLines:Ae}=We(),pe=Da(),Fe=za({shouldPersist:!0}),Te=Za({flag:sn,onAbort:Fe,onError:Ne=>{throw Ne}}
1),Ye=bo({canDecelerate:x,asPaymentMethod:p}),St=Fo();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:m},()=>de.completePayment(ApplePaySession.STATUS_FAILURE)),m.leaveErrorBreadcrumb("[ApplePay] Completion flow - clearing activeSession (abort path)"),u.clearActiveSession({invokingWallet:"APPLE_PAY"}),m.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?.()){m.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:m},()=>{S.completePayment(Pe),be=!0})}catch(Ve){e({session:S,error:Ve,isProcessing:!0})}finally{m.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=Ma(B),$={status:ApplePaySession.STATUS_FAILURE,errors:k};m.log("apple_pay_authorization_has_errors","apple_pay_authorization_has_errors",{errors:k});try{se({methodName:"completePayment",abortSignal:ie,wallets:u,observability:m},()=>S.completePayment($)),ie.aborted||$.errors.length===0?(m.leaveErrorBreadcrumb("[ApplePay] payment failed with no errors or abort action, sheet will close"),u.clearActiveSession({invokingWallet:"APPLE_PAY"}),C()):(m.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:m},()=>S.completePayment(k)),u.clearActiveSession({invokingWallet:"APPLE_PAY"}),O({status:ne.Failure,walletType:ue,endsAuthorization:!1}),ae({event:dt.RecoveryFlowInitiated,walletType:ue}),U.value&&(u.setEscalatedWallet("APPLE_PAY"),a.value.currentPage?.id==="review"&&r("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,at=j.value.isRequired("phone",{countryCode:ee(M?.countryCode)}),ot=Nt.validateBilling(Ne.payment);if(ot.shouldPersist&&ke&&!re){const B=!i.value&&at||g.value?M?.phoneNumber:void 0;g.value&&M?.phoneNumber&&m.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(ot.paymentSheetAction){Be(de,ot.paymentSheetAction);return}if(m.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,at&&!_e);if(S.shouldPersist&&M){A({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)};m.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&&Ae.value.forEach(S=>{S.value={...S.value,deliveryMethodOptions:{...S.value.deliveryMethodOptions,phone:M.phoneNumber}}}),y.value&&M?.phoneNumber&&m.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=o.current.fields.paymentDue.value;if(Rt&&Rt.amount>0||l.value){const S=me.value,{brand:B,lastFourDigits:k}=mo(It.paymentMethod.displayName);me.value=aa(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?oa(H.unstable_getSerialization("experiments")):null,Ln=Tt!==void 0&&Tt===ia(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=Lo(it);m.counter({name:"apple_pay_subscriptions_deceleration_variant",value:1,attributes:{variant:rt??ra.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()){m.leaveErrorBreadcrumb("ApplePay: Pre-completion handler failed",{asPaymentMethod:J}),Ie();return}Ct.value=!0;let le=0,Ue="",st="unexpected error",Lt=[];const wn=Oa(o.current.fields.deliveryNext?.value);try{m.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")&&m.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:at}));const Pe=$.status==="rejected"&&$.violations.some(wt=>wt.code===xe),{shouldRetry:be,retryReason:Ve,updatedDeliveryMethodHandles:Mt}=wo($,{retryCount:le,negotiated:o,originalSelectedDeliveryMethods:wn});if(be&&!Pe){Mt&&(Ge(Ae,Mt),ue===W.Express&&(m.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))),m.leaveErrorBreadcrumb(`ApplePay: retrying due to ${Ve}`,{retryCount:le}),le++,Ue=Ve,B=!ie.aborted;return}m.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?La: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&&(m.counter({name:"wallet_submit_for_completion_retry",value:1,attributes:{retry_reason:Ue||"unknown",retry_count:le,status:st,instrument:D.ApplePay}}),m.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,o,l,d,L,I,e,Y,O,C,t,re,ye,i,s?.email,A,ce,Ce,Ae,me,n,St,R,pe,u,m,v,x,Te,U,N,E,_,P,ae,he,Ye,b,T,H,w,a,r])}function nn(e,t,n){const a=tt(t,n),r=e.fields.line2;e.value={...we(t),...a},r&&"line2"in a&&(r.value=a.line2)}function wo(e,{retryCount:t,negotiated:n,originalSelectedDeliveryMethods:a}){const r={shouldRetry:!1,retryReason:"",updatedDeliveryMethodHandles:void 0};if(e.status!=="rejected"||t>=Oo)return r;const o=wa(e,n.current.fields.deliveryNext?.peek(),a);return o?{shouldRetry:!0,retryReason:"delivery_option_mismatch",updatedDeliveryMethodHandles:o}:r}function Fo(){const{negotiate:e}=mt(),{checkout:{wallets:t},observability:n}=G();return Q(async(a,r)=>{let o=!1,i,s;try{await e({runListenersOnError:!0,fieldsToResolve:["deliveryNext"],onComplete:p=>{if(p.status==="success"||p.status==="error"||p.status==="invalid"){o=!0;return}i=p.status}})}catch(p){o||(s=p)}const l=a.aborted||!t.activeSession.value;if(o&&!l)return!0;let A="rejected";l?A="session_ended":i&&(A="unsettled_status");const d={result:"failed",reason:A,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)}),r(),!1},[e,t,n])}function vt(){const e=gt();return Q((t,n)=>{const{negotiationResultMapper:a}=e();if(!a)throw new z("NegotiationResultMapper not set up correctly",{groupingHash:"ApplePayAPIError::NegotiationResultMapper"});return a.mapResultToPaymentSheetAction(t,n)},[e])}function Yo(e,t,{interfaceFlow:n,isConstrainedAddress:a=!1,deliveryAddressOptions:r}={}){return a?e:{...e,delivery:{...e.delivery,interfaceFlow:n,useProgressiveRates:!1,deliveryLines:(e.delivery?.deliveryLines??[]).map(o=>({...o,destination:{partialStreetAddress:$a(t,r)}}))}}}function Bo(){const{observability:e,checkout:{wallets:t,address:{countryDetails:n,extendedAddressMode:a}},checkout:r,shop:o}=G(),i=et(o),s=Se(),l=Et(),A=vt(),d=Ze(),p=fe(),y=_t(D.ApplePay),g=yt(),{formattedRecurringTotalTooltip:h,lineItemsLabels:E,deliveryOptionGroupTypeLabels:_,deliveryMethodTitlePrefixes:P}=Xe();return Q(async(v,I,f,R)=>{const{billingContact:C}=v.paymentMethod;if(!r.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=>ko(u,C,{deliveryAddressOptions:{extendedAddressMode:a},extendedAddressFieldsEnabled:i}),observability:e,onComplete:m,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 m(u){if(t.activeSession.value&&!f.aborted&&(e.leaveErrorBreadcrumb("ApplePay: completed negotiation",{action:"paymentMethodSelected",status:u.status}),C)){const b=A(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())}}r.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,A,E,p,r.isShippingRequired,e,s,y,g,a,n,i])}const ko=(e,t,{deliveryAddressOptions:n,extendedAddressFieldsEnabled:a=!1}={})=>Yo(e,{...we(t),...tt(t,a)},{interfaceFlow:"APPLE_PAY",deliveryAddressOptions:n});function Nn(){const e=Et(),t=G(),{checkout:{wallets:n},observability:a}=t;return Q(({session:r,paymentSheetAction:o,onProceed:i,abortSignal:s})=>{switch(o.action){case"abort":se({methodName:"abort",abortSignal:s,wallets:n,observability:a},()=>r.abort()),n.clearActiveSession({invokingWallet:"APPLE_PAY"}),e();break;case"update":i(o.errors);break;case"no-op":i();break;default:throw new z(`Missing handler for payment sheet action "${o.action}"`,{groupingHash:"ApplePayAPIError::MissingHandlerPaymentSheetAction"})}},[e,n,a])}function Uo(){const e=Se(),t=Ze(),n=vt(),a=fe(),r=hn(),{inMemoryApplePayParts:{initialDeliveryIdentifier:o,asPaymentMethod:i}}=te(),{deliveryLines:s,shippingAddress:l}=We(),A=yt(),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:m,connectTwoShippingTitles:u}=Xe(),b=Nn(),{shouldGateCrossBorder:c,crossBorderGate:w}=la(),N=At(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 ae=H.shippingContact.countryCode?ee(H.shippingContact.countryCode):void 0;if(Ge(s,void 0),o.value=void 0,c(ae)){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:ae});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=ae});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 A({abortSignal:j,fieldsToResolve:["deliveryNext","duties","taxes"],customizeNegotiation:F=>dn(F,U,{interfaceFlow:"APPLE_PAY",isPickupSelected:r.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:oe,recurringTotals:Z,deliveryNext:he,...Ce}=Le(a);if(oe==null)return e({session:F,error:new z("Missing negotiated payment due",{groupingHash:"ApplePayAPIError::MissingNegotiatedPaymentDue"})});const ce=Ke(oe.currencyCode);try{const ye={newTotal:Je(O.total,oe),newLineItems:$e({...Ce,formattedRecurringTotals:t(Z),formattedRecurringTotalTooltip:C,lineItemsLabels:O,deliveryOptionGroupTypeLabels:L,deliveryMethodTitlePrefixes:m})},me=En({deliveryMethodTitlePrefixes:m,connectTwoShippingTitles:u,deliveryNext:he}),Ae={...ye,newShippingMethods:me};se({methodName:"completeShippingContactSelection",abortSignal:j,wallets:_,observability:v},()=>F.completeShippingContactSelection({errors:re,...ce?Pt(Ae):Ae}));try{const pe=Vo(he,re);if(!pe)return;const Fe=me.find(Te=>pe.every(Ye=>Te.identifier.includes(Ye)))?.identifier;Fe&&(o.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 oe=n(F,{shippingCountryCode:ee(H.shippingContact.countryCode),...re&&{options:{applePayRecoveryFlowEnabled:re}}});oe.effects?.forEach(Z=>Z()),v.leaveErrorBreadcrumb("ApplePay: Payment sheet action",{action:"shippingContactSelected",paymentSheetAction:oe.action}),b({session:T,paymentSheetAction:oe,onProceed:Z=>Y(T,Z),abortSignal:j})}},[s,l,r,n,b,a,e,O,t,C,L,m,u,o,A,_,v,N,h,p,g,c,w,R,I,f])}function Vo(e,t){if(t?.length||!e||e.status!=="filled"||!e.lines?.length)return;const n=e.lines.reduce((a,r)=>(r.status==="available"&&r.selectedDeliveryMethodHandle&&a.push(r.selectedDeliveryMethodHandle),a),[]);if(!(n.length<e.lines.length))return n}function Ho(){const e=Se(),t=Ze(),n=vt(),a=fe(),r=hn(),{observability:o,checkout:{wallets:i,address:{countryDetails:s,extendedAddressMode:l}},shop:A}=G(),d=et(A),{inMemoryApplePayParts:{initialDeliveryIdentifier:p}}=te(),{deliveryLines:y,shippingAddress:g}=We(),h=_t(D.ApplePay),E=yt(),_=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(),m=Nn();return Q(async(u,b,c)=>{const w=p.value;p.value=void 0;const N=u.shippingMethod.identifier===w;o.counter({name:"apple_pay_skip_initial_delivery_negotiation",value:1,attributes:{skippedNegotiation:N}}),!N&&w&&o.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 Fa(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),o.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=>dn(Y,T,{interfaceFlow:"APPLE_PAY",isPickupSelected:r.value,isConstrainedAddress:f,availableDeliveryAddresses:P,negotiatedDelivery:I,deliveryAddressOptions:{extendedAddressMode:l}}),observability:o,walletName:D.ApplePay,onComplete:ae,logPrefix:"ApplePay::useOnShippingMethodSelected"})}catch(Y){e({session:b,error:Y})}function U(Y){const{paymentDue:x,recurringTotals:F,...re}=Le(a);if(x==null)return e({session:Y,error:new z("Missing negotiated payment due",{groupingHash:"ApplePayAPIError::MissingNegotiatedPaymentDue"})});const oe=Ke(x.currencyCode);try{se({methodName:"completeShippingMethodSelection",abortSignal:c,wallets:i,observability:o},()=>{const Z={newTotal:Je(C.total,x),newLineItems:$e({...re,formattedRecurringTotals:t(F),formattedRecurringTotalTooltip:R,lineItemsLabels:C,deliveryOptionGroupTypeLabels:O,deliveryMethodTitlePrefixes:L})};Y.completeShippingMethodSelection(oe?Pt(Z):Z)}),K.endAndRun("apple-pay-sheet-load",Z=>{h({event:dt.SheetLoaded,ttl:Z}),o.histogram({name:"wallet_sheet_loaded",value:Z,attributes:{instrument:D.ApplePay}})})}catch(Z){Z instanceof Error&&e({error:Z,session:Y})}}function ae(Y){if(i.activeSession.value&&!c.aborted){o.leaveErrorBreadcrumb("ApplePay: completed negotiation",{action:"shippingMethodSelected",status:Y.status});try{const x=n(Y,{shippingCountryCode:T.countryCode});x.effects?.forEach(F=>F()),o.leaveErrorBreadcrumb("ApplePay: Payment sheet action",{action:"shippingMethodSelected",paymentSheetAction:x.action}),m({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,m,r,C,a,y,g,e,o,h,p,E,f,P,I,s,d,l])}function xo(){const e=Me(D.ApplePay),t=Se(),{shop:n,source:{sourceId:a},observability:r,checkout:{wallets:o},embed:i,graphql:{coreGraphql:s}}=G(),l=vn({embed:i,isCrossOriginIframeEnabled:n.hasFlagEnabled(pn)}),{inMemoryApplePayParts:{prefetchPaymentSession:A}}=te(),d=Wa(D.ApplePay);return Q((p,y,g,h)=>{const E=h===A.value?.prefetchUrl;r.histogram({name:"apple_pay_prefetch_session",value:K.end("apple-pay-session-begin"),attributes:{prefetch:E?"success":"retried"}}),_().then(P=>{if(A.value=void 0,P instanceof _n){r.leaveErrorBreadcrumb("[ApplePay] Validation query returned failed response",{reason:P.reason}),r.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=o.activeSession.value?.wallet==="APPLE_PAY";r.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:o,observability:r},()=>p.completeMerchantValidation(JSON.parse(P.body)))}).catch(P=>{t({error:P,session:p,isAborted:g.aborted})});async function _(){if(A.value)try{const P=await A.value.prefetchPromise;if(E&&P)return P;E&&!P?r.leaveErrorBreadcrumb("[ApplePay] session query prefetch returned no data - starting new validation query",{validationUrl:h,prefetchUrl:A.value?.prefetchUrl}):E||r.leaveErrorBreadcrumb("[ApplePay] session query prefetch URL mismatch - starting new validation query",{validationUrl:h,prefetchUrl:A.value?.prefetchUrl})}catch(P){if(P instanceof ut)return;r.log("apple_pay_on_validate_merchant","Apple Pay prefetch session error",{error:P,prefetchValidationUrl:A.value?.prefetchUrl,validationUrl:h})}return r.leaveErrorBreadcrumb("[ApplePay] starting new session query",{hadPrefetch:!!A.value,validationUrl:h}),Pn({graphql:s,sourceId:a,validationUrl:h,asPaymentMethod:y,signal:g,observability:r,isPrefetch:!1,domain:l})}},[s,a,r,e,d,t,A,o,l])}function In(){const e=Se(),t=fe(),n=Me(D.ApplePay),{inMemoryApplePayParts:{asPaymentMethod:a,paymentSheetError:r,prefetchPaymentSession:o}}=te(),{shop:i,source:{sourceId:s},observability:l,embed:A,graphql:{coreGraphql:d}}=G(),{countryCode:p}=i,y=vn({embed:A,isCrossOriginIframeEnabled:i.hasFlagEnabled(pn)}),g=Eo(),h=Qa().geolocation.country.code,E=fo(h),_=So(),P=xo(),v=Bo(),I=Ho(),f=Uo(),R=Mo();return Q(({asPaymentMethod:C=!1,supportedNetworks:O,waitForTotalsToSettle:L,isPaymentAuthorizationBlocked:m,subscriptionConsent:u})=>{K.start("apple-pay-session-begin"),r.value=void 0,a.value=C;const b=Bn(!1),c=new AbortController,{paymentDue:w}=Le(t);if(!w)return n(ne.Failure,C?W.PaymentMethod:W.Express),r.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"};o.value||(o.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(sa,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,m,u),{session:N,error:void 0}},[a,g,t,r,_,R,v,f,I,P,p,e,n,o,E,d,l,s,y])}const qo=5e3;function Go(e,t){return t.aborted?Promise.resolve(!1):e.value?new Promise(n=>{let a=!1,r=()=>{};const o=l=>{a||(a=!0,r(),t.removeEventListener("abort",i),clearTimeout(s),n(l))},i=()=>o(!1);t.addEventListener("abort",i,{once:!0});const s=setTimeout(i,qo);r=e.subscribe(l=>{l||o(!0)}),a&&r(),t.aborted&&i()}):Promise.resolve(!0)}function Rn(){const{inMemoryApplePayParts:{asPaymentMethod:e,expiresAt:t}}=te(),{observability:n,checkout:{wallets:a}}=G(),r=At(e);return Q(o=>
1{if(o){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{o.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}r.value&&(t.value=new Date(Date.now()+300*1e3).toISOString()),a.setActiveSession({newValue:"APPLE_PAY",asPaymentMethod:e.value})}},[e,n,a,r,t])}const zo=new Set(ln);function Wo(){const{negotiate:e}=mt(),{observability:t,shopPay:n,checkout:{wallets:a,identity:r}}=G(),o=r.current.value==="shopPay",{inMemoryApplePayParts:{isLoadingPaymentSheet:i,paymentSheetError:s}}=te(),l=o?D.ShopPayApplePay:D.ApplePay,A=In(),d=Me(l),p=Ja(),y=yn(),{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(o){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})=>zo.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 Go(g,f).then(C=>(t.histogram({name:"apple_pay_shop_offer_reconciliation_wait_duration",value:Date.now()-R,attributes:{reconciled:C}}),C))};return async({disabled:f=!1,isMountedRef:R,validateButtonPress:C})=>{if(!f){d(ne.Clicked,W.PaymentMethod);try{const O=A({asPaymentMethod:!0,supportedNetworks:P||[],waitForTotalsToSettle:I,isPaymentAuthorizationBlocked:()=>g.value}),L=await v(C),m=R?R.current:!0;L&&!a.activeSession.value&&m&&h(O.session)}catch(O){t.leaveErrorBreadcrumb("Failed to create Apple Pay session",{error:O,shopPay:o}),s.value={type:"failed_to_create_session"},a.activeSession.value?.wallet==="APPLE_PAY"&&a.clearActiveSession({invokingWallet:"APPLE_PAY"})}}}}function pr(){const{applePaySessionHandler:e,inMemoryApplePayParts:t}=te(),n=ct(Wo()),a=ct(In()),r=ct(Rn());return kn(()=>{if(t.sessionLoadFailed.value)return;const o={onClickHandler:(...i)=>n.current(...i),createSession:(...i)=>a.current(...i),showApplePayPaymentSheet:(...i)=>r.current(...i)};return e.value=o,()=>{e.value=void 0}},[e,n,a,r,t]),null}export{pr 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.