1import{f as re,T as de,l as Xe,e as ue,q as x,A as ne,p as Mt,h as Gt,u as j,g as Lt,S as Ve}from"./esnext-vendor.BBoIVOQW.js";import{fi as ve,fh as wt,ca as Ht,fU as je,eX as Yt,f as Je,eA as Ut,f4 as Vt,eY as kt,fV as me,fW as Bt,fl as Ft,eW as xt,bk as Wt,fo as zt,fn as Zt,B as ke,S as qt,fX as $t}from"./hydrate.Tsur0pib.js";import{d5 as Qt,k as Ke,gA as et,gB as ye,eu as tt,gC as Xt,b4 as jt,aP as Jt,dh as Kt,T as z,ah as at,a5 as ce,W as Pe,gD as he,b3 as Oe,gE as Ae,ag as J,aA as rt,aB as ot,cJ as De,gF as Se,d4 as ea,d3 as ta,C as nt,gG as aa,b9 as ra,aj as oa,w as Be,gH as na,gI as sa,bn as ia,gJ as la,b6 as st}from"./addresses-is-address-empty.ZJ1ThpFy.js";import{g as da}from"./Page.B9pV9lua.js";import{S as fe,u as ua,a as ca}from"./hooks-useStableHostMethodsReferences.DJyLKxes.js";import{u as ga,W as pa}from"./WalletsSandbox-WalletSandbox.Y0YrDRHu.js";import{f as k,g as Ea,s as _a,r as ma,B as ya,P as ha,T as it,U as lt,V as dt,D as Te,N as Ce,a as va,b as Pa,c as Aa,d as Sa,e as Ia,h as ut,E as ct,I as gt,i as pt,j as Re,k as fa,l as Ra,u as Na,m as ba,n as Oa,o as Da,p as Ta,q as Fe,S as xe,t as Ca}from"./wallets-deserialize-delivery-handles.CQL5bAxO.js";import{a as Ma,g as Ga}from"./hooks-useShopPayExternalAppContext.YLtTu3k6.js";import{a as B,c as ae,b as We}from"./cross-border-hooks.BN4C-Hww.js";import{a as Et}from"./shop-pay-installments-monorail.wQxzDho3.js";import{S as se}from"./app.CUBUOQtX.js";import{a as La,u as wa}from"./hooks-useWalletsThreePageVaultedReviewEscalation.C7zf4Eyx.js";import{r as ze}from"./redemption-promotions.C4GFMar5.js";import"./shared-permissions.DW7FOCqf.js";import"./amazon-pay-useAmazonPayPaymentLine.CMgi35Fb.js";import"./AddressPresenter.Ce4uWLSc.js";import"./hooks-useShowShopPayOptin.BPTq9EIX.js";import"./negotiated-findSelectedDeliveryMethod.DhxHslog.js";import"./graphql-PaymentSessionMutation.KqKA7ogg.js";const Ha=/^[A-Z]{1,2}[0-9]{1,2}[A-Z]?$/,Ya=/^[A-Z][0-9][A-Z]$/;function Ua(t){const{countryCode:e,postalCode:a}=t;if(a==null)return t;const r=a.trim().toUpperCase();return e==="CA"&&Ya.test(r)?t.postalCode=`${r} 0Z0`:e==="GB"&&Ha.test(r)&&(t.postalCode=`${r} 0ZZ`),t}function Va(t=window.navigator.userAgent){const e=/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/537\.36 \(KHTML, like Gecko\) Chrome\/[\d.]+(?: Mobile)? Safari\/537\.36$/,a=/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/537\.36 \(KHTML, like Gecko\) Chrome\/[\d.]+ Safari\/537\.36 Edg\/[\d.]+$/,r=/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/537\.36 \(KHTML, like Gecko\) Chrome\/[\d.]+(?: Mobile)? Safari\/537\.36 Vivaldi\/[\d.]+$/;return e.test(t)||a.test(t)||r.test(t)}const ka=2,Ba=0,Fa={apiVersion:ka,apiVersionMinor:Ba},_t="%";function xa(t,e){const a=t.find(d=>d.deliveryLine.type==="ONE_TIME_PURCHASE"),r=t.find(d=>d.deliveryLine.type==="SUBSCRIPTION");let o="";if(r){if(r.methodType==="PICK_UP"||r.methodType==="LOCAL")return r.title;o=r.title}const s=[a?.title??"",o].filter(Boolean),[c,i]=s;return c===void 0?"":i===void 0?c:s.length===2?e.combineTwoShippingTitles(c,i):e.combineMultipleShippingTitles(s)}function mt(t){return yt(JSON.stringify(t))}function yt(t){return t.replace(/["']/g,_t)}function Wa(t){return yt(_a(t))}function za(t){const e=new RegExp(`[${_t}]`,"g");return t.replace(e,'"')}function Za(t,e){const a=jt(t).filter(Jt).map(Ma);return Ga(a).filter(o=>o.length).map(o=>({id:Wa(o),label:xa(o,e),description:o.map(vt).join(", ")}))}function qa({paymentDue:t,subtotal:e,duties:a,taxes:r,deliveryNext:o,discountLines:n,tipLines:s,paymentLines:c,checkoutTotal:i,deferredTotal:d,labels:y,i18nCurrency:h,translations:N,selectedShippingId:P,deliveryMacros:v,paymentFlexibilityPaymentTermsTemplate:I,googlePayTransactionId:E,merchandiseLines:D,shouldWalletDecelerateForSubscriptions:_=!1,discountsZeroValueUXEnabled:R=!1}){const A=v?.length?Ja(v):Za(o,N),f=!!tt({deferredTotal:d,checkoutTotal:i,paymentFlexibilityPaymentTermsTemplate:I})?.amount,m=ht({paymentDue:t,subtotal:e,duties:a,taxes:r,deliveryNext:o,discountLines:n,tipLines:s,paymentLines:c,labels:y,i18nCurrency:h,checkoutTotal:i,deferredTotal:d,hasPayableDeposit:f,googlePayTransactionId:E,merchandiseLines:D,shouldWalletDecelerateForSubscriptions:_,discountsZeroValueUXEnabled:R}),C=A.find(u=>u.id===P)?.id??A[0]?.id;return{...A.length>0?{newShippingOptionParameters:{shippingOptions:A,defaultSelectedOptionId:C}}:{},newTransactionInfo:m}}
1function ht({paymentDue:t,subtotal:e,duties:a,taxes:r,deliveryNext:o,discountLines:n,tipLines:s,paymentLines:c,labels:i,i18nCurrency:d,checkoutTotal:y,deferredTotal:h,hasPayableDeposit:N,googlePayTransactionId:P,merchandiseLines:v,shouldWalletDecelerateForSubscriptions:I=!1,discountsZeroValueUXEnabled:E=!1}){const D=t?k(t.amount):"0",_=N&&y&&h,R=_?k(y.amount):void 0,A=_?k(h.amount.amount):void 0,f=!!v?.lines?.length,m=[];v?.lines&&v.lines.forEach(u=>{m.push({label:Ea(u),type:"LINE_ITEM",price:k(u.totalPrice.amount)}),Xa(u,E).forEach(T=>{m.push(T)})}),e&&m.push({label:i.subtotal,type:"SUBTOTAL",price:k(e.amount)}),Qa(n?.lines,E).forEach(u=>{m.push(u)});const C=Qt(o).reduce((u,T)=>u+T.method.cost.amount,0);return m.push({label:i.shipping,type:"LINE_ITEM",price:k(C)}),a&&a?.status==="available_total"&&a?.totalDuty.amount!==0&&m.push({label:i.duties,type:"LINE_ITEM",price:k(a.totalDuty.amount)}),r&&r.status==="available_total"&&r.totalTax.amount!==0&&m.push({label:i.taxes,type:"LINE_ITEM",price:k(r.totalTax.amount)}),n?.lines.forEach(u=>{if(Ke(u)){if(f&&u.discount.presentationLevel==="LINE"&&u.sourceTerm!=="delivery"||et(u))return;const T=u.amount?.amount;T&&m.push({label:u.title,type:"LINE_ITEM",price:ye(k(T))})}}),c?.lines.filter(u=>u.method.type==="giftCard").forEach(u=>{u.cost&&m.push({label:`${i.giftCard} ${u.method.code.slice(-4).toUpperCase()}`,type:"LINE_ITEM",price:ye(k(u.cost.amount))})}),s?.forEach(u=>{m.push({label:i.tip,type:"LINE_ITEM",price:k(u.amount.amount)})}),R&&m.push({label:i.deposit,type:"LINE_ITEM",price:R}),A&&m.push({label:i.totalDueLater,type:"LINE_ITEM",price:A}),{totalPrice:R||D,currencyCode:e?.currencyCode||d,totalPriceStatus:"ESTIMATED",totalPriceLabel:R?i.totalDueToday:i.total,displayItems:m,...P&&{transactionId:P},...I&&{checkoutOption:"CONTINUE_TO_REVIEW"}}}function $a(t){return Kt(t.discountDetails.discount)&&t.discountDetails.discount.presentationLevel==="LINE"}function Qa(t,e){return t?t.flatMap(a=>{if(!Ke(a))return[];if(!et(a))return[];const r=a.amount?.amount;if(r===void 0)return[];if(e&&r===0)return[];const o=k(r);return[{label:a.title,type:"LINE_ITEM",price:r===0?o:ye(o)}]}):[]}function Xa(t,e){const a=new Map;return t.lineAllocations.forEach(r=>{r.allocations.filter($a).forEach(o=>{const{title:n}=o.discountDetails;a.set(n,(a.get(n)??0)+o.amount.amount)})}),Array.from(a).filter(([,r])=>!e||r!==0).map(([r,o])=>({label:r,type:"LINE_ITEM",price:o===0?k(o):ye(k(o))}))}function Ne({googleAddress:t,isFirstNameRequired:e}){let a=t.iso3166AdministrativeArea||void 0,r=t.locality||void 0,o=t.countryCode;t.countryCode==="AE"&&(r=t.administrativeArea),t.countryCode&&Xt.includes(t.countryCode)&&(a=t.countryCode,o="US");const n={city:r,postalCode:t.postalCode||void 0,zoneCode:a,countryCode:o};if("name"in t){const[s,...c]=(t.name||"").split(" ");c.length===0?(n.lastName=s,e&&(n.firstName=n.lastName)):(n.firstName=s,n.lastName=c.join(" "))}return"address1"in t&&(n.address1=t.address1),"address2"in t&&(n.address2=t.address2),"phoneNumber"in t&&(n.phone=t.phoneNumber),n}function ja({googleAddress:t,isFirstNameRequired:e}){return Ua(Ne({googleAddress:t,isFirstNameRequired:e}))}function vt({costAfterDiscounts:t,deliveryPromisePresentmentTitle:e}){const{short:a}=e||{},r=k(t.amount);return`${a?`(${a}) `:""}${r} ${t.currencyCode}`}function Ja(t){return t.map(({totalTitle:e,totalCostAfterDiscounts:a,deliveryPromisePresentmentTitle:r,deliveryMethodHandles:o})=>({id:mt(o),label:e,description:vt({costAfterDiscounts:a,deliveryPromisePresentmentTitle:r})}))}function Ka(){const{checkout:t}=z(),e=ve("GOOGLE_PAY");return re(()=>{const a=e.value;if(a===void 0)return[];const{allowedAuthMethods:r,allowedCardNetworks:o,gateway:n,gatewayMerchantId:s}=a;return[{type:"CARD",parameters:{allowedAuthMethods:r,allowedCardNetworks:o,billingAddressRequired:!0,billingAddressParameters:{format:"FULL-ISO3166",phoneNumberRequired:t.configuration.addressSettings.nonBillingAddressSettings.value.isRequired("phone")}},tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:n??"",gatewayMerchantId:s??""}}}]})}function Pt(){const{i18n:t}=z();return de(()=>({total:t.translate("order_summary.total_label"),subtotal:t.translate("order_summary.subtotal_label"),shipping:t.translate("order_summary.shipping_label"),duties:t.translate("order_summary.duties_label"),taxes:t.translate("order_summary.estimated_taxes_label"),giftCard:t.translate("order_summary.gift_card_label"),tip:t.translate("order_summary.tip_label"),deposit:t.translate("order_summary.deposit_label"),totalDueToday:t.translate("order_summary.total_due_today_label"),totalDueLater:t.translate("order_summary.total_due_later_label")}),[t])}function At(){const{shop:{name:t,myshopifyDomain:e}}=z(),a=ve("GOOGLE_PAY");return re(()=>{const r=a.value;return r===void 0?void 0:{merchantName:t,merchantId:r.merchantId,merchantOrigin:e,authJwt:r.authJwt}})}function er({asPaymentMethod:t}){const e=at(),a=At(),r=Ka(),{checkout:o,i18n:n,shop:s}=z(),c=ce(),i=wt(),d=Pt(),{locationAddress:y}=Pe(),h=Ht(),N=je(s),P=o.configuration.layout.isOnePage.value,v=s.hasFlagEnabled(he),I=P||v,E=re(()=>I&&Oe({checkout:o})),D=Xe(t);return re(()=>{const _=!D.value&&!Ae({availableDeliveryAddresses:c.availableDeliveryAddresses?.value,mustSelectProvidedAddress:c.mustSelectProvidedAddress?.value})&&o.isShippingRequired.value,R=_?["PAYMENT_AUTHORIZATION","SHIPPING_ADDRESS","SHIPPING_OPTION"]:["PAYMENT_AUTHORIZATION"],A=ma(e,{includeShopPromotion:!1}),f=h.value&&y.fields.countryCode.value?[y.fields.countryCode.value]:s.shippingCountries?.map(T=>T.value),m=r.value,C=a.value;if(m.length===0||!C||!f||f.length===0&&_||A.paymentDue==null||A.subtotal==null)return null;const u=!!tt({deferredTotal:A.deferredTotal,checkoutTotal:A.checkoutTotal,paymentFlexibilityPaymentTermsTemplate:A.paymentFlexibilityPaymentTermsTemplate})?.amount;return{...Fa,allowedPaymentMethods:m,merchantInfo:C,callbackIntents:R,emailRequired:i.value,shippingAddressParameters:{format:"FULL-ISO3166",allowedCountryCodes:f,phoneNumberRequired:o.configuration.addressSettings.nonBillingAddressSettings.value.isRequired("phone")},shippingAddressRequired:_,shippingOptionRequired:_,transactionInfo:ht({labels:d,i18nCurrency:n.currency,...A,hasPayableDeposit:u,shouldWalletDecelerateForSubscriptions:E.value,discountsZeroValueUXEnabled:N})}})}const be="GOOGLE_PAY",tr="54px",ar="FAILED_TO_OPEN_WINDOW",rr="VALIDATION_TIMEOUT";class _e extends se{constructor(){super(...arguments),this.name="GooglePayGenericError"}}class or extends se{constructor(){super(...arguments),this.name="GooglePayCreateButtonError"}}class nr extends se{constructor(){super(...arguments),this.name="GooglePayDeveloperError"}}class sr extends se{constructor(){super(...arguments),this.name="GooglePayUnexpectedStatusCodeError"}}class Ze extends se{constructor(){super(...arguments),this.name="GooglePaySubmissionError"}}class ir extends se{constructor(){super(...arguments),this.name="GooglePayInvalidError"}}function lr(t){const e=Et(B.GooglePay),a=ue(!1),{persistedGooglePaySignal:r,inMemoryGooglePayParts:{sdkStatus:o,buttonStatus:n,paymentSheetError:s,paymentSheetOpenPromiseResolve:c,paymentSheetOpenPromise:i}}=J(),{observability:d,checkout:{wallets:y},client:{userAgent:h}}=z(),N=rt(h),P=ot(h);return x(v=>{d.leaveErrorBreadcrumb("[GooglePay] useGooglePayResponseHandler onResponse",{response:v}),t.value=!1;const{response:I,error:E}=v;if(I)c.value?.(void 0);else if(E){switch(E.name==="CANCELED"?d.counter({name:"wallet_sheet_cancelled",value:1,attributes:{instrument:B.GooglePay}}):d.counter({name:"wallet_sheet_failed",value:1,attributes:{instrument:B.GooglePay}}),E.name){case"CANCELED":d.leaveErrorBreadcrumb("[GooglePay] useGooglePayResponseHandler error: CANCELED"),e(ae.Cancelled);break;case"DEVELOPER_ERROR":d.leaveErrorBreadcrumb("[GooglePay] useGooglePayResponseHandler error: DEVELOPER_ERROR",{errorMessage:E.message}),e(ae.Failure),s.value={type:"invalid_config"},d.error(new nr(`loadPaymentData failed: ${E.message}`,{groupingHash:"GooglePayDeveloperError::LoadPaymentDataFailed"}));break;case"BUYER_ACCOUNT_ERROR":case"MERCHANT_ACCOUNT_ERROR":d.leaveErrorBreadcrumb("[GooglePay] useGooglePayResponseHandler error: ACCOUNT_ERROR",{errorType:E.name,errorMessage:E.message}),e(ae.Failure),n.value={status:"error"},o.value={status:"error"},d.log("google_pay_response_handler_session_unavailable","Google Pay is unavailable for this session",{reason:E.name});break;case"INTERNAL_ERROR":d.leaveErrorBreadcrumb("[GooglePay] useGooglePayResponseHandler error: INTERNAL_ERROR",{errorMessage:E.message}),e(ae.Failure),s.value={type:"unexpected_terminal_error"},d.log("google_pay_response_handler_internal_error","Google Pay internal server error occurred",{errorMessage:E.message});break;case rr:d.leaveErrorBreadcrumb("[GooglePay] useGooglePayResponseHandler error: VALIDATION_TIMEOUT"),e(ae.Failure);break;case ar:a.value||(d.leaveErrorBreadcrumb("[GooglePay] useGooglePayResponseHandler error: FAILED_TO_OPEN_WINDOW"),e(ae.Failure),d.counter({name:"wallet_failed_to_open_window",value:1,attributes:{os:P,browser:N.name}}),a.value=!0);break;default:d.leaveErrorBreadcrumb("[GooglePay] useGooglePayResponseHandler error: UNEXPECTED_STATUS",{errorName:E.name,errorMessage:E.message}),d.error(new sr(`loadPaymentData failed with unexpected status code: [${E.name}] ${E.message}`,{groupingHash:`GooglePayUnexpectedStatusCodeError::UnexpectedStatus::${E.name}`}));break}c.value?.(void 0)}d.leaveErrorBreadcrumb("[GooglePay] useGooglePayResponseHandler cleanup complete"),y.activeSession.value?.wallet==="GOOGLE_PAY"?y.clearActiveSession({invokingWallet:"GOOG
1LE_PAY"}):d.leaveErrorBreadcrumb("[GooglePay] useGooglePayResponseHandler cleanup complete, but activeSession is not Google Pay",{activeSession:y.activeSession.value}),i.value=void 0,r.value={initialCurrencyCode:void 0}},[N,P,i,r,c,d,e,s,n,o,a,t,y])}function dr({paymentDataRequest:t,asPaymentMethod:e,isScrimOpen:a,containerRef:r,endpoint:o}){const n=Yt(),{negotiate:s}=Je(),{observability:c,checkout:{wallets:i},client:{userAgent:d}}=z(),y=rt(d),h=y.name==="Safari",N=ot(d),P=ue(!1),v=ue(!1),{inMemoryGooglePayParts:{paymentSheetError:I,paymentSheetOpenPromise:E,paymentSheetOpenPromiseResolve:D,sdkStatus:_},persistedGooglePaySignal:R}=J(),A=Et(B.GooglePay),f=Ut(B.GooglePay),m=Vt(B.GooglePay);return x(async()=>{n(r);try{if(e){if(P.value)return;P.value=!0,h&&(o.value?.call.updateValidationLock({status:"success"}),a.value=!0),await new Promise((u,T)=>{s({negotiationStage:"completion",runListenersOnError:!0,onComplete:F=>{F?.status==="success"?u():T()}})})}if(a.value=!0,i.activeSession.value){c.leaveErrorBreadcrumb("[GooglePay] useHandleClick onClick early return - active session exists"),a.value=!1,o.value?.call.updateValidationLock({status:"failure"});return}const C=_.value;if(C?.status!=="available"){c.leaveErrorBreadcrumb("[GooglePay] useHandleClick onClick early return - SDK not available",{sdkStatus:C?.status}),a.value=!1,o.value?.call.updateValidationLock({status:"failure"});return}i.setActiveSession({newValue:"GOOGLE_PAY",asPaymentMethod:e});try{f();const u=t.value;if(u===null||u.callbackIntents==null||u.callbackIntents.length===0){c.leaveErrorBreadcrumb("[GooglePay] useHandleClick onClick early return - invalid payment data request",{paymentDataRequest:u===null?"null":"invalid"}),i.clearActiveSession({invokingWallet:"GOOGLE_PAY"}),I.value={type:"config_missing_required_fields"},a.value=!1,o.value?.call.updateValidationLock({status:"failure"});return}m(),A(ae.Success,e?We.PaymentMethod:We.Express),c.counter({name:"wallet_sheet_clicked",value:1,attributes:{instrument:B.GooglePay}}),v.value||(c.counter({name:"wallet_attempt_to_open_payment_sheet",value:1,attributes:{os:N,browser:y.name}}),v.value=!0),R.value={initialCurrencyCode:u.transactionInfo.currencyCode,receiptIdForPaymentFailure:R.value?.receiptIdForPaymentFailure},c.log("handle_click_button_clicked","Google Pay button clicked",{allowedAuthMethods:u.allowedPaymentMethods.map(T=>T.parameters.allowedAuthMethods)}),E.value=new Promise(T=>{D.value=T}),o.value?.call.updateValidationLock({status:"success"})}catch(u){throw i.clearActiveSession({invokingWallet:"GOOGLE_PAY"}),a.value=!1,u}}catch(C){c.leaveErrorBreadcrumb("[GooglePay] useHandleClick onClick error handling",{error:C}),h&&e?(o.value?.call.closePopupWindows(),a.value=!1):(!e||!h)&&(a.value=!1),o.value?.call.updateValidationLock({status:"failure"})}finally{P.value&&(P.value=!1)}},[e,y,r,n,m,f,o,v,h,a,P,s,N,t,I,E,D,R,_,c,A,i])}function ur({endpoint:t,isTerminated:e,color:a,config:r,merchantInfo:o,buttonLabel:n,ariaLabel:s,markAsLoaded:c,sdkStatus:i,sdkStatusRef:d,buttonStatus:y,paymentDataRequest:h,containerRef:N,asPaymentMethod:P,isFirstRender:v,updateSdkStatus:I,connectedNullPaymentDataRequest:E,cardsinkConfig:D}){const{observability:_,source:R}=z();return x(async A=>{if(e.current){_.leaveErrorBreadcrumb("[GooglePay] useOnConnect skipped - sandbox already terminated");return}_.leaveErrorBreadcrumb("[GooglePay] useOnConnect starting configuration"),h.value||(E.current=!0),t.value=A;const f=await A.call.configure({isDark:a==="dark",environment:r?.environment,merchantInfo:o,buttonLabel:n,ariaLabel:s,paymentDataRequest:h.value,style:{borderRadius:kt(N.current)},cardsinkConfig:D,sourceId:R.sourceId});v.current=!1,c(),f.status===fe.Success?(_.leaveErrorBreadcrumb("[GooglePay] useOnConnect configuration successful"),I({status:"available"},i,d),y.value.status!=="error"&&(y.value={status:"rendered"},_.counter({name:"checkout_wallet_button_rendered",value:1,attributes:{wallet_name:be,status:"success",isPaymentMethodFlow:P}}))):(_.leaveErrorBreadcrumb("[GooglePay] useOnConnect configuration failed",{status:f.status}),f.status===fe.Error&&cr({result:f,observability:_}),y.value={status:"error"},_.counter({name:"checkout_wallet_button_rendered",value:1,attributes:{wallet_name:be,status:"error",isPaymentMethodFlow:P,reason:f.status===fe.ScriptLoadError?"script_load_error":"sandbox_error"}}),I({status:"error"},i,d))},[t,e,a,r?.environment,o,n,s,c,i,d,y,h,N,_,P,v,I,E,D,R.sourceId])}function cr({result:{type:t,name:e,message:a},observability:r}){t==="createButton"&&r.error(new or(a,{cause:{name:e,message:a}}),{metadata:{additionalKey:{name:e,message:a}}})}class St extends ya{constructor(e,a){super(),this.observability=e,this.translated=a}get negotiationResultMapper(){return null}validatePaymentCurrency({initialCurrencyCode:e,currentCurrencyCode:a}){return e==null||a==null?(this.observability.leaveErrorBreadcrumb("[GooglePay] validatePaymentCurrency skipped currency comparison, missing currency code",{initialCurrencyCode:e,currentCurrencyCode:a}),{}):e===a?(this.observability.log("google_pay_validate_payment_currency_succeeded","[GooglePay] validatePaymentCurrency succeeded, currency codes match",{currencyCode:a}),{}):(this.observability.leaveErrorBreadcrumb("[GooglePay] validatePaymentCurrency blocking submission, currency change",{initialCurrencyCode:e,currentCurrencyCode:a}),this.observability.counter({name:"wallet_action_generator_handled_error",value:1,attributes:{violationCode:"CURRENCY_CHANGE",WalletName:B.GooglePay}}),{paymentSheetAction:{action:"show_error",errors:[{reason:"OTHER_ERROR",intent:"PAYMENT_AUTHORIZATION",message:this.translated.currencyChangeError}]}})}get completionResultMapper(){return new ha({success:({result:e})=>"receipt"in e?{action:"submit"}:{action:"abort"},rejected:({result:e,violationActions:a})=>{const r=e.violations??[];
1this.getUnhandledErrors(r,a).forEach(s=>{this.observability.error(new Ze(`submitForCompletion in ${this.isRedesign()?"redesign":"3-page"} Google Pay failed due to unhandled error ${s.code}`,{groupingHash:`GooglePaySubmissionError::SubmitForCompletion::UnhandledError::${s.code}`}),{severity:"error"})});const{firstPaymentSheetAction:o,violationCode:n}=this.getMergedPaymentSheetAction({resultViolations:r,violationActions:a});return n&&this.observability.counter({name:"wallet_action_generator_handled_error",value:1,attributes:{violationCode:n,WalletName:B.GooglePay}}),o||{action:"abort"}},invalid:({result:e})=>{const a={reasons:JSON.stringify(e.reasons),action:"invalid"};return this.observability.counter({name:"WalletsPlatform_google_pay_payment_sheet_unexpected_action",value:1,attributes:a}),{action:"abort"}},denied:()=>({action:"abort"}),throttled:()=>({action:"abort"}),tooManyRequests:()=>({action:"abort"}),alreadyCompleted:()=>({action:"abort"}),fetch_failed:()=>(this.observability.counter({name:"WalletsPlatform_google_pay_payment_sheet_unexpected_action",attributes:{action:"fetch_failed"},value:1}),{action:"show_error",errors:[{reason:"OTHER_ERROR",intent:"PAYMENT_AUTHORIZATION",message:this.translated.genericError}]})},e=>this.mapUnhandledStatus(e),(e,a)=>this.getCompletionViolationActions(e,a))}mapUnhandledStatus(e){return this.observability.error(new Ze(`Unhandled completion status: ${e.status}`,{groupingHash:`GooglePaySubmissionError::UnhandledCompletionStatus::${e.status}`})),{action:"show_error",errors:[{reason:"OTHER_ERROR",intent:"PAYMENT_AUTHORIZATION",message:this.translated.genericError}]}}}class gr extends St{constructor(e,a,r){super(e,a),this.inMemoryGooglePayParts=r}validateBilling(e){return e.paymentMethodData.info?.billingAddress?{shouldPersist:!0}:this.genericPaymentMethodError()}validateShipping(e,a){const r=e.shippingAddress;return a?r?{shouldPersist:!0}:this.genericPaymentMethodError():{shouldPersist:!1}}isRedesign(){return!0}getCompletionViolationActions(e,a){return[{violations:[...De,"MERCHANDISE_NOT_APPLICABLE",Se,...it,...lt,...dt,"LOCALIZATION_EXTENSION_FIELD_ERROR",...Te,...Ce,"DELIVERY_WRONG_NUMBER_OF_DELIVERY_LINES",...va,...Pa,...Aa,...ea,"PAYMENTS_METHOD_REQUIRED","PAYMENTS_METHOD",...Sa,...Ia,...ta,"PAYMENTS_PHONE_NUMBER_DOES_NOT_MATCH_EXPECTED_PATTERN","BUYER_IDENTITY_MISSING_CONTACT_METHOD",...ut,"BUYER_IDENTITY_EMAIL_REQUIRED",...ct,...gt,...nt],generateAction:()=>({action:"abort"})},{violations:[...pt,"BUYER_IDENTITY_CONTACT_INFO_DOES_NOT_MATCH_CUSTOMER_PROFILE"],generateAction:()=>({action:"abort",effects:[()=>{this.inMemoryGooglePayParts.paymentSheetError.value={type:"unexpected_terminal_error"}}]})},{violations:["DELIVERY_ZONE_NOT_FOUND"],generateAction:()=>({action:"abort",effects:[()=>this.logZoneCompletionFailure(a,"DELIVERY_ZONE_NOT_FOUND")]})},{violations:["DELIVERY_ZONE_REQUIRED_FOR_COUNTRY"],generateAction:()=>({action:"abort",effects:[()=>this.logZoneCompletionFailure(a,"DELIVERY_ZONE_REQUIRED_FOR_COUNTRY")]})}]}genericPaymentMethodError(){return{shouldPersist:!1,paymentSheetAction:{action:"show_error",errors:[{reason:"OTHER_ERROR",intent:"PAYMENT_METHOD",message:this.translated.genericError}]}}}logZoneCompletionFailure(e,a){const{shippingZone:r,shippingCountry:o}=Re(e);this.observability.log("redesign_payment_sheet_action_generator_payment_completion_failed","google_pay_payment_completion_failed",{reason:a,shippingZone:r,shippingCountry:o,result:e})}}class pr extends St{constructor(e,a,r){super(e,a),this.inMemoryGooglePayParts=r}validateBilling(e){return e.paymentMethodData.info?.billingAddress?{shouldPersist:!0}:{shouldPersist:!1,paymentSheetAction:{action:"show_error",errors:[{reason:"OTHER_ERROR",intent:"PAYMENT_METHOD",message:this.translated.genericError}]}}}validateShipping(e,a,r){const o=e.shippingAddress;return a?o?r&&!o.address2?{shouldPersist:!1,paymentSheetAction:{action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.translated.addressLine2MissingError}]}}:{shouldPersist:!0}:{shouldPersist:!1,paymentSheetAction:{action:"show_error",errors:[{reason:"OTHER_ERROR",intent:"PAYMENT_METHOD",message:this.translated.genericError}]}}:{shouldPersist:!1}}isRedesign(){return!1}getCompletionViolationActions(e,a){return[{violations:[...De,"MERCHANDISE_NOT_APPLICABLE",Se,...it,...lt,...dt,"LOCALIZATION_EXTENSION_FIELD_ERROR","DELIVERY_WRONG_NUMBER_OF_DELIVERY_LINES","DELIVERY_STRATEGY_CONDITIONS_NOT_SATISFIED",...gt,...nt],generateAction:()=>({action:"abort"})},{violations:[...pt,"BUYER_IDENTITY_MISSING_CONTACT_METHOD","BUYER_IDENTITY_CONTACT_INFO_DOES_NOT_MATCH_CUSTOMER_PROFILE"],generateAction:()=>({action:"abort",effects:[()=>{this.inMemoryGooglePayParts.paymentSheetError.value={type:"unexpected_terminal_error"}}]})},{violations:Te,generateAction:()=>({action:"abort",effects:[()=>{this.inMemoryGooglePayParts.paymentSheetError.value={type:"unusable_partial_address"}}]})},{violations:Ce,generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_UNSERVICEABLE",intent:"SHIPPING_ADDRESS",message:this.translated.addressUnserviceableError}]})},{violations:["DELIVERY_FIRST_NAME_REQUIRED"],generateAction:()=>Z(this.translated.firstNameMissingError)},{violations:["DELIVERY_LAST_NAME_REQUIRED"],generateAction:()=>Z(this.translated.lastNameMissingError)},{violations:["DELIVERY_ADDRESS1_REQUIRED"],generateAction:()=>Z(this.translated.addressLine1MissingError)},{violations:["DELIVERY_ADDRESS2_REQUIRED"],generateAction:()=>Z(this.translated.addressLine2MissingError)},{violations:["DELIVERY_PHONE_NUMBER_REQUIRED","DELIVERY_OPTIONS_PHONE_NUMBER_REQUIRED"],generateAction:()=>Z(this.translated.phoneMissingError)},{violations:["DELIVERY_POSTAL_CODE_REQUIRED"],generateAction:()=>Z(this.translated.zipMissingError)},{violations:["DELIVERY_CITY_REQUIRED"],generateAction:()=>Z(this.translated.cityMissingError)},{violations:["DELIVERY_ZONE_REQUIRED_FOR_COUNTRY"],generateAction:()=>({action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:this.translated.zoneMissingError}],effects:[()=>{const{shippingZone:r,shippingCountry:o}=Re(a);this.observability.log("three_page_payment_sheet_action_generator_payment_completion_failed","google_pay_payment_completion_failed",{reason:"DELIVERY_ZONE_REQUIRED_FOR_COUNTRY",shippingZone:r,shippingCountry:o,result:a})}]})},{violations:["DELIVERY_ZONE_NOT_FOUND"],generateAction:()=>{const{shippingZone:r,shippingCountry:o}=Re(a);return{action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_OPTION",message:this.translated.zoneInvalidError}],effects:[()=>{this.observability.log("three_page_payment_sheet_action_generator_payment_completion_failed","google_pay_payment_completion_failed",{reason:"DELIVERY_ZONE_NOT_FOUND",shippingZone:r,shippingCountry:o,result:a})}]}}},{violations:[...ct,"BUYER_IDENTITY_EMAIL_REQUIRED"],generateAction:()=>Z(this.translated.emailInvalidError)},{violations:["DELIVERY_COMPANY_REQUIRED","DELIVERY_ADDRESS1_CONTAINS_EMOJIS","DELIVERY_ADDRESS1_CONTAINS_HTML_TAGS","DELIVERY_ADDRESS1_CONTAINS_MATHEMATICAL_SYMBOLS","DELIVERY_LAST_NAME_CONTAINS_URL"],generateAction:()=>Z(this.translated.addressInvalid)},{violations:[...ut,"DELIVERY_OPTIONS_PHONE_NUMBER_DOES_NOT_MATCH_EXPECTED_PATTERN","DELIVERY_PHONE_NUMBER_DOES_NOT_MATCH_EXPECTED_PATTERN"],generateAction:()=>Z(this.translated.phoneInvalidError)},{violations:["DELIVERY_INVALID_POSTAL_CODE_FOR_ZONE","DELIVERY_INVALID_POSTAL_CODE_FOR_COUNTRY"],generateAction:()=>
1Z(this.translated.zipInvalidError)},{violations:["PAYMENTS_METHOD_REQUIRED","PAYMENTS_METHOD"],generateAction:()=>W(this.translated.genericError)},{violations:["PAYMENTS_FIRST_NAME_REQUIRED"],generateAction:()=>W(this.translated.billingAddressFirstNameMissingError)},{violations:["PAYMENTS_LAST_NAME_REQUIRED"],generateAction:()=>W(this.translated.lastNameMissingError)},{violations:["PAYMENTS_ADDRESS1_REQUIRED"],generateAction:()=>W(this.translated.billingAddressLine1MissingError)},{violations:["PAYMENTS_CITY_REQUIRED"],generateAction:()=>W(this.translated.billingAddressCityMissingError)},{violations:["PAYMENTS_ZONE_REQUIRED_FOR_COUNTRY"],generateAction:()=>W(this.translated.billingAddressZoneMissingError)},{violations:["PAYMENTS_POSTAL_CODE_REQUIRED"],generateAction:()=>W(this.translated.billingAddressZipMissingError)},{violations:["PAYMENTS_PHONE_NUMBER_DOES_NOT_MATCH_EXPECTED_PATTERN"],generateAction:()=>W(this.translated.billingAddressPhoneInvalidError)},{violations:[fa],generateAction:()=>W(this.translated.billingAddressZipInvalidError)},{violations:[Ra],generateAction:()=>W(this.translated.billingAddressZoneInvalidError)},{violations:["PAYMENTS_INVALID_POSTAL_CODE_FOR_ZONE"],generateAction:()=>W(this.translated.billingZipInvalidError)},{violations:["PAYMENTS_ADDRESS1_CONTAINS_HTML_TAGS","PAYMENTS_CITY_CONTAINS_HTML_TAGS","PAYMENTS_LAST_NAME_CONTAINS_URL"],generateAction:()=>W(this.translated.billingAddressInvalid)}]}}function Z(t){return{action:"show_error",errors:[{reason:"SHIPPING_ADDRESS_INVALID",intent:"SHIPPING_ADDRESS",message:t}]}}function W(t){return{action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",intent:"PAYMENT_METHOD",message:t}]}}function Er({supportsOnePage:t=!1}={}){const{i18n:e,observability:a}=z(),{inMemoryGooglePayParts:r}=J(),o=de(()=>({genericError:e.translate("wallets.errors.generic",{walletName:e.translate("brand.google_pay")}),shippingMethodError:e.translate("wallets.errors.outdated.shipping_method"),currencyChangeError:e.translate("wallets.errors.detour.currency_change",{walletName:e.translate("brand.google_pay")}),addressUnserviceableError:e.translate("wallets.errors.unsupported.address"),addressInvalid:e.translate("wallets.errors.invalid.shipping_address"),phoneInvalidError:e.translate("wallets.errors.invalid.phone"),zipInvalidError:e.translate("wallets.errors.invalid.postal_code"),zoneInvalidError:e.translate("wallets.errors.invalid.zone"),firstNameMissingError:e.translate("wallets.errors.missing.first_name"),lastNameMissingError:e.translate("wallets.errors.missing.last_name"),addressLine1MissingError:e.translate("wallets.errors.missing.address1"),addressLine2MissingError:e.translate("wallets.errors.missing.address2"),zipMissingError:e.translate("wallets.errors.missing.zip"),zoneMissingError:e.translate("wallets.errors.missing.province"),cityMissingError:e.translate("wallets.errors.missing.city"),emailInvalidError:e.translate("wallets.errors.invalid.email"),phoneMissingError:e.translate("wallets.errors.missing.phone"),billingAddressInvalid:e.translate("wallets.errors.invalid.billing_address"),billingAddressPhoneInvalidError:e.translate("wallets.errors.invalid.billing_phone"),billingAddressZipInvalidError:e.translate("wallets.errors.invalid.billing_zip"),billingAddressZoneInvalidError:e.translate("wallets.errors.invalid.billing_zone"),billingZipInvalidError:e.translate("wallets.errors.invalid.billing_zip"),billingAddressLine1MissingError:e.translate("wallets.errors.missing.billing_address1"),billingAddressFirstNameMissingError:e.translate("wallets.errors.missing.billing_first_name"),billingAddressCityMissingError:e.translate("wallets.errors.missing.billing_city"),billingAddressZipMissingError:e.translate("wallets.errors.missing.billing_zip"),billingAddressZoneMissingError:e.translate("wallets.errors.missing.billing_province")}),[e]);return de(()=>t?new gr(a,o,r):new pr(a,o,r),[a,t,o,r])}function Me(){const{persistedGooglePaySignal:t}=J(),{observability:e,checkout:a}=z(),r=ce(),o=Ae({availableDeliveryAddresses:r.availableDeliveryAddresses?.value,mustSelectProvidedAddress:r.mustSelectProvidedAddress?.value}),n=a.configuration.addressSettings.nonBillingAddressSettings.value,{deliveryLines:s,email:c,shippingAddress:i,paymentLines:d}=Pe();return x(()=>{e.leaveErrorBreadcrumb("[GooglePay] useClearGooglePayProposedState clearing proposed state");const y=aa(d.value);d.value=y,c.value="",t.value={...t.value,description:void 0},o||(me(s,void 0),i.value=ra({countryCode:n.defaultShippingDetails.country.code,zoneCode:n.defaultShippingDetails.zone.code}))},[n.defaultShippingDetails,o,t,s,c,d,i,e])}function _r(){const{walletUsedForSubmissionSignal:t,inMemoryGooglePayParts:{paymentSheetError:e}}=J(),a=Me();return x(()=>{e.value=void 0,t.value=void 0,a()},[e,t,a])}const mr=1;function yr(){const{deliveryLines:t,email:e,shippingAddress:a,billingAddress:r,paymentLines:o}=Pe(),{progress:n}=Je(),{shop:s,checkout:c,observability:i}=z(),d=c.configuration.addressSettings.nonBillingAddressSettings,y=oa(),h=ce(),N=h.availableDeliveryAddresses?.value,P=h.mustSelectProvidedAddress?.value,v=Ae({availableDeliveryAddresses:N,mustSelectProvidedAddress:P}),I=at(),E=c.configuration.layout.isOnePage.value,D=s.hasFlagEnabled(he),_=!E&&D,R=re(()=>c.configuration.layout.isOnePage.value||D),A=re(()=>R.value&&Oe({checkout:c})),f=ve("GOOGLE_PAY"),m=Er({supportsOnePage:R.value||A.value}),C=Me(),u=Na(),T=Bt(),F=Ft(),K=_r(),ee=La({flag:he,onAbort:K,onError:K}),{inMemoryGooglePayParts:{paymentSheetOpenPromise:l,paymentSheetError:g},persistedGooglePaySignal:p,walletUsedForSubmissionSignal:w}
1=J(),{trackAttempt:H,trackComplete:M}=wa(B.GooglePay),U=x(async({reason:S})=>{_?await ee({wallet:"GOOGLE_PAY",reason:S,asPaymentMethod:!1,announceSubscriptionReviewLayoutSwitch:S==="subscriptions"}):(c.wallets.setEscalatedWallet("GOOGLE_PAY"),F?.dispatch("addressReplaced"))},[ee,_,F,c.wallets]);return x(({isShippingRequired:S,paymentData:b,cardsinkResult:G})=>new Promise(Q=>{const X=performance.now();i.leaveErrorBreadcrumb("[GooglePay] usePaymentAuthorized, attempting completion",{shippingAddressCity:b.shippingAddress?.locality??"MISSING",shippingAddressAdministrativeArea:b.shippingAddress?.administrativeArea??"MISSING",shippingAddressCountryCode:b.shippingAddress?.countryCode??"MISSING",billingAddressCity:b.paymentMethodData.info?.billingAddress?.locality??"MISSING",billingAddressAdministrativeArea:b.paymentMethodData.info?.billingAddress?.administrativeArea??"MISSING",billingAddressCountryCode:b.paymentMethodData.info?.billingAddress?.countryCode??"MISSING"}),H();const O=()=>{M({result:"failed",durationMs:performance.now()-X})},q=b.shippingAddress,L=b.paymentMethodData.info?.billingAddress,$=b.paymentMethodData,ie=d.value.isRequired("address2"),Ie=m.validatePaymentCurrency({initialCurrencyCode:p.value?.initialCurrencyCode,currentCurrencyCode:I.current.fields.subtotal?.value?.currencyCode}),ge=m.validateBilling(b),pe=m.validateShipping(b,S,ie);if(i.leaveErrorBreadcrumb("[GooglePay] usePaymentAuthorized: validation results",{paymentValidationResult:Ie,billingValidationResult:ge,shippingValidationResult:pe}),Ie.paymentSheetAction)return O(),oe(Ie.paymentSheetAction);if(ge.paymentSheetAction)return O(),oe(ge.paymentSheetAction);if(pe.paymentSheetAction)return O(),oe(pe.paymentSheetAction);if(ge.shouldPersist&&L&&(r.value=Ne({googleAddress:L,isFirstNameRequired:d.value.isRequired("firstName")})),pe.shouldPersist&&q){const V=q.iso3166AdministrativeArea;T({postalCode:q.postalCode,countryCode:q.countryCode,city:q.locality,zoneCode:V},"GOOGLE_PAY"),v||(a.value=Ne({googleAddress:q,isFirstNameRequired:d.value.isRequired("firstName")}))}const Ge=h.buyerIdentity.value?.customerProfile?.email||b.email;Ge&&(e.value=Ge),u(),p.value={...p.value,description:$.description,receiptIdForPaymentFailure:void 0};const Le=o.value,{signature:It,signedMessage:ft,protocolVersion:Rt}=b.paymentMethodData.tokenizationData.token?JSON.parse(b.paymentMethodData.tokenizationData.token):{signature:"",signedMessage:"",protocolVersion:""},Nt=V=>{if(V){if(G&&"error"in G)return i.leaveErrorBreadcrumb("[GooglePay] Cardsink deposit failed in sandbox",{error:G.error}),i.counter({name:"wallet_authorization_cardsink",value:1,attributes:{status:"failed",instrument:B.GooglePay}}),oe({action:"show_error",errors:[{reason:"PAYMENT_DATA_INVALID",message:"Failed to process payment",intent:"PAYMENT_AUTHORIZATION"}]}),!1;G&&"sessionId"in G&&(i.leaveErrorBreadcrumb("[GooglePay] Using sessionId from sandbox cardsink",{sessionId:G.sessionId}),i.counter({name:"wallet_authorization_cardsink",value:1,attributes:{status:"success",instrument:B.GooglePay}}),o.value=Be(Le,{method:{type:"wallet",name:"GOOGLE_PAY",walletContent:{protocolVersion:"",signature:"",signedMessage:"",sessionId:G.sessionId,paymentMethodIdentifier:f.value?.paymentMethodIdentifier}}}))}return!0},bt=()=>{const V=I.current.fields.paymentDue.value,Y=V&&V.amount>0||y.value;return G?Nt(Y):(Y&&(o.value=Be(Le,{method:{type:"wallet",name:"GOOGLE_PAY",walletContent:{signature:It,signedMessage:ft,protocolVersion:Rt,paymentMethodIdentifier:f.value?.paymentMethodIdentifier}}})),!0)};let te=0;const Ot=ba(I.current.fields.deliveryNext?.value),we=async()=>{let V=!1;i.leaveErrorBreadcrumb("[GooglePay] usePaymentAuthorized, payment authorized completion attempt",{attemptNumber:te}),await n("google-pay-payment-authorized",async Y=>{i.leaveErrorBreadcrumb("[GooglePay] usePaymentAuthorized, payment authorized completion result",{result:{status:Y.status,violations:("violations"in Y?Y.violations:[])||[],errors:("errors"in Y?Y.errors:[])||[]}}),Y.status==="success"&&(w.value="GOOGLE_PAY"),(Y.status==="denied"||Y.status==="throttled"||Y.status==="tooManyRequests")&&C();const le=Y,Dt=le.status==="rejected"&&le.violations.some(Ct=>Ct.code===Se),{shouldRetry:Tt,retryReason:He,updatedDeliveryMethodHandles:Ye}
1=hr(le,te,I,Ot);if(Ye&&me(t,Ye),Tt&&!Dt){te++,i.counter({name:"wallet_submit_for_completion_retry",value:1,attributes:{retry_reason:He,retry_count:te,status:le.status,instrument:B.GooglePay}}),i.log("payment_authorized_completion_retried",`GooglePay::usePaymentAuthorized: Retrying ${He} completion`,{attemptNumber:te}),we();return}const Ee=m.completionResultMapper.mapResultToPaymentSheetAction(le);i.leaveErrorBreadcrumb("[GooglePay] usePaymentAuthorized, payment sheet action mapper result",{paymentSheetAction:Ee});const Ue=Ee.action==="show_error"||Ee.action==="abort"?"failed":"success";try{await oe(Ee)}finally{M({result:Ue,durationMs:performance.now()-X,attributes:{retry_count:te>0?te.toString():void 0}}),i.leaveErrorBreadcrumb("[GooglePay] usePaymentAuthorized, authorization result",{authorizationResult:Ue}),R.value&&(Y.status==="rejected"||Y.status==="invalid")&&(g.value||(g.value={type:"recovery_notice"}),_?V=!0:U({reason:"submitForCompletion"}))}},{skipToCompletion:!0,customizeCompletion:Oa}),V&&U({reason:"submitForCompletion"})};bt()&&(A.value?oe({action:"decelerate",effects:[()=>{g.value=void 0}]}).finally(()=>U({reason:"subscriptions"})).catch(V=>{i.leaveErrorBreadcrumb("[Google Pay] Failed to handle payment sheet action:",{err:V})}):we());async function oe(V){if(V.effects?.forEach(Y=>Y()),V.action==="show_error"){i.leaveErrorBreadcrumb("[GooglePay] usePaymentAuthorized, resolving with error",{paymentSheetAction:V}),Q({transactionState:"ERROR",error:V.errors?.[0]});return}else i.leaveErrorBreadcrumb("[GooglePay] usePaymentAuthorized, resolving with success"),Q({transactionState:"SUCCESS"}),await l.value}}),[d,C,f,h,y,I,l,m,p,n,r,t,e,o,a,w,T,i,g,u,v,R,A,U,_,H,M])}function hr(t,e,a,r){const o={shouldRetry:!1,retryReason:"",updatedDeliveryMethodHandles:void 0};if(e>=mr)return o;if(t.status==="stale")return{shouldRetry:!0,retryReason:"stale",updatedDeliveryMethodHandles:void 0};if(t.status==="fetch_failed")return{shouldRetry:!0,retryReason:"fetch_failed",updatedDeliveryMethodHandles:void 0};if(t.status==="rejected"&&t.violations?.length){const n=Da(t,a.current.fields.deliveryNext?.peek(),r);if(n)return{shouldRetry:!0,retryReason:"delivery_option_mismatch",updatedDeliveryMethodHandles:n}}return o}const qe={paymentMethod:{walletPaymentMethod:{name:"GOOGLE_PAY",walletContent:{googlePayWalletContent:{signature:"",signedMessage:"",protocolVersion:""}}}},amount:{any:!0}};function vr({googlePayTransactionId:t}){const{deliveryLines:e,shippingAddress:a}=Pe(),r=Pt(),{checkout:o,i18n:n,observability:s,shop:c}=z(),i=o.configuration.addressSettings.nonBillingAddressSettings,d=Me(),{persistedGooglePaySignal:y}=J(),h=Ta(),N=ce(),{value:P}=N.deliveryNext,v=N.availableDeliveryAddresses?.value,I=N.mustSelectProvidedAddress?.value,E=Ae({availableDeliveryAddresses:v,mustSelectProvidedAddress:I}),D=o.isShippingRequired.value&&!E,_=je(c),R=o.configuration.layout.isOnePage.value,A=c.hasFlagEnabled(he),f=R||A,m=re(()=>f&&Oe({checkout:o})),C=x(l=>l.reduce((g,p,w)=>w===l.length-1?n.translate("shipping.shipping_method_combinations.combination",{rest:g,current:p}):n.translate("shipping.shipping_method_combinations.with_separator",{rest:g,current:p}),""),[n]),u=de(()=>({businessDays:l=>n.translate("shipping.estimated_delivery_date",{count:l}),businessDaysRange:(l,g)=>n.translate("shipping.estimated_delivery_date_range",{minimum:l,maximum:g}),subscriptionsOnlyShippingTitle:n.translate("shipping.subscription_shipping"),combineTwoShippingTitles:(l,g)=>n.translate("shipping.shipping_method_combinations.combination",{rest:l,current:g}),combineMultipleShippingTitles:C}),[n,C]),T=x(({intent:l,trigger:g,result:p})=>{if(p.errors.some(O=>De.has(O.code)))return s.leaveErrorBreadcrumb("[GooglePay] usePaymentDataChanged negotiation error, stock problems"),{reason:"OTHER_ERROR",intent:l,message:n.translate("wallets.errors.detour.stock_problems",{walletName:n.translate("brand.google_pay")})};if(p.errors.some(O=>O.code===Se))return s.leaveErrorBreadcrumb("[GooglePay] usePaymentDataChanged negotiation error, price mismatch"),{reason:"OTHER_ERROR",intent:l,message:n.translate("wallets.errors.detour.price_change",{walletName:n.translate("brand.google_pay")})};if(p.errors.some(O=>na.has(O.code)))return s.leaveErrorBreadcrumb("[GooglePay] usePaymentDataChanged negotiation error, delivery zone not found",{zoneCode:p.negotiated.shippingAddress?.zoneCode,countryCode:p.negotiated.shippingAddress?.countryCode}),{reason:"SHIPPING_ADDRESS_INVALID",intent:l,message:n.translate("wallets.errors.invalid.zone")};if(p.errors.some(O=>Ce.includes(O.code)))return s.leaveErrorBreadcrumb("[GooglePay] usePaymentDataChanged negotiation error, no delivery strategy",{zoneCode:p.negotiated.shippingAddress?.zoneCode,countryCode:p.negotiated.shippingAddress?.countryCode}),{reason:"SHIPPING_ADDRESS_UNSERVICEABLE",intent:l,message:n.translate("wallets.errors.unsupported.address")};if(!sa(p.negotiated.paymentMethods,"GOOGLE_PAY"))return s.leaveErrorBreadcrumb("[GooglePay] usePaymentDataChanged negotiation error, google pay unavailable"),{reason:"SHIPPING_ADDRESS_UNSERVICEABLE",intent:l,message:n.translate("wallets.errors.unsupported.wallet_is_unavailable",{walletName:n.translate("brand.google_pay")})};const b=y.value;if(b?.initialCurrencyCode!==p.negotiated.subtotal?.currencyCode)return s.leaveErrorBreadcrumb("[GooglePay] usePaymentDataChanged negotiation error, currency change",{beforeCurrencyCode:b?.initialCurrencyCode,afterCurrencyCode:p.negotiated.subtotal?.currencyCode}),{reason:"OTHER_ERROR",intent:l,message:n.translate("wallets.errors.detour.currency_change",{walletName:n.translate("brand.google_pay")})};const Q=g==="INITIALIZE";if(p.errors.some(O=>Te.includes(O.code))&&!Q)return s.leaveErrorBreadcrumb("[GooglePay] usePaymentDataChanged negotiation error, delivery line changed"),{reason:"SHIPPING_OPTION_INVA
1LID",intent:l,message:n.translate("wallets.errors.outdated.shipping_method")}},[y,n,s]),F=x(({result:l,intent:g,trigger:p,resolve:w,reject:H,shippingOptionId:M,destinationCountry:U,destinationRegion:S,abortSignal:b})=>{function G(){return H({reason:"OTHER_ERROR",message:n.translate("wallets.errors.generic",{walletName:n.translate("brand.google_pay")}),intent:g})}if(b.aborted)return s.leaveErrorBreadcrumb("[GooglePay] usePaymentDataChanged result arrived after the session was aborted"),G();switch(s.leaveErrorBreadcrumb("[GooglePay] usePaymentDataChanged received negotiation result",{status:l.status,intent:g,trigger:p}),l.status){case"success":{if(l.negotiated.paymentDue==null)return s.error(new _e("Missing negotiated paymentDue",{groupingHash:"GooglePayGenericError::MissingNegotiatedPaymentDue"})),G();const Q=la(l.negotiated.deliveryNext),X=t.value,O=qa({...l.negotiated,labels:r,i18nCurrency:n.currency,translations:u,selectedShippingId:M,deliveryMacros:Q,googlePayTransactionId:X,shouldWalletDecelerateForSubscriptions:m.value,discountsZeroValueUXEnabled:_});if(O.error=T({intent:g,trigger:p,result:l}),D&&!O.newShippingOptionParameters&&!O.error){const L=l.negotiated.deliveryNext&&l.negotiated.deliveryNext.status!=="unavailable"?l.negotiated.deliveryNext.lines:[],$={wallet:"google_pay",intent:g,trigger:p,googlePayTransactionId:X,destinationCountry:U,destinationRegion:S,deliveryNextStatus:l.negotiated.deliveryNext?.status,deliveryLineCount:L.length,deliveryLineStatuses:L.map(ie=>ie.status).join(",")};s.log("google_pay_missing_shipping_options","wallet_missing_shipping_options",$),s.leaveErrorBreadcrumb("[GooglePay] usePaymentDataChanged resolved with no shipping options and no error",$)}return s.leaveErrorBreadcrumb("[GooglePay] usePaymentDataChanged handleNegotiationResult",{result:l.status,intent:g,trigger:p,transactionInfo:O.newTransactionInfo?JSON.stringify(O.newTransactionInfo):"MISSING"}),w(O)}case"throttled":return d(),H({reason:"OTHER_ERROR",message:n.translate("wallets.errors.detour.queue",{walletName:n.translate("brand.google_pay")}),intent:g});case"tooManyRequests":case"denied":case"alreadyCompleted":return d(),G();case"invalid":return l.reasons.includes(ia.SubmittedForCompletion)?(s.log("payment_data_changed_negotiation_rejected","wallet_rejected_negotiation",{wallet:"google_pay",reason:"invalid",intent:g,trigger:p,reasons:l.reasons}),s.counter({name:"wallet_rejected_negotiation",value:1,attributes:{wallet:"google_pay",reason:"invalid"}}
1)):s.error(new ir("Received unhandled invalid result",{groupingHash:"GooglePayInvalidError::UnhandledInvalidResult"}),{metadata:{request:{reasons:l.reasons}}}),G();case"stale":return s.log("payment_data_changed_negotiation_rejected","wallet_rejected_negotiation",{wallet:"google_pay",reason:"stale",intent:g,trigger:p}),s.counter({name:"wallet_rejected_negotiation",value:1,attributes:{wallet:"google_pay",reason:"stale"}}),G();default:return s.error(new _e(`Unhandled negotiation status: ${l.status}${"error"in l&&l.error?`, ${l.error}`:""}`,{groupingHash:"GooglePayGenericError::UnhandledNegotiationStatus"})),G()}},[d,n,r,u,T,s,m,D,t,_]),K=x((l,g,p)=>g?new Promise((w,H)=>{st(P)||me(e,void 0);const M=p==="INITIALIZE"?l.initiallySelectedShippingOptionId:void 0,U=ja({googleAddress:g,isFirstNameRequired:i.value.isRequired("firstName")});s.leaveErrorBreadcrumb("[GooglePay] usePaymentDataChanged negotiating for handleShippingAddressSelected",{trigger:p,city:g.locality,administrativeArea:g.administrativeArea,countryCode:g.countryCode}),E||(a.value=U),h({abortSignal:l.abortController.signal,fieldsToResolve:["deliveryNext","taxes"],customizeNegotiation:S=>({...Fe(S,U,{interfaceFlow:"GOOGLE_PAY",isConstrainedAddress:E,availableDeliveryAddresses:v,negotiatedDelivery:P}),payment:{...S.payment,totalAmount:{any:!0},paymentLines:ze(S.payment?.paymentLines,qe)}}),observability:s,walletName:B.GooglePay,onComplete:S=>F({result:S,intent:"SHIPPING_ADDRESS",trigger:p,resolve:w,reject:H,destinationCountry:g.countryCode,destinationRegion:g.administrativeArea,...M&&{shippingOptionId:M},abortSignal:l.abortController.signal}),logPrefix:"GooglePay::usePaymentDataChanged::handleShippingAddressSelected"}).catch(S=>{F({result:S instanceof xe?{status:"stale"}:{status:"unexpected_error",error:S},intent:"SHIPPING_ADDRESS",trigger:p,resolve:w,reject:H,destinationCountry:g.countryCode,destinationRegion:g.administrativeArea,abortSignal:l.abortController.signal})})}):Promise.resolve({}),[i,F,a,e,h,s,P,E,v]),ee=x((l,g,p)=>new Promise((w,H)=>{let M;try{M=Ca(za(g))}catch{return s.error(new _e(`Invalid shippingOptionId format: ${g}`,{groupingHash:"GooglePayGenericError::InvalidShippingOptionId"}
1)),w({error:{reason:"SHIPPING_OPTION_INVALID",message:n.translate("general.choose_delivery_strategy"),intent:"SHIPPING_OPTION"}})}me(e,M);const U=a.value;s.leaveErrorBreadcrumb("[GooglePay] usePaymentDataChanged negotiating for handleShippingMethodSelected",{trigger:p}),h({abortSignal:l,fieldsToResolve:["deliveryNext","taxes"],customizeNegotiation:S=>({...Fe(S,U,{interfaceFlow:"GOOGLE_PAY",isConstrainedAddress:E,availableDeliveryAddresses:v,negotiatedDelivery:P}),payment:{...S.payment,totalAmount:{any:!0},paymentLines:ze(S.payment?.paymentLines,qe)}}),observability:s,walletName:B.GooglePay,onComplete:S=>F({result:S,intent:"SHIPPING_OPTION",trigger:p,resolve:w,reject:H,shippingOptionId:g,abortSignal:l}),logPrefix:"GooglePay::usePaymentDataChanged::handleShippingMethodSelected"}).catch(S=>{F({result:S instanceof xe?{status:"stale"}:{status:"unexpected_error",error:S},intent:"SHIPPING_OPTION",trigger:p,resolve:w,reject:H,shippingOptionId:g,abortSignal:l})})}),[F,n,a,e,h,s,E,v,P]);return x(async({sessionData:l,intermediatePaymentData:g})=>{function p(U,S,b){return{error:{reason:U,message:S,intent:b}}}const{shippingAddress:w,shippingOptionData:H,callbackTrigger:M}=g;switch(M){case"INITIALIZE":case"SHIPPING_ADDRESS":return K(l,w,M);case"SHIPPING_OPTION":return H?.id?ee(l.abortController.signal,H.id,M):p("SHIPPING_OPTION_INVA
1LID",n.translate("general.choose_delivery_strategy"),"SHIPPING_OPTION");default:return s.error(new _e(`Could not recognize the intent: ${M}`,{groupingHash:"GooglePayGenericError::CannotRecognizeIntent"})),s.leaveErrorBreadcrumb("[GooglePay] usePaymentDataChanged could not recognize the intent",{callbackTrigger:M}),p("OTHER_ERROR",n.translate("wallets.errors.generic",{walletName:n.translate("brand.google_pay")}),"SHIPPING_ADDRESS")}},[K,ee,s,n])}const Pr="QIbE6",Ar={GooglePayButtonContainerSpinnerDisplayed:Pr};function Br({asPaymentMethod:t=!1}){const e=ne(null),a=ue(null),r=ne(!1),{isScrimOpen:o,closePopupWindowsAndScrim:n}=xt({endpoint:a,invokingWallet:"GOOGLE_PAY"}),s=Wt(),c=At(),i=ve("GOOGLE_PAY").value,{value:d}=ce().deliveryNext,{i18n:y,checkout:{wallets:h,proposal:N},client:{userAgent:P},shop:v}=z(),I=ne({abortController:Qe(),initiallySelectedShippingOptionId:void 0}),E=ue(void 0),{inMemoryGooglePayParts:{sdkStatus:D,buttonStatus:_}}=J(),{markAsLoaded:R}=da(),A=ne(!0),f=ne(!1),m=er({asPaymentMethod:t}),C=ne(null),{checkoutCardsinkCallerIdentificationSignature:u}=N.negotiated.fields,T=de(()=>{if(!v.cardsinkUrl)return;const L=window.location.host;return{isLocalDev:L.endsWith("checkout.my.shop.dev")||L.endsWith("checkout.shop.dev"),cardsinkUrl:v.cardsinkUrl,callerIdentificationJwt:u.value}},[v.cardsinkUrl,u]),F=t?y.translate("wallets.call_to_action",{walletName:""}):void 0,K=y.translate("brand.google_pay"),ee=ur({endpoint:a,isTerminated:r,color:s,config:i,merchantInfo:c.value,buttonLabel:F,ariaLabel:K,markAsLoaded:R,sdkStatus:D,sdkStatusRef:e,buttonStatus:_,paymentDataRequest:m,containerRef:C,asPaymentMethod:t,isFirstRender:A,updateSdkStatus:$e,connectedNullPaymentDataRequest:f,cardsinkConfig:T}),l=dr({paymentDataRequest:m,asPaymentMethod:t,isScrimOpen:o,containerRef:C,endpoint:a}),g=lr(o),p=vr({googlePayTransactionId:E}),w=yr(),H=ga(),M=ua(),U=ca({onPaymentAuthorized:w,onPaymentDataChanged:L=>p({sessionData:I.current,intermediatePaymentData:L}),onClick:async({transactionId:L}={})=>(L&&(E.value=L),st(d)&&(I.current.initiallySelectedShippingOptionId=mt($t({proposedDeliveryLines:N.proposed.deliveryLines}))),await l()),onResponse:L=>{const $=I.current.abortController;I.current={abortController:Qe(),initiallySelectedShippingOptionId:void 0};const ie=g(L);return $.abort(),ie},telemetry:H,breadcrumb:M});Mt(()=>{const L=!A.current||f.current;a.value&&m.value&&L&&(f.current=!1,a.value.call.updatePaymentDataRequest(m.value))}),Gt(()=>($e({status:"loading"},D,e),()=>{const L=D.value,$=_.value;L===e.current&&$.status!=="error"&&(D.value={status:"idle"},_.value={status:"not_rendered"},h.activeSession.value?.wallet==="GOOGLE_PAY"&&h.clearActiveSession({invokingWallet:"GOOGLE_PAY"}))}),[]);const S=t?tr:void 0,b=j(ke,{inlineAlignment:"center",children:j(qt,{size:"large"})}),G=!Va(P),Q=Xe(!G),X=j(Zt,{isOpen:o,isInvisible:Q,onClick:n,children:G&&j(zt,{handleClose:n,walletName:y.translate("brand.google_pay")})}),O=j(Ve,{children:[j(pa,{wallet:be,onConnect:ee,onTerminate:()=>{r.current=!0,a.value=null},hostMethods:U,ref:C,height:S}),X]}),q=t&&_.value.status!=="rendered"&&_.value.status!=="error";return t?j(Ve,{children:[q&&b,j(ke,{className:Lt({[Ar.GooglePayButtonContainerSpinnerDisplayed]:q}),children:O})]}):O}function $e(t,e,a){a.current=t,e.value=a.current}function Qe(){return new AbortController}export{Br as default};
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.