PageSourceSearch

https://www.linksys.com/cdn/shopifycloud/checkout-web/assets/c1/component-WalletApplePayLazy.DQG9_qyy.js

js linksys.com collected 2026-09-24 08:39:55 UTC 70,117 bytes, 1 lines download raw bytes

1import{U as Yn,T as Ee,q as Q,f as an,y as Bn,h as kn}from"./esnext-vendor.D7ldIee_.js";import{cD as Ft,x as Yt,dH as Un,gS as on,j as Vn,gR as lt,g$ as rn,aW as Hn,aG as xn,gT as qn,gU as Gn,dg as zn,b0 as Wn,N as G,hP as Qn,$ as ve,O as We,ac as fe,ab as te,gW as Qe,hQ as Zn,hR as sn,hS as $n,hT as jn,hi as Jn,bk as He,cV as Bt,hU as kt,de as Xn,df as Kn,hV as ln,gX as xe,C as Ut,aV as ea,hW as ta,hX as na,hY as cn,hZ as aa,gp as oa,h_ as ra,a0 as dt,aa as ia,ae as sa,cc as ge,r as la,h$ as ca,i0 as pa,i1 as da,i2 as pn,i3 as ua}from"./addresses-is-address-empty.-MuOhIyI.js";import{a as D,b as W,c as ne,W as ut}from"./Monorail-monorailMetric-wallets.C3kHkAxp.js";import{a as yt,I as Oe,W as Vt,b as z}from"./apple-pay-errors.CcNuwNMC.js";import{f as K,g as ya,s as ha,r as Le,B as Aa,P as Ht,U as ma,a as _a,v as xt,w as qt,i as Pa,N as Gt,E as Ea,h as ga,x as va,y as fa,z as Sa,A as Ca,C as Ta,F as Na,l as zt,G as Ia,H as Ra,J as Wt,K as ba,L as Da,j as Oa,T as Qt,M as Zt,O as $t,D as jt,V as Jt,I as Xt,Q as Kt,u as La,m as Ma,n as wa,R as Fa,o as Ya,p as ht,q as dn,t as Ba}from"./wallets-deserialize-delivery-handles.BetPukh8.js";import{fb as ka,ge as un,gf as Ze,gg as At,c6 as yn,gh as qe,c1 as Ua,fe as Va,fN as Ha,fc as xa,f$ as mt,gi as qa,fM as Ge,cV as hn,eY as Ga,ce as za,fg as ct}from"./hydrate.ByRIsqvd.js";import{b as X}from"./app.A60-IfPs.js";import{a as Me,b as An,u as _t}from"./shop-pay-installments-monorail.cv2DVyY3.js";import{u as $e,a as Wa}from"./hooks-useWalletsThreePageVaultedReviewEscalation.DXszpNvO.js";import{d as Qa}from"./shared-report-graphql-error.CaKFFhiw.js";import{d as Za}from"./hooks-useHasOrdersFromMultipleShops.PKFq4ktR.js";import{u as $a}from"./shipping-methods-grouping.DDWlTvqo.js";import{u as ja}from"./hooks-payment-button.D5UAY6lK.js";import"./hooks-useCanChangeCompanyLocation.Bk004VMP.js";import"./constants.DowbVE6J.js";import"./hooks-useReplaceShopPayInHistory.Cz4PqGkk.js";import"./graphql-PaymentSessionMutation.CK_JkOwG.js";const Ja={id:"1501fe0af4559751b078e255872e602b9742658e6ef2d8b73091b38649adb321",type:"query",name:"ApplePayPaymentSession",source:""},mn=5,Xa=4,Ka=mn+Xa,eo=600;class _n{constructor(t){this.reason=t}}class en extends Error{constructor(){super(...arguments),this.name="ApplePaySessionCreationResponseError"}}const to=({sourceId:e,isPrefetch:t})=>t?`${e}-prefetch-${Yt()}`:`${e}-${Yt()}`,Pn=async({graphql:e,sourceId:t,validationUrl:n,asPaymentMethod:a,signal:o,observability:r,isPrefetch:i,domain:s})=>{const l=to({sourceId:t,isPrefetch:i}),m=async h=>{const{data:E,error:_}=await e.staticQuery(Ja,{cache:!1,variables:h?{pendingTask:{taskId:h}}:{applePaySessionCreate:{resourceId:l,validationUrl:n,domain:s,walletInstrumentation:{expressWalletInCheckout:!a}}}});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(o.aborted)throw new yt("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=eo-P;v>0&&await Ft(v)}if(p=_.taskId,y++,y>=Ka)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 Ft(_.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}},no={EG:"EG",AE:"AE"};
1function je({subtotal:e,duties:t,taxes:n,deliveryNext:a,discountLines:o,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:ya(c),amount:K(c.totalPrice.amount)})});const E=e===void 0?[]:[{label:l.subtotal,amount:e?K(e.amount):void 0}],_=ao({deliveryNext:a,deliveryOptionGroupTypeLabels:m,deliveryMethodTitlePrefixes:d}),P=t&&t?.status==="available_total"&&t?.totalDuty.amount!==0?[{label:l.duties,amount:K(t.totalDuty.amount)}]:[],v=n&&n.status==="available_total"&&n.totalTax.amount!==0?[{label:l.taxes,amount:K(n.totalTax.amount)}]:[],I=o&&o.lines.map(c=>{if(Vn(c)){const w=c.amount?.amount;if(w)return{label:c.title,amount:lt(K(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(K(T))}]:[]})??[],O=r?.lines.filter(c=>c.method.type==="giftCard").map(c=>c.cost?{label:l.giftCards,amount:lt(K(c.cost.amount))}:void 0).filter(c=>c!==void 0)||[],L=i&&i[0],A=L&&L.amount.amount>0?[{label:l.tip,amount:K(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 ao({deliveryNext:e,deliveryOptionGroupTypeLabels:t,deliveryMethodTitlePrefixes:n}){const a=rn(e);return a?a.map(({totalCost:o})=>({label:n.SHIPPING,amount:K(o.amount)})):zn(e).map(({line:o,method:r},i,s)=>({label:oo(o,r,s.length===1,t,n),amount:K(r.cost.amount)}))}function oo(e,t,n,a,o){const r=o[t.methodType];return n?r:`${r} (${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:m,deliveryPromisePresentmentTitle:d})=>({label:s,amount:K(l.amount),detail:d?.short??"",identifier:JSON.stringify(m)}));const o=Hn(n).filter(xn).map(qn),r=Gn(o).filter(s=>s.length>0);return ro(n,r).map(s=>({label:so(s,e,t),amount:lo(s),detail:po(s,t),identifier:ha(s)}))}function ro(e,t){if(!e||e.status!=="filled"||!Wn(e))return t;const n=new Set(e.lines.reduce((o,r)=>(r.status==="available"&&r.selectedDeliveryMethodHandle&&o.add(r.selectedDeliveryMethodHandle),o),new Set)),a=t.find(o=>o.every(r=>n.has(r.handle)));return a?[a,...t.filter(o=>o!==a)]:t}const io=", ";function gn(e,t){const n=e.values(),a=n.next();if(a.done)return"";const o=n.next();if(o.done)return a.value;let r=a.value,i=o.value;for(const s of n)r+=`${io}${i}`,i=s;return t(r,i)}function so(e,t,n){const a=e.find(l=>l.deliveryLine.type==="ONE_TIME_PURCHASE");let o="";a&&(o=a.methodType==="PICK_UP"?t[a.methodType]:a.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,o=a?.title??""}const s=[...new Set([o,i])];return gn(s.filter(Boolean),n)}function lo(e){return K(e.reduce((t,n)=>t+n.costAfterDiscounts.amount,0))}function co(e,t){return e.add(t),e}function po(e,t){return gn([...e.map(n=>{const{methodType:a,pickupLocation:o,deliveryPromisePresentmentTitle:r,description:i}=n;return a==="PICK_UP"||a==="PICKUP_POINT"?yo(o?.address)??"":r?r.short:i||""}).reduce(co,new Set)],t)}function Je(e,t){return{label:e,amount:K(t.amount)}}function uo({phoneRequired:e,emailRequired:t,shippingRequired:n}){const a=["name","postalAddress"],o=[...e?["phone"]:[],...t?["email"]:[]];return{requiredShippingContactFields:n?[...a,...o]:o,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(no).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 yo(e){if(e){const{address1:t="",address2:n="",city:a="",company:o="",zoneCode:r="",countryCode:i=""}
1=e,s=[t,n].filter(Boolean).join(" ");return[o,s,a,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 ho(e){const t={brand:"",lastFourDigits:""};if(!e)return t;const n=e.split(" ");if(n.length!==2)return t;const[a,o]=n;if(a===void 0||o===void 0)return t;for(const r of a.toLowerCase())if(r<"a"||r>"z")return t;return Number.isNaN(Number(o))?t:{brand:a,lastFourDigits:o}}const Ao=new Set(["HUF","RSD"]);function mo(e){return Ao.has(e)}function Xe(e){return e!==void 0&&mo(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 _o(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 Ke(){const{i18n:e,shop:t}=G(),{name:n}=t,a=e.translate("order_summary.recurring_total_tooltip"),o=t.hasFlagEnabled(Qn),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"),...o&&{flashDeal:e.translate("order_summary.flash_deal")},giftCards:e.translate("order_summary.gift_card_label"),tip:e.translate("order_summary.tip_label")}),[n,e,o]),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:a,lineItemsLabels:r,deliveryOptionGroupTypeLabels:i,deliveryMethodTitlePrefixes:s,connectTwoShippingTitles:l}),[a,r,i,s,l])}function Po(){const{checkout:e,observability:t}=G(),n=e.configuration.addressSettings.nonBillingAddressSettings.value,a=ka(),o=ve(),r=n.isRequired("phone",{countryCode:ee(o.buyerIdentity.value?.countryCode)}),i=un(),{value:s}=o.deliveryNext,l=We(),m=fe(),d=Ze(),{paymentDue:p,recurringTotals:y,...g}=Le(m),h=Ke(),{deliveryMethodTitlePrefixes:E,connectTwoShippingTitles:_}=h,P=o.availableDeliveryAddresses?.value,v=o.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}=uo({phoneRequired:Eo({asPaymentMethod:L,phoneRequired:r,shouldRequestPhoneOnRetry:A,shopPayOptInExists:u}),emailRequired:go({asPaymentMethod:L,emailRequired:a.value,shopPayOptInExists:u,proposedEmailExists:b}),shippingRequired:w?!1:i.value}),T=Je(h.lineItemsLabels.total,p),$=je({...g,formattedRecurringTotals:d(y),...h}),U=w?[]:En({deliveryMethodTitlePrefixes:E,connectTwoShippingTitles:_,deliveryNext:s}),ae={total:T,currencyCode:p.currencyCode,countryCode:O,lineItems:$,shippingMethods:U,shippingType:"shipping",merchantCapabilities:["supports3DS"],supportedNetworks:C,requiredShippingContactFields:N,requiredBillingContactFields:H};return Xe(p.currencyCode)?_o(ae):ae},[I,f,R,_,E,s,a,P,d,h,v,g,p,r,y,i,t,l])}const Eo=({asPaymentMethod:e,phoneRequired:t,shouldRequestPhoneOnRetry:n,shopPayOptInExists:a})=>e?a:t||n,go=({asPaymentMethod:e,emailRequired:t,shopPayOptInExists:n,proposedEmailExists:a})=>e?!a&&n:t;function vo(e){const t="apple-pay-gateway.apple.com/paymentservices/startSession";return e==="CN"?`https://cn-${t}`:`https://${t}`}function fo(){const e=Me(D.ApplePay),{trackComplete:t}=$e(D.ApplePay),n=At(),{inMemoryApplePayParts:a}=te(),{checkout:o,observability:r,shop:i}=G(),s=yn();return Q((l,m)=>{l.abort(),a.prefetchPaymentSession.value=void 0;const d=m.value,p=a.asPaymentMethod.value,y=p?W.PaymentMethod:W.Express;X.remove("apple-pay-sheet-load"),X.exists("apple-pay-authorization")&&t({result:"failed",durationMs:X.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}),a.requirePhoneOnNextAttempt.value&&r.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&&$n({applePaySubscriptionsDecelerationActive:g,applePayThreePageVaultedReviewEnabled:h,isOnePageCheckout:o.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:_}),a.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:_}),o.wallets.activeSession.value?.wallet==="APPLE_PAY"&&o.wallets.clearActiveSession({invokingWallet:"APPLE_PAY"}),_)return;n()}e(ne.Cancelled)},[n,a.asPaymentMethod,a.paymentSheetError,a.subscriptionReviewTransition,a.requirePhoneOnNextAttempt,a.prefetchPaymentSession,t,e,r,i,o,s])}function Cn(){const{observability:e}
1=G(),t=An(D.ApplePay),{trackComplete:n}=$e(D.ApplePay);return Q(({status:a,walletType:o,endsAuthorization:r=!0})=>{if(e.counter({name:"apple_pay_payment_status",value:1,attributes:{status:a,wallet_type:o}}),t(a,o),a===ne.Attempt)return;if(!r){X.remove("apple-pay-authorization");return}const i=a===ne.Success?"success":"failed";X.endAndRun("apple-pay-authorization",s=>{n({result:i,durationMs:s,walletType:o,attributes:{walletType:o}}),e.log("apple_pay_payment_status_updated","Apple Pay payment authorization status update received",{result:i,status:a,walletType:o})})},[e,t,n])}function Et(){const e=At(),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=An(D.ApplePay),{trackComplete:n}=$e(D.ApplePay),{checkout:{wallets:a},observability:o}=G(),{inMemoryApplePayParts:r}=te(),i=At();return Q(({session:s,isProcessing:l=!1,isMessagingHandledElsewhere:m=!1,error:d,isAborted:p})=>{if(d instanceof yt)return;X.remove("apple-pay-sheet-load");const y=r.asPaymentMethod.value?W.PaymentMethod:W.Express;o.counter({name:"apple_pay_session_terminated",value:1,attributes:{error_type:d.name,wallet_type:y}}),o.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}),X.exists("apple-pay-authorization")?(t(ne.Failure,y),n({result:"failed",durationMs:X.end("apple-pay-authorization"),walletType:y})):(e(ne.Failure,y),o.counter({name:"wallet_sheet_failed",value:1,attributes:{instrument:D.ApplePay}})),!l&&!m&&(r.paymentSheetError.value={type:"session_terminated"});const{actionable:g}=Qa(d);if(d instanceof Oe?o.leaveErrorBreadcrumb(`IgnoredApplePayAPIError: ${d.message}`):g?o.error(d,{severity:"error",errorClass:qe.Api}):o.leaveErrorBreadcrumb("[ApplePay] Unactionable error",{error:d}),a.setHasActiveApplePaySubscriptionReview(!1),!p&&a.activeSession.value?.wallet==="APPLE_PAY"?a.clearActiveSession({invokingWallet:"APPLE_PAY"}):o.leaveErrorBreadcrumb("[ApplePay] clearActiveSession skipped",{activeSession:a.activeSession.value?.wallet,isAborted:p}),s)try{s.abort()}catch{}finally{i()}},[r.asPaymentMethod,r.paymentSheetError,i,o,t,n,e,a])}const So=["BR","KW","PA","PE","PH"];function et(e){return e.hasFlagEnabled(jn)}function tt(e,t){if(!t)return{};const n={district:void 0,line2:void 0,subdistrict:void 0},a=e.countryCode?.toUpperCase();return!a||!So.includes(a)||(e.subLocality&&(n.district=e.subLocality),e.addressLines?.[1]&&(n.line2=e.addressLines[1]),e.subAdministrativeArea&&(n.subdistrict=e.subAdministrativeArea)),n}const Co=[He.InvalidExtensionState,He.InvalidCaptcha,He.SubmittedForCompletion];class To extends Aa{constructor(t,n,a,o){super(),this.observability=t,this.translations=n,this.inMemoryApplePayParts=a,this.persistedApplePaySignal=o}get negotiationResultMapper(){return new Ht({success:({result:t,violationActions:n,defaultMapper:a})=>{if(!("errors"in t))return a();const{firstPaymentSheetAction:r}=this.getMergedPaymentSheetAction({resultViolations:t.errors,violationActions:n});return r||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:o}=this.getMergedPaymentSheetAction({resultViolations:t.violations,violationActions:n}),{action:r,violationCode:i}=o();return i&&this.observability.counter({name:"wallet_action_generator_handled_error",value:1,attributes:{violationCode:i,WalletName:D.ApplePay,action:r?.action??"abort",asPaymentMethod:!!a?.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:!!a?.asPaymentMethod,violationCode:i,violations:t.violations.map(s=>s.code).join(",")})),r):{action:"abort"}},invalid:({result:t,options:n})=>{const o=!!n?.applePayRecoveryFlowEnabled&&t.reasons.length>0&&t.reasons.every(i=>Jn.includes(i)),r=o?"decelerate":"abort";if(this.notifyInvalidResult(t,"completion",r),o){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,a,o,r){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)),o&&!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:[...Bt,"MERCHANDISE_NOT_APPLICABLE",...ma,...kt,..._a,xt,qt],generateAction:()=>({action:"abort"})},{violations:Pa,generateAction:()=>this.generateAbortAction("session_terminated")},{violations:Gt,generateAction:()=>this.generateAbortAction("shipping_options_changed")},{violations:Ea,generateAction:()=>V("emailAddress",this.translations.emailInvalidError)},{violations:["BUYER_IDENTITY_CONTACT_INFO_DOES_NOT_MATCH_CUSTOMER_PROFILE"],generateAction:()=>this.generateAbortAction("unhandled_completion_status")},{violations:ga,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:[...va],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:[...fa,"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:Sa,generateAction:()=>this.generateDecelerateAction()}]:[{violations:Ca,generateAction:()=>q("name",this.translations.nameContainsEmojisError)},{violations:Ta,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",...Xn],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:Na,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:Ia,generateAction:()=>q("postalCode",this.translations.postalCodeEmojiError)},{violations:Ra,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,...ba],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:o,shippingCountry:r}=Oa(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:o,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",...Kn],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:Da,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"}})}
1,{violations:[...ln,xe,...Zt,...$t,...Ut,...jt,"DELIVERY_WRONG_NUMBER_OF_DELIVERY_LINES",...Jt,...Xt],generateAction:()=>this.generateDecelerateAction()}]:this.getCompletionAbortViolationActions()}getCompletionAbortViolationActions(){return[{violations:[...Qt,xe,...Zt,...Ut,"DELIVERY_COMPANY_REQUIRED"],generateAction:()=>({action:"abort"})},{violations:$t,generateAction:()=>this.generateAbortAction("session_terminated")},{violations:jt,generateAction:()=>this.generateAbortAction("unusable_partial_address")},{violations:["DELIVERY_WRONG_NUMBER_OF_DELIVERY_LINES",...Jt],generateAction:()=>this.generateAbortAction("unhandled_completion_status")},{violations:Xt,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:[...Kt,"DELIVERY_INVALID_POSTAL_CODE_FOR_COUNTRY","DELIVERY_INVALID_POSTAL_CODE_FOR_ZONE"],generateAction:()=>({action:"no-op"})}]:[{violations:Kt,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 o=a==="AE"?"subLocality":"administrativeArea";return new ApplePayError(n,o,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}]}}notifyInvalidResult(t,n,a){const{expectedReasons:o,unexpectedReasons:r}=[...new Set(t.reasons)].reduce((i,s)=>(Co.includes(s)?i.expectedReasons.push(s):i.unexpectedReasons.push(s),i),{expectedReasons:[],unexpectedReasons:[]});o.length>0&&(this.observability.log("apple_pay_payment_sheet_action_generator_negotiation_rejected","wallet_rejected_negotiation",{wallet:"apple_pay",reason:"invalid",stage:n,expectedReasons:o.sort(),unexpectedReasons:r.sort(),action:a}),this.observability.counter({name:"wallet_rejected_negotiation",value:1,attributes:{wallet:"apple_pay",reason:"invalid",stage:n,expectedReasons:o.sort().join(","),hasUnexpectedReasons:!!r.length,action:a}}));for(const i of r.sort())this.observability.error(new z(`Intercepted ${n}
1 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(),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 To(t,o,n,a),[o,n,a,t])}function No(){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&&ea({checkout:t})}function Io({canDecelerate:e}){const t=ta(),{checkout:n,shop:a}=G();return an(()=>(a.hasFlagEnabled(na)||a.hasFlagEnabled(cn))&&Tn({canDecelerate:e,checkout:n})&&t.value)}function Ro({canDecelerate:e,asPaymentMethod:t}){const n=Io({canDecelerate:e}),{checkout:a}=G(),o=Ua();return an(()=>{const r=o!==null,i=Tn({canDecelerate:e,checkout:a});return t.value?{shouldDecelerate:!1,isABTestActive:r,isCaliforniaDeceleration:!1,hasSubscription:i}:n.value?{shouldDecelerate:!0,isABTestActive:r,isCaliforniaDeceleration:!0,hasSubscription:i}:r?aa(o)?{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 oa{};ft.type="wallet:address-replace";let pt=ft;const bo="Apple Pay active session error";function se({methodName:e,abortSignal:t,wallets:n,observability:a},o){if(t?.aborted||!n.activeSession.value){tn({observability:a},{errorName:"SessionAlreadyTerminated",methodName:e});return}try{o()}catch(r){if(r instanceof Error&&r.name==="InvalidAccessError"){tn({observability:a},{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",bo,t),e.leaveErrorBreadcrumb("[Apple Pay] Error while calling ApplePaySession method",t,"error")}const Do=1;function Oo(e){return e.shouldDecelerate?e.isCaliforniaDeceleration?"california":"decelerated":"none"}function Lo(){const e=Se(),t=ra(),{progress:n}=dt(),a=ia(),o=Va(),r=fe(),i=un(),s=ve().buyerIdentity.value?.customerProfile,l=sa(),m=Ha(),d=xa("APPLE_PAY"),{inMemoryApplePayParts:{asPaymentMethod:p,requirePhoneOnNextAttempt:y,requireBillingPhoneOnNextAttempt:g,paymentSheetError:h,expiresAt:E,preCompletionHandler:_,subscriptionReviewTransition:P},persistedApplePaySignal:v,walletUsedForSubmissionSignal:I}=te(),f=gt(),R=No(),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),$=c.addressSettings.nonBillingAddressSettings,U=c.layout.isOnePage,ae=_t(D.ApplePay),{trackAttempt:Y}=$e(D.ApplePay),x=mt(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:Ae,deliveryLines:me}=We(),pe=La(),Fe=qa({shouldPersist:!0}),Te=Wa({flag:sn,onAbort:Fe,onError:Ne=>{throw Ne}}
1),Ye=Ro({canDecelerate:x,asPaymentMethod:p}),St=wo();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}),X.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,j=k?.walletOrderTypeIdentifier&&k?.walletServiceUrl&&k?.walletAuthenticationToken,Pe=L&&j?{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=Fa(B),j={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(j)),ie.aborted||j.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}),ae({event:ut.RecoveryFlowInitiated,walletType:ue}),U.value&&(u.setEscalatedWallet("APPLE_PAY"),a.value.currentPage?.id==="review"&&o("payment-methods",{replace:!0})),v.value={...v.value,receiptIdForPaymentFailure:void 0,recoverySubmissionAttemptCount:0},U.value?N.dispatchEvent(new pt):nt=!0}catch(j){return e({session:S,error:j}),!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=$.value.isRequired("address2"),On=$.value.isRequired("firstName"),{token:It,billingContact:ke,shippingContact:M}=Ne.payment,at=$.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&&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(ot.paymentSheetAction){Be(de,ot.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,at&&!_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}=ho(It.paymentMethod.displayName);Ae.value=la(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?ca(H.unstable_getSerialization("experiments")):null,Ln=Tt!==void 0&&Tt===da(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=Oo(it);A.counter({name:"apple_pay_subscriptions_deceleration_variant",value:1,attributes:{variant:rt??pa.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=Ma(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 j=k;j.status==="rejected"&&(Lt=j.violations.map(De=>De.code),j.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:j.violations.map(De=>De.code).join(","),isPhoneRequired:at}));const Pe=j.status==="rejected"&&j.violations.some(wt=>wt.code===xe),{shouldRetry:be,retryReason:Ve,updatedDeliveryMethodHandles:Mt}=Mo(j,{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(j,{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?wa: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,$,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,ae,he,Ye,b,T,H,w,a,o])}function nn(e,t,n){const a=tt(t,n),o=e.fields.line2;e.value={...we(t),...a},o&&"line2"in a&&(o.value=a.line2)}function Mo(e,{retryCount:t,negotiated:n,originalSelectedDeliveryMethods:a}){const o={shouldRetry:!1,retryReason:"",updatedDeliveryMethodHandles:void 0};if(e.status!=="rejected"||t>=Do)return o;const r=Ya(e,n.current.fields.deliveryNext?.peek(),a);return r?{shouldRetry:!0,retryReason:"delivery_option_mismatch",updatedDeliveryMethodHandles:r}:o}function wo(){const{negotiate:e}=dt(),{checkout:{wallets:t},observability:n}=G();return Q(async(a,o)=>{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=a.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)}),o(),!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 Fo(e,t,{interfaceFlow:n,isConstrainedAddress:a=!1,deliveryAddressOptions:o}={}){return a?e:{...e,delivery:{...e.delivery,interfaceFlow:n,useProgressiveRates:!1,deliveryLines:(e.delivery?.deliveryLines??[]).map(r=>({...r,destination:{partialStreetAddress:Za(t,o)}}))}}}function Yo(){const{observability:e,checkout:{wallets:t,address:{countryDetails:n,extendedAddressMode:a}},checkout:o,shop:r}=G(),i=et(r),s=Se(),l=Et(),m=vt(),d=Ze(),p=fe(),y=_t(D.ApplePay),g=ht(),{formattedRecurringTotalTooltip:h,lineItemsLabels:E,deliveryOptionGroupTypeLabels:_,deliveryMethodTitlePrefixes:P}=Ke();return Q(async(v,I,f,R)=>{const{billingContact:C}=v.paymentMethod;if(!o.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=>Bo(u,C,{deliveryAddressOptions:{extendedAddressMode:a},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=Xe(u.currencyCode);try{se({methodName:"completePaymentMethodSelection",abortSignal:f,wallets:t,observability:e},()=>{const N={newTotal:Je(E.total,u),newLineItems:je({...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())}}o.isShippingRequired.value||X.endAndRun("apple-pay-sheet-load",u=>{y({event:ut.SheetLoaded,ttl:u}),e.histogram({name:"wallet_sheet_loaded",value:u,attributes:{instrument:D.ApplePay}})})},[t,l,P,_,d,h,m,E,p,o.isShippingRequired,e,s,y,g,a,n,i])}const Bo=(e,t,{deliveryAddressOptions:n,extendedAddressFieldsEnabled:a=!1}={})=>Fo(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:o,paymentSheetAction:r,onProceed:i,abortSignal:s})=>{switch(r.action){case"abort":se({methodName:"abort",abortSignal:s,wallets:n,observability:a},()=>o.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,a])}function ko(){const e=Se(),t=Ze(),n=vt(),a=fe(),o=hn(),{inMemoryApplePayParts:{initialDeliveryIdentifier:r,asPaymentMethod:i}}=te(),{deliveryLines:s,shippingAddress:l}=We(),m=ht(),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}=Ke(),b=Nn(),{shouldGateCrossBorder:c,crossBorderGate:w}=$a(),N=mt(i);return Q(async(H,T,$)=>{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),r.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 m({abortSignal:$,fieldsToResolve:["deliveryNext","duties","taxes"],customizeNegotiation:F=>dn(F,U,{interfaceFlow:"APPLE_PAY",isPickupSelected:o.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=Xe(oe.currencyCode);try{const ye={newTotal:Je(O.total,oe),newLineItems:je({...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:$,wallets:_,observability:v},()=>F.completeShippingContactSelection({errors:re,...ce?Pt(me):me}));try{const pe=Uo(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||$.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:$})}},[s,l,o,n,b,a,e,O,t,C,L,A,u,r,m,_,v,N,h,p,g,c,w,R,I,f])}function Uo(e,t){if(t?.length||!e||e.status!=="filled"||!e.lines?.length)return;const n=e.lines.reduce((a,o)=>(o.status==="available"&&o.selectedDeliveryMethodHandle&&a.push(o.selectedDeliveryMethodHandle),a),[]);if(!(n.length<e.lines.length))return n}function Vo(){const e=Se(),t=Ze(),n=vt(),a=fe(),o=hn(),{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=ht(),_=ve(),P=_.availableDeliveryAddresses?.value,v=_.mustSelectProvidedAddress?.value,I=_.deliveryNext?.value,f=Qe({availableDeliveryAddresses:P,mustSelectProvidedAddress:v}),{formattedRecurringTotalTooltip:R,lineItemsLabels:C,deliveryOptionGroupTypeLabels:O,deliveryMethodTitlePrefixes:L}=Ke(),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 Ba(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,$=H(u.shippingMethod.identifier);if($==null)return;Ge(y,$),r.leaveErrorBreadcrumb("ApplePay: Shipping method selected negotiation",{handles:JSON.stringify($),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:o.value,isConstrainedAddress:f,availableDeliveryAddresses:P,negotiatedDelivery:I,deliveryAddressOptions:{extendedAddressMode:l}}),observability:r,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=Xe(x.currencyCode);try{se({methodName:"completeShippingMethodSelection",abortSignal:c,wallets:i,observability:r},()=>{const Z={newTotal:Je(C.total,x),newLineItems:je({...re,formattedRecurringTotals:t(F),formattedRecurringTotalTooltip:R,lineItemsLabels:C,deliveryOptionGroupTypeLabels:O,deliveryMethodTitlePrefixes:L})};Y.completeShippingMethodSelection(oe?Pt(Z):Z)}),X.endAndRun("apple-pay-sheet-load",Z=>{h({event:ut.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 ae(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,o,C,a,y,g,e,r,h,p,E,f,P,I,s,d,l])}function Ho(){const e=Me(D.ApplePay),t=Se(),{shop:n,source:{sourceId:a},observability:o,checkout:{wallets:r},embed:i,graphql:{coreGraphql:s}}=G(),l=vn({embed:i,isCrossOriginIframeEnabled:n.hasFlagEnabled(pn)}),{inMemoryApplePayParts:{prefetchPaymentSession:m}}=te(),d=Ga(D.ApplePay);return Q((p,y,g,h)=>{const E=h===m.value?.prefetchUrl;o.histogram({name:"apple_pay_prefetch_session",value:X.end("apple-pay-session-begin"),attributes:{prefetch:E?"success":"retried"}}),_().then(P=>{if(m.value=void 0,P instanceof _n){o.leaveErrorBreadcrumb("[ApplePay] Validation query returned failed response",{reason:P.reason}),o.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";o.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:o},()=>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?o.leaveErrorBreadcrumb("[ApplePay] session query prefetch returned no data - starting new validation query",{validationUrl:h,prefetchUrl:m.value?.prefetchUrl}):E||o.leaveErrorBreadcrumb("[ApplePay] session query prefetch URL mismatch - starting new validation query",{validationUrl:h,prefetchUrl:m.value?.prefetchUrl})}catch(P){if(P instanceof yt)return;o.log("apple_pay_on_validate_merchant","Apple Pay prefetch session error",{error:P,prefetchValidationUrl:m.value?.prefetchUrl,validationUrl:h})}return o.leaveErrorBreadcrumb("[ApplePay] starting new session query",{hadPrefetch:!!m.value,validationUrl:h}),Pn({graphql:s,sourceId:a,validationUrl:h,asPaymentMethod:y,signal:g,observability:o,isPrefetch:!1,domain:l})}},[s,a,o,e,d,t,m,r,l])}function In(){const e=Se(),t=fe(),n=Me(D.ApplePay),{inMemoryApplePayParts:{asPaymentMethod:a,paymentSheetError:o,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=Po(),h=za().geolocation.country.code,E=vo(h),_=fo(),P=Ho(),v=Yo(),I=Vo(),f=ko(),R=Lo();return Q(({asPaymentMethod:C=!1,supportedNetworks:O,waitForTotalsToSettle:L,isPaymentAuthorizationBlocked:A,subscriptionConsent:u})=>{X.start("apple-pay-session-begin"),o.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),o.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(ua,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}},[a,g,t,o,_,R,v,f,I,P,p,e,n,r,E,d,l,s,y])}const xo=5e3;function qo(e,t){return t.aborted?Promise.resolve(!1):e.value?new Promise(n=>{let a=!1,o=()=>{};const r=l=>{a||(a=!0,o(),t.removeEventListener("abort",i),clearTimeout(s),n(l))},i=()=>r(!1);t.addEventListener("abort",i,{once:!0});const s=setTimeout(i,xo);o=e.subscribe(l=>{l||r(!0)}),a&&o(),t.aborted&&i()}):Promise.resolve(!0)}function Rn(){const{inMemoryApplePayParts:{asPaymentMethod:e,expiresAt:t}}=te(),{observability:n,checkout:{wallets:a}}=G(),o=mt(e);return Q(r=>{if(r){X.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}o.value&&(t.value=new Date(Date.now()+300*1e3).toISOString()),a.setActiveSession({newValue:"APPLE_PAY",asPaymentMethod:e.value})}},[e,n,a,o,t])}const Go=new Set(ln);function zo(){const{negotiate:e}=dt(),{observability:t,shopPay:n,checkout:{wallets:a,identity:o}}=G(),r=o.current.value==="shopPay",{inMemoryApplePayParts:{isLoadingPaymentSheet:i,paymentSheetError:s}}=te(),l=r?D.ShopPayApplePay:D.ApplePay,m=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(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})=>Go.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 qo(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&&!a.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"},a.activeSession.value?.wallet==="APPLE_PAY"&&a.clearActiveSession({invokingWallet:"APPLE_PAY"})}}}}function cr(){const{applePaySessionHandler:e,inMemoryApplePayParts:t}=te(),n=ct(zo()),a=ct(In()),o=ct(Rn());return kn(()=>{if(t.sessionLoadFailed.value)return;const r={onClickHandler:(...i)=>n.current(...i),createSession:(...i)=>a.current(...i),showApplePayPaymentSheet:(...i)=>o.current(...i)};return e.value=r,()=>{e.value=void 0}},[e,n,a,o,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.