PageSourceSearch

https://juniperbooks.com/cdn/shopifycloud/checkout-web/assets/c1/actions.B8CuxFwT.js

js juniperbooks.com collected 2026-09-25 18:34:59 UTC 92,778 bytes, 1 lines download raw bytes

1import{ii as Yn,dh as Wn,b0 as Qn,e as it,ij as Ht,gv as zn,cu as U,i8 as kt,br as Et,ik as jn,ib as Yt,V as Ve,il as $n,bA as le,im as Kn,au as Jn,bw as Xn,w as Wt,l as Zn,v as eo,gN as to,eD as Qt,x as no,b3 as zt,io as oo,ip as jt,k as $t,eW as Kt,iq as Jt,aP as so,ir as io,c0 as ro,is as ao,it as lo,b4 as uo,p as co,c5 as mo,h3 as po,g1 as ho,n as yo,t as fo,gf as go,H as vo,iu as ut,iv as bo,iw as Rt,ix as _o,iy as Xt,iz as So,iA as Ao,iB as Io,eX as To,iC as Mo,iD as Co,iE as Po,eY as ko,iF as ot,aC as De,eZ as Eo,iG as Ro,eC as Fo,iH as Lo,iI as xo,iJ as Do,iK as No,iL as wo,iM as Oo,ai as Bo,iN as Uo,iO as Vo,iP as Go,iQ as qo,iR as Ho,iS as Yo,iT as ct,iU as Wo,cO as Qo,iV as zo,bk as jo,iW as $o,iX as Zt,iY as Ko,iZ as en,i_ as J,i$ as tn,em as Jo,cP as Xo,ci as Zo}from"./addresses-is-address-empty.Bn2lNY_L.js";import{gY as es,gZ as ts,g_ as ns,g$ as os,h0 as ss,h1 as is,h2 as rs,h3 as nn,h4 as on,h5 as rt,h6 as as,h7 as ds,h8 as ls,h9 as us,ha as cs,hb as ms,hc as ps,hd as hs,he as ys,hf as fs}from"./hydrate.DZ4YTm7p.js";import{c as sn,a as rn,V as at,r as gs,ah as vs,H as bs,M as _s,L as Ss}from"./esnext-vendor.B9Da21W6.js";import{s as As,g as Ne,a as Ue,d as Ge,b as Ft}from"./MarketsProDisclaimer.BqGHM17j.js";import{g as Is,e as Ts}from"./Page.jjGbeNkl.js";import{s as Ms,i as Cs}from"./negotiated-findSelectedDeliveryMethod.DuEyfwut.js";import{t as Ps,d as an,a as ks,b as Es,s as Rs,c as Fs,e as Ls,f as xs,g as Ds,h as Ns,i as ws,j as Os,m as Bs,k as Us,l as Vs,p as Gs,n as qs,o as Hs}from"./shared-receipt-mapper-load-recovery.Ci5IIc7r.js";import{S as mt,j as Ys}from"./app.DbSrjjlA.js";import{d as dn}from"./shared-report-graphql-error.0sJ2-gTk.js";import{t as ln,a as Lt,b as Ws,d as Qs,s as zs,f as js,g as $s,i as Ks,r as Js,o as Xs}from"./shared-receipt-eager-mappers.BEm77m4Q.js";import"./graphql-PaymentSessionMutation.CAXCwUvV.js";import"./hooks-useShopPayExternalAppContext.DWwMuRnz.js";import"./hooks-useReplaceShopPayInHistory.DPpLejwu.js";function Zs({buyerEditedAddress:e,shopUserSecureData:t,shopPayVerificationTrigger:o,customerProfile:n}){if(e)return;if(!!t&&o==null)return"SHOP_PAY";if(n)return"CUSTOMER"}function un(e=[]){return new Set([...(e??[]).map(({stableId:t})=>t),...(e??[]).flatMap(({lineComponents:t})=>t.map(({stableId:o})=>o))])}class xt extends Error{constructor(){super(...arguments),this.name="UnknownMerchandiseTypeError"}}function ei(e){let t=null;const o=()=>(t===null&&(t=new Map(e.lines.map(n=>[n.stableId,n]))),t);return{merchandiseLines:e.lines.map(n=>({...dt(n,o),lineComponentsSource:n.lineComponentsSource,lineComponents:n.lineComponents.map(s=>dt(s,o))}))}}function ti(e){switch(e.typename){case"ContextualizedProductVariantMerchandise":case"ProductVariantMerchandise":return{productVariantReference:{id:e.id,variantId:e.variantId,properties:Dt(e.properties),sellingPlanId:e.sellingPlan?.id??null,sellingPlanDigest:e.sellingPlan?.digest??null}};case"SourceProvidedMerchandise":if(!Yn(e))throw new xt("Source-provided merchandise is missing the fields only the server can supply");return{sourceProvidedMerchandise:{title:e.title,subtitle:e.subtitle??void 0,price:{value:{amount:e.itemPrice.amount.toFixed(2),currencyCode:e.itemPrice.currencyCode}},giftCard:e.giftCard,productType:e.productType,sku:e.sku,variantId:e.variantId??void 0,productIdV2:e.productId??void 0,properties:Dt(e.properties),requiresShipping:e.requiresShipping,vendor:e.vendor??void 0,taxCode:e.taxCode??void 0,taxable:e.taxable??!0,taxesIncluded:e.taxesIncluded,optionalIdentifier:e.optionalIdentifier??void 0,weight:e.weight?{value:e.weight.value,unit:e.weight.unit}:void 0}};default:throw new xt(`Unrecognized merchandise type: ${e.typename}`)}}function Dt(e){return e.map(t=>{switch(t.sourceType){case"MerchandisePropertyValueNull":return{name:t.name,value:t.value};case"MerchandisePropertyValueString":return{name:t.name,value:{string:t.value}};case"MerchandisePropertyValueInt":return{name:t.name,value:{integer:t.value}};case"MerchandisePropertyValueFloat":return{name:t.name,value:{float:t.value}};case"MerchandisePropertyValueBoolean":return{name:t.name,value:{boolean:t.value}};case"MerchandisePropertyValueJson":return{name:t.name,value:{json:JSON.parse(t.value)}};default:rn(t)}})}function ni(e){if(!e)return{any:!0};const{currencyCode:t}=e;return{value:{amount:e.amount.toFixed(sn(t)),currencyCode:t}}}function dt(e,t){const o={stableId:e.stableId,merchandise:ti(e),quantity:{items:{value:e.quantity}},expectedTotalPrice:ni(e.totalPrice)};if("parentRelationship"in e&&e.parentRelationship?.parent){const n=t().get(e.parentRelationship.parent.stableId);n&&(o.parent=dt(n,t))}return o}function oi(e){if(e)return{total:{amount:e.total.amount.toString(),currencyCode:e.total.currencyCode}}}function si(e){if(!(!e||e.length===0))return{availableRedeemables:e.map(Is)}}function ii(e){if(e)return{provider:e.provider,challenge:e.challenge,token:e.token}}function ri(e){const t=e.find(o=>o.peek().type==="ONE_TIME_PURCHASE");if(t)return t.peek().deliveryMethodOptions}function ai({shippingAddress:e,proposedDeliveryLines:t,externalDeliveryIds:o,destinationChanged:n,isSubmitForCompletion:s,isPointOfSale:i,isPointOfSaleShipToHome:r,negotiatedDelivery:d,filteredMerchandiseStableIds:a,locationAddress:l,geolocationCoordinates:m,retailLocationId:u,isShippingRequired:f,availableDeliveryAddresses:I,isConstrainedAddress:v,extendedAddressMode:S,marketDrivenShippingEnabled:T,stableIdToShopId:y,remoteShopsConfigMap:h}){const C=d?.status==="filled"?d.lines.map(({type:p})=>p):[],A=t.sort((p,c)=>{const g=p.peek().type,M=c.peek().type;return C.indexOf(g)-C.indexOf(M)}),w=ri(A),F=d?.status==="filled"&&d.sourceIsBuyerProposal,k=A.map(p=>{const c=p.peek(),g=d?.status==="filled"&&d?.lines.find(({type:M,id:P})=>M===c.type&&(!P||P===c.id))||void 0;return{proposedDeliveryLine:c,negotiatedDeliveryLine:g}}),_=k.map(({proposedDeliveryLine:p,negotiatedDeliveryLine:c})=>{const g=di({proposedDeliveryLine:p,filteredMerchandiseStableIds:a,marketDrivenShippingEnabled:T,stableIdToShopId:y,remoteShopsConfigMap:h}),M=li(p,c);return{...g,enabled:g.enabled||g.remoteConfigMissing&&!!M?.token,rate:M}}),E=_.some(({enabled:p})=>p)?Wn(_,({rate:p})=>p?.amount??0,({enabled:p,shopId:c,rate:g})=>p&&g?.token?`${c}:${g.token}`:void 0):new Set;return k.map(({proposedDeliveryLine:p,negotiatedDeliveryLine:c},g)=>ui({shippingAddress:e,proposedDeliveryLine:p,externalDeliveryIds:o,destinationChanged:n,negotiatedDeliveryLine:c,filteredMerchandiseStableIds:a,locationAddress:l,geolocationCoordinates:m,proposedAlternateOptions:w,isSubmitForCompletion:s,isPointOfSale:i,isPointOfSaleShipToHome:r,retailLocationId:u,isShippingRequired:f,availableDeliveryAddresses:I,isConstrainedAddress:v,negotiatedSourceIsBuyerProposal:F,extendedAddressMode:S,foldExpectedTotalPriceToZero:E.has(g)}))}function di({proposedDeliveryLine:e,filteredMerchandiseStableIds:t,marketDrivenShippingEnabled:o,stableIdToShopId:n,remoteShopsConfigMap:s}){const i=cn(e.targetMerchandiseLines,t)[0]?.stableId,r=i?n?.get(i):void 0;if(r){const d=s?.get(r);return{shopId:r,enabled:d?.marketDrivenShippingEnabled??!1,remoteConfigMissing:!d}}return{shopId:"local",enabled:o,remoteConfigMissing:!1}}function li(e,t){const o=e.deliveryMethodHandle;if(!t||t.status==="not_required"||!o)return;const n=t.methods.find(({handle:s})=>s===o);if(n?.cost)return{amount:n.cost.amount,token:Qn(n)}}function ui({shippingAddress:e,proposedDeliveryLine:t,externalDeliveryIds:o,destinationChanged:n,negotiatedDeliveryLine:s,filteredMerchandiseStableIds:i,locationAddress:r,geolocationCoordinates:d,proposedAlternateOptions:a,isSubmitForCompletion:l,isPointOfSale:m,isPointOfSaleShipToHome:u,retailLocationId:f,isShippingRequired:I,availableDeliveryAddresses:v,isConstrainedAddress:S=!1,negotiatedSourceIsBuyerProposal:T=!1,extendedAddressMode:y,foldExpectedTotalPriceToZero:h=!1}){const C=t.targetMerchandiseLines.filter(({stableId:D})=>i.has(D)),A=C.length?C.some(({requiresShipping:D})=>D):void 0,w=s?.targetMerchandiseLines?.some(({requiresShipping:D})=>D),F=A??I??w??!0,{deliveryMethodHandle:k,deliveryMethodTypes:_,deliveryMethodOptions:E,targetMerchandiseLines:p,isCustomRate:c,customDeliveryStrategy:g}=t,M=s?.status==="available"?s?.selectedDeliveryMethodHandle:void 0,P=ci({proposedHandle:k,negotiatedHandle:M,canOverwriteNullishProposedHandle:T||S});let L;s?.status==="available"?L=s.methods.find(({handle:G})=>G===(k??P))?.isCustomRate??c:L=c;const x=As({deliveryMethodHandle:P,deliveryMethodOptions:{instructions:E.instructions??a?.instructions,phone:E.phone??a?.phone},isCustomRate:L,isPointOfSale:m,retailLocationId:f,isPointOfSaleShipToHome:u,customDeliveryStrategy:g});mi(x,o);const O=pi({proposedTargetMerchandiseLines:p,filteredMerchandiseStableIds:i,hasMatchingNegotiatedDeliveryLine:!!s,isShippingRequired:I});let R;m&&!u?R=["RETAIL"]:F?R=_:R=["NONE"];const N=R.length>0&&R.every(D=>D==="PICK_UP"),W=R.includes("PICKUP_POINT"),H=F&&!N;let B;const z=v?.find(D=>it(D.address,e,["phone","zoneCode"])),X=v?.find(D=>it(D.address,e,["phone","zoneCode"])&&Ht(D.address,e));H?W&&r?B=Ne(r,{extendedAddressMode:y}):S?B={deliveryAddressReference:Ue(v[0].address)}:X?B={deliveryAddressReference:Ue(X.address)}:l?B={streetAddress:Ge(e,{extendedAddressMode:y})}:B={partialStreetAddress:Ge(e,{extendedAddressMode:y})}:N&&(z?B={deliveryAddressReference:Ue(z.address)}:r?.coordinates?B=Ne(r,{extendedAddressMode:y}):r?.postalCode?B=Ne(r,{extendedAddressMode:y}):d&&r?.countryCode&&(B=Ne({countryCode:r.countryCode,coordinates:d},{extendedAddressMode:y})));const Q=hi(s,k,h);return{destination:B,selectedDeliveryStrategy:x,targetMerchandiseLines:O,deliveryMethodTypes:R,expectedTotalPrice:Q,destinationChanged:n}}function ci({proposedHandle:e,negotiatedHandle:t,canOverwriteNullishProposedHandle:o}){return o?e??t:e}function mi(e,t){t?.externalCheckoutSessionId&&(e.externalCheckoutSessionId=t.externalCheckoutSessionId),t?.externalCustomerId&&(e.externalCustomerId=t.externalCustomerId),t?.externalPromiseId&&(e.externalPromiseId=t.externalPromiseId)}function pi({proposedTargetMerchandiseLines:e,filteredMerchandiseStableIds:t,hasMatchingNegotiatedDeliveryLine:o,isShippingRequired:n}){const s=cn(e,t);return s.length?{lines:s}:n?n&&!o?{any:!0}:{lines:[]}:{any:!0}}function cn(e,t){return e.reduce((o,{stableId:n})=>n&&t.has(n)?[...o,{stableId:n}]:o,[])}function hi(e,t,o=!1){const n={any:!0};if(!e||e.status==="not_required"||!t)return n;const{methods:s}=e,i=s.find(({handle:a})=>a===t)?.cost;if(!i)return n;const r=sn(i.currencyCode);return{value:{amount:(o?0:i.amount).toFixed(r),currencyCode:i.currencyCode}}}function mn(e,t){if(e.anyAllocation)return{anyAllocation:e.anyAllocation};const o=un(t);return{allocated:{allocations:e.allocations.reduce((n,s)=>{const{target:{type:i,amount:r,stableId:d}}=s;if(i==="MERCHANDISELINE"){if(d){if(!o.has(d))return n;n.push({amount:{value:{amount:r.amount.toString(),currencyCode:r.currencyCode}},target:{merchandiseLineTarget:{stableId:d}}})}}else n.push(yi(s));return n},[])}}}function yi(e){const{target:{index:t,amount:{currencyCode:o,amount:n}}}=e;return{amount:{value:{amount:n.toString(),currencyCode:o}},target:{deliveryLineTarget:{atIndex:t}}}}function fi(e,t,o){const n=mn(e,t);return!n.anyAllocation&&!n.allocated.allocations.length&&o?.leaveErrorBreadcrumb("discount.codeDiscountLineForGraphQL.no_allocation",{discountType:e.discount.type,discountTitle:e.discount.title,discountValue:e.discount.value}),{allocationSet:n,discount:{discountWithCode:e.discount.title},required:!0}}function Nt(e){switch(e.value?.typename){case"FixedAmountValue":{const{fixedAmount:{amount:t,currencyCode:o},appliesOnEachItem:n}=e.value;return{fixedAmountValue:{value:{amount:t.toString(),currencyCode:o},appliesOnEachItem:n}}}case"PercentageValue":{const{percentage:t}=e.value;return{percentageValue:{percentage:t.toString()}}}default:return{}}}function gi(e){const{signature:t="",signatureUuid:o=""}=e;return t.length&&o.length?{value:t,uuid:o}:null}function vi(e,t,o){const n=e.discount,s=mn(e,t);return s.anyAllocation||s.allocated.allocations.length?{allocationSet:s,discount:{customDiscount:{targetEntireCart:n.presentationLevel==="CART",title:n.title,de
1scription:n.description??null,value:Nt(n),signature:gi(n),type:n.discountType}},required:!0}:(o?.leaveErrorBreadcrumb("discount.customDiscountLineForGraphQL.no_allocation",{discountType:n.discountType,discountTitle:n.title,discountValue:Nt(n)}),null)}function bi(e){return{allocationSet:{anyAllocation:{totalAmount:{any:!0}}},discount:{discountWithCode:e.title},required:!0}}function _i(e,t,o){return e.lines.reduce((n,s)=>{let i=null;return zn(s)?i=bi(s):s.discount.type==="code"?i=fi(s,t,o):s.discount.type==="custom"&&(i=vi(s,t,o)),i!=null&&n.push(i),n},[])}function Si(e){return{signature:e.signature??void 0,contents:e.contents.map(t=>({signature:t.signature,targetTerms:t.targetTerms,targetLine:t.targetLine===void 0?void 0:{allLines:t.targetLine?.allLines??!1,index:t.targetLine?.index},attributes:t.attributes}))}}function Ai(e,t,o){return{message:t??e.note??null,customAttributes:o?.map(({...n})=>n)??e.customAttributes?.map(n=>({key:n.key,value:n.value}))??[]}}function Ii(e){return{buyerRefusesDuties:e}}function Ti({hasRegularSubscriptionPaymentTerms:e,isCompleting:t,allowAtNegotiation:o=!1,runningTotal:n,paymentDue:s,checkoutTotal:i,lines:r}){if(!e||!t&&!o||s!=null&&s.currencyCode!==i.currencyCode)return;const d=Mi({runningTotal:n,paymentDue:s,checkoutTotal:i}),a=Math.max(0,U(i.amount-(d?.amount??i.amount))),l=Ci({checkoutTotal:i,reflectedRedeemableAmount:a,lines:r}),m=l.hasPaymentMethodAmount||l.inferredFromConcreteRedeemables;let u=l.amount,f=0,I=Math.min(a,l.amount);const v=new Map,S=new Set;let T=!1;if(r.forEach(y=>{if(y.due||y.method.type!=="giftCard"&&y.method.type!=="redeemable")return;if(!t&&(y.cost==null||y.cost.amount<=0)){T=!0,S.add(y);return}if(!m){if(kt(y)){const C=Math.max(0,U(u));if(C===0){T=!0,S.add(y);return}u=Math.max(0,U(u-C)),f=U(f+C),v.set(y,{amount:C,currencyCode:i.currencyCode});return}T=!0,S.add(y);return}if(y.cost==null){const C=I<=0,A=Math.max(0,U(kt(y)&&C?u:Math.min(I,u)));if(A===0){T=!0,S.add(y);return}u=Math.max(0,U(u-A)),I=Math.max(0,U(I-A)),f=U(f+A),v.set(y,{amount:A,currencyCode:i.currencyCode});return}if(y.cost.amount<=0){T=!0,S.add(y);return}if(y.cost.currencyCode!==i.currencyCode)return;const h=Math.max(0,U(Math.min(y.cost.amount,u)));if(h===0){T=!0,S.add(y);return}u=Math.max(0,U(u-h)),I=Math.max(0,U(I-h)),f=U(f+h),v.set(y,{amount:h,currencyCode:i.currencyCode})}),!(v.size===0&&S.size===0))return{paymentMethodAmount:{amount:{amount:Math.max(0,U(l.amount-f)),currencyCode:i.currencyCode},fillAmount:!T},redeemableAmounts:v,unconstrainedRedeemableLines:S}}function Mi({runningTotal:e,paymentDue:t,checkoutTotal:o}){const n=[t,e].filter(s=>s!=null&&s.currencyCode===o.currencyCode);if(n.length!==0)return n.reduce((s,i)=>i.amount<s.amount?i:s)}function Ci({checkoutTotal:e,reflectedRedeemableAmount:t,lines:o}){const{hasPaymentMethodAmount:n,allocatedPaymentMethodAmount:s,allocatedRedeemableAmount:i}=o.reduce((r,d)=>d.due||d.cost==null||d.cost.currencyCode!==e.currencyCode?r:d.method.type==="giftCard"||d.method.type==="redeemable"?{...r,allocatedRedeemableAmount:U(r.allocatedRedeemableAmount+Math.max(0,d.cost.amount))}:{...r,hasPaymentMethodAmount:!0,allocatedPaymentMethodAmount:U(r.allocatedPaymentMethodAmount+Math.max(0,d.cost.amount))},{hasPaymentMethodAmount:!1,allocatedPaymentMethodAmount:0,allocatedRedeemableAmount:0});return n?{amount:Math.min(e.amount,U(s+i+t)),currencyCode:e.currencyCode,hasPaymentMethodAmount:n,inferredFromConcreteRedeemables:!1}:t>0||i>0?{...e,hasPaymentMethodAmount:n,inferredFromConcreteRedeemables:!0}:{...e,hasPaymentMethodAmount:n,inferredFromConcreteRedeemables:!1}}const wt={any:!0};function Pi({fixSubscriptionRedeemablePaymentAmount:e,hasRegularSubscriptionPaymentTerms:t,line:o,isCompleting:n,paymentDue:s,completionAmount:i,cost:r,coreAllocatesImmediateAmount:d}){if(!e||!t||o.due)return;if(n&&d){const l=s??r;return l==null?void 0:{amount:l,fillAmount:!1}}const a=n?i?.amount??r??s:s;if(a!=null)return{amount:a,fillAmount:n?i?.fillAmount??!0:!1}}class ki extends Error{constructor(){super(...arguments),this.name="MalformedDateStringError"}}class pn extends Error{constructor(){super(...arguments),this.name="BankPaymentLineDroppedError"}}function Ei(e,t,o){switch(e.name){case"PAYPAL_EXPRESS":{const n=e.walletContent,s=n?.payerApprovedAmount;return{name:"PAYPAL_EXPRESS",walletContent:{paypalWalletContent:{...n?.authAssertionContext&&{authAssertionContext:n.authAssertionContext},email:n?.email??"",payerId:n?.payerId??"",token:n?.token??"",expiresAt:n?.expiresAt??null,merchantId:n?.merchantId??null,currencyCode:n?.currencyCode??null,isVenmo:n?.isVenmo??null,...n?.isVaultWithPurchaseOrder&&{isVaultWithPurchaseOrder:!0},paymentMethodIdentifier:n?.paymentMethodIdentifier??"",...o&&{acceptedSubscriptionTerms:o},...t&&{vaultingAgreement:t},...s&&{payerApprovedAmount:{amount:s.amount,currencyCode:s.currencyCode}}}}}}case"SHOP_PAY":{const n=e.walletContent;if(n==null)return null;const s=n.creditCardInstallments?{installmentsCount:n.creditCardInstallments,intervalType:"MONTH"}:void 0;return{name:"SHOP_PAY",walletContent:{shopPayWalletContent:{sessionToken:n.sessionToken??"",billingAddress:{streetAddress:n.billingAddress},paymentAttributes:n.paymentAttributes,paymentMethod:n.paymentMethod,paymentMethodIdentifier:n.paymentMethodIdentifier??"",addressId:n.addressId,...n.hsaRequested!=null&&{hsaRequested:n.hsaRequested},...s&&{creditCardInstallmentPlan:s},...n.msiEligibleCard&&{msiEligibleCard:n.msiEligibleCard}}}}}case"APPLE_PAY":{const n=e.walletContent;return n==null?null:{name:"APPLE_PAY",walletContent:{applePayWalletContent:{paymentMethodIdentifier:n?.paymentMethodIdentifier,version:n?.version??"",data:n?.data??"",signature:n?.signature??"",lastDigits:n?.lastDigits,cardNetworkBrand:n?.cardNetworkBrand,header:{ephemeralPublicKey:n?.header?.ephemeralPublicKey??"",publicKeyHash:n?.header?.publicKeyHash??"",transactionId:n?.header?.transactionId??"",applicationData:n?.header?.applicationData},...n?.billingAddress&&{billingAddress:n.billingAddress},expiresAt:n?.expiresAt??null}}}}case"GOOGLE_PAY":{const n=e.walletContent;return n==null?null:{name:"GOOGLE_PAY",walletContent:n?{googlePayWalletContent:{protocolVersion:n.protocolVersion,signature:n.signature,signedMessage:n.signedMessage,sessionId:n.sessionId??void 0,...n.paymentMethodIdentifier&&{paymentMethodIdentifier:n.paymentMethodIdentifier},...n.billingAddress&&{billingAddress:{streetAddress:n.billingAddress}}}}:void 0}}case"SHOPIFY_INSTALLMENTS":{const n=e.walletContent;return n==null?null:{name:"SHOPIFY_INSTALLMENTS",walletContent:{shopifyInstallmentsWalletContent:{...n,billingAddress:{streetAddress:n.billingAddress},paymentMethodIdentifier:n.paymentMethodIdentifier}}}}default:throw new $n(`Unable to handle wallet ${e.name}`)}}function Ri(e){return e.shopPayApprovalId?{approvalId:e.shopPayApprovalId}:{token:e.token}}function Fi(e,t){return{paymentMethodIdentifier:e.paymentMethodIdentifier,name:e.name,billingAddress:{streetAddress:t}}}function Li(e,t,o,n,s,i,r,d){const a=e.method.type,l=a==="wallet"&&e.method.name==="SHOP_PAY"&&e.method.walletContent?.shopPayAsPaymentMethodOptIn,m=a==="direct"?e.method:void 0,u=!l&&m?.credit
1CardInstallments?{installmentsCount:m.creditCardInstallments,intervalType:"MONTH"}:void 0;return{directPaymentMethod:a==="direct"&&e.method.sessionId||l?{paymentMethodIdentifier:l?e.method.walletContent?.paymentMethodIdentifier:e.method.paymentMethodIdentifier,sessionId:l?e.method.walletContent?.sessionId||"":e.method.sessionId||"",billingAddress:{streetAddress:t},...s&&{acceptedSubscriptionTerms:!0},cardSource:l?null:e.method.cardSource||null,...n&&{vaultingAgreement:n},paymentAttributes:l?null:e.method.paymentAttributes,installmentPlan:u}:null,giftCardPaymentMethod:a==="giftCard"?{code:e.method.code,billingAddress:o?{streetAddress:t}:null}:null,redeemablePaymentMethod:a==="redeemable"&&e.method.redemptionContent?Ts(e.method,t):null,walletPaymentMethod:a==="wallet"&&!l?Ei(e.method,n,s):null,walletsPlatformPaymentMethod:a==="walletsPlatformPaymentMethod"?{name:e.method.name,walletParams:e.method.walletParams}:null,...a==="shopWallet"&&{shopWallet:Ri(e.method)},localPaymentMethod:a==="local"?Fi(e.method,t):null,paymentOnDeliveryMethod:null,paymentOnDeliveryMethod2:a==="paymentOnDelivery"?{billingAddress:{streetAddress:t},paymentMethodIdentifier:e.method.paymentMethodIdentifier}:null,manualPaymentMethod:a==="manualPayment"?{id:e.method.id,billingAddress:{streetAddress:t},paymentMethodIdentifier:e.method.paymentMethodIdentifier}:null,customPaymentMethod:a==="customManualPayment"?{id:e.method.id,billingAddress:{streetAddress:t},paymentMethodIdentifier:e.method.paymentMethodIdentifier}:null,offsitePaymentMethod:a==="offsite"?{name:e.method.name,paymentMethodIdentifier:e.method.paymentMethodIdentifier,billingAddress:{streetAddress:t}}:null,customOnsitePaymentMethod:a==="customOnsite"?{name:e.method.name,paymentMethodIdentifier:e.method.paymentMethodIdentifier,billingAddress:{streetAddress:t},paymentAttributes:e.method.paymentAttributes??""}:null,deferredPaymentMethod:a==="deferred"&&(i&&r||!i)?{deferredPayment:!0}:null,customerCreditCardPaymentMethod:a===Ve.CreditCard?{token:e.method.token,paymentMethodIdentifier:e.method.paymentMethodIdentifier,...s&&{acceptedSubscriptionTerms:!0},cvvSessionId:e.method.cvvSessionId,...e.method.creditCardInstallments&&{installmentPlan:{installmentsCount:e.method.creditCardInstallments,intervalType:"MONTH"}}}:null,paypalBillingAgreementPaymentMethod:a===Ve.PayPal?{token:e.method.token,paymentMethodIdentifier:e.method.paymentMethodIdentifier,...s&&{acceptedSubscriptionTerms:!0}}:null,remotePaymentInstrument:a==="bank"&&e.method.selectedType&&e.method.selectedToken?(o&&d?.counter({name:"bank_payment_submit_result",value:1,attributes:{hasSelectedToken:"true"},exportImmediately:!0}),{paymentMethodIdentifier:e.method.paymentMethodIdentifier,billingAddress:{streetAddress:t},...n&&{vaultingAgreement:n},paymentCredentials:[{token:e.method.selectedToken,tokenType:e.method.selectedType}]}):(a==="bank"&&o&&(d?.counter({name:"bank_payment_submit_result",value:1,attributes:{hasSelectedToken:"false"},exportImmediately:!0}),d?.error(new pn(`Bank remotePaymentInstrument set to null in getPaymentMethod: selectedToken=${e.method.selectedToken?"present":"missing"}, selectedType=${e.method.selectedType?"present":"missing"}`))),null)}}function xi(e,t,o,{isCompleting:n=!1,hasSellingPlan:s,hasFixedSellingPlan:i,acceptPaymentVaulting:r,hasPayableDeposit:d,useIntervalForTaxAndPayment:a,fixSubscriptionRedeemablePaymentAmount:l=!1,backendRedeemableCompletionAllocation:m=!1,negotiationRedeemableRecompute:u=!1,observability:f}){const{runningTotal:I,paymentDue:v,deferredTotal:S,checkoutTotal:T,orderDeposit:y,paymentTermsTemplateType:h}=e,C=(c,g)=>!c||!g?wt:{value:{amount:c.amount.toString(),currencyCode:c.currencyCode}},A=t.lines.filter(c=>{const{method:{type:g},cost:M}=c;if(g==="other"||g==="noop")return!1;const P=M&&M.amount>0;return g==="giftCard"?(!n||P||s)&&!i:g==="redeemable"?!0:!(v!=null&&!s&&n&&v.amount<=0)}),w=A.some(c=>c.method.type!=="deferred"),F=Yt({hasSellingPlan:s,hasFixedSellingPlan:i,paymentTermsTemplateType:h}),k=()=>h!=null||d||y!=null||!!(S&&S.amount.amount>0)||A.some(c=>c.due!=null||c.method.type==="deferred"),_=T?.currencyCode,E=l&&m&&F&&n&&_!=null&&!k()&&A.some(c=>
1!c.due&&Et(c)&&c.cost!=null&&c.cost.amount>0&&c.cost.currencyCode===_)&&A.filter(c=>!c.due&&!Et(c)).length===1&&A.some(c=>!c.due&&jn(c));l&&m&&F&&n&&f?.counter({name:"subscription_redeemable_completion_deferral",value:1,attributes:{deferred:String(E)},exportImmediately:!0});const p=T&&l&&!E?Ti({hasRegularSubscriptionPaymentTerms:F,isCompleting:n,allowAtNegotiation:u&&!k(),runningTotal:I,paymentDue:v,checkoutTotal:T,lines:A}):void 0;if(u&&F&&!n){const c=p?.redeemableAmounts.size??0,g=c>0;f?.counter({name:"subscription_redeemable_negotiation_recompute",value:1,attributes:{engaged:String(g),fixEnabled:String(l)}}),f?.log("subscription_redeemable_negotiation_recompute","[Payment] Negotiation-time subscription redeemable recompute",{engaged:g,fixEnabled:l,concreteRedeemableLines:c,hasCheckoutTotal:T!=null,deferredComponent:k()})}return A.map(c=>{const{method:{type:g},cost:M}=c,P=Li(c,o,n,r,s,d,w,f),L=!!(M&&M.amount>0);if(g==="giftCard"){const R=p?.unconstrainedRedeemableLines.has(c)??!1,N=p?.redeemableAmounts.get(c);return{amount:C(R?void 0:N??M,!R&&(N!=null||L&&n)),paymentMethod:P}}if(g==="redeemable"){const R=p?.unconstrainedRedeemableLines.has(c)??!1,N=p?.redeemableAmounts.get(c),W=R?void 0:N??M,H=P.redeemablePaymentMethod?.redemptionSource,z=!R&&(H==="STORE_CREDIT"||H==="CUSTOM"?N!=null||L&&n:L);return{amount:C(W,z),paymentMethod:P}}const x=T&&Pi({fixSubscriptionRedeemablePaymentAmount:l,hasRegularSubscriptionPaymentTerms:F,line:c,isCompleting:n,paymentDue:v,completionAmount:p?.paymentMethodAmount,cost:M,coreAllocatesImmediateAmount:E});if(x)return we({line:c,paymentMethod:P,amount:x.amount,fillAmount:x.fillAmount,totalTaxRange:e.totalTaxRange,useIntervalForTaxAndPayment:S?!1:a});if(v==null)return{amount:wt,paymentMethod:P};const O=s||d||n&&v.amount>0;if(S&&T){const R=!!c.due;if(l&&(F||y&&T.amount<=0)){const N=n&&T.amount===0,W=N||!!(i||y)&&O&&T.amount>0;return N&&!R&&f?.counter({name:"zero_due_immediate_line_concretized",value:1,exportImmediately:!0}),we({line:c,paymentMethod:P,amount:R?S.amount:T,fillAmount:R?O:W,totalTaxRange:e.totalTaxRange,useIntervalForTaxAndPayment:!1})}return we({line:c,paymentMethod:P,amount:R?S.amount:T,fillAmount:O,totalTaxRange:e.totalTaxRange,useIntervalForTaxAndPayment:!1})}return we({line:c,paymentMethod:P,amount:v,fillAmount:O,totalTaxRange:e.totalTaxRange,useIntervalForTaxAndPayment:a})}).filter((c,g)=>{const M=c&&Object.values(c.paymentMethod).some(Boolean);return n&&!M&&c&&A[g]?.method.type==="bank"&&f?.error(new pn("Bank payment line dropped: all paymentMethod fields are null/falsy in paymentLinesForGraphQL")),!!M})}function Di(e,t){if(!t)return e.amount.toString();const o=t.interval.upperBound.amount-t.interval.lowerBound.amount;return U(e.amount+o).toString()}function we({line:e,paymentMethod:t,amount:o,fillAmount:n,totalTaxRange:s,useIntervalForTaxAndPayment:i}){const r={paymentMethod:t,due:Ni(e)};return n?i?{...r,amount:{interval:{upperBound:{amount:Di(o,s),currencyCode:o.currencyCode}}}}:{...r,amount:{value:{amount:o.amount.toString(),currencyCode:o.currencyCode}}}:{...r,amount:{any:!0}}}function Ni(e){return e.due&&"time"in e.due?{time:wi(e.due.time)}:e.due}function wi(e){const t=typeof e=="string"?new Date(e):e;if(!(t instanceof Date))return null;try{return t.toISOString()}catch{throw new ki("Error converting date to ISO string")}}const hn={any:!0};function Oi({totalCost:e,totalTaxRange:t,useIntervalForTaxAndPayment:o}){if(!o)return{value:{amount:e.amount.toString(),currencyCode:e.currencyCode}};const n=t?.interval.upperBound??e;return{interval:{upperBound:{amount:n.amount.toString(),currencyCode:n.currencyCode}}}}function yn(e,t,o){if(e?.status==="available_total_included"&&t?.status==="available_total")return{proposedMixedStateTotalAmount:{proposedTotalAmount:{value:{amount:t.totalDuty.amount.toString(),currencyCode:t.totalDuty.currencyCode}},proposedTotalIncludedAmount:{value:{amount:e.totalIncludedInTarget.amount.toString(),currencyCode:e.totalIncludedInTarget.currencyCode}}},proposedTotalAmount:null,proposedTotalIncludedAmount:null};switch(e?.status){case"available_total_included":return{proposedTotalAmount:null,proposedTotalIncludedAmount:{value:{amount:e.totalIncludedInTarget.amount.toString(),currencyCode:e.totalIncludedInTarget.currencyCode}},proposedMixedStateTotalAmount:null};case"available_total":return{proposedTotalAmount:Oi({useIntervalForTaxAndPayment:o?.useIntervalForTaxAndPayment??!1,totalCost:e.totalCost,totalTaxRange:e.totalTaxRange}),proposedTotalIncludedAmount:null,proposedMixedStateTotalAmount:null};default:return{proposedTotalAmount:hn,proposedTotalIncludedAmount:null,proposedMixedStateTotalAmount:null}}}function Bi(e){const o=new Map;return e?.forEach((n,s)=>{switch(n.status){case"available_total_included":return o.set(s,{proposedTotalAmount:null,proposedTotalIncludedAmount:{value:{amount:n.totalIncludedInTarget.amount.toString(),currencyCode:n.totalIncludedInTarget.currencyCode}},proposedMixedStateTotalAmount:null});case"available_total":return o.set(s,{proposedTotalAmount:{value:{amount:n.totalCost.amount.toString(),currencyCode:n.totalCost.currencyCode}},proposedTotalIncludedAmount:null,proposedMixedStateTotalAmount:null});
1case"pending":case"unavailable":return o.set(s,{proposedTotalAmount:hn,proposedTotalIncludedAmount:null,proposedMixedStateTotalAmount:null});default:return rn(n)}}),o}class Ui extends Error{constructor(){super(...arguments),this.name="MissingRemoteSessionTokenError"}}const oe={any:!0},Vi={get:()=>"dedicated"};function Gi({shopId:e,merchandiseLines:t,deliveryTermsInput:o,paymentDetails:n,sessionToken:s,queueToken:i,taxesInput:r,isCompleting:d=!1,shippingAddress:a,isShippingRequired:l,availableDeliveryAddresses:m,primaryPaymentMethod:u,observability:f,extendedAddressMode:I}){if(!s)throw new Ui(`No session token for remote shop: ${e}`);if(o.deliveryLines.length===0&&t.length>0){const c=m?.find(g=>it(g.address,a,["phone"])&&Ht(g.address,a));o.deliveryLines.push({destination:(()=>{if(l)return c?{deliveryAddressReference:Ue(c.address)}:d?{streetAddress:Ge(a,{extendedAddressMode:I})}:{partialStreetAddress:Ge(a,{extendedAddressMode:I})}})(),selectedDeliveryStrategy:{deliveryStrategyMatchingConditions:{estimatedTimeInTransit:oe,shipments:oe},options:{}},targetMerchandiseLines:oe,deliveryMethodTypes:[l?"SHIPPING":"NONE"],expectedTotalPrice:oe,destinationChanged:!1})}const v=r??{proposedTotalAmount:oe},{paymentDue:S,sessionId:T,paymentMethodIdentifier:y,billingAddress:h,cardSource:C,paymentAttributes:A,paymentFlexibilityTermsId:w,preserveBillingAddressExtendedFields:F}=n??{},k=F?Vi:I,_=S&&S.amount>0&&h&&T&&u,E=[];if(_){const c=zi({primaryPaymentMethod:u,sessionId:T,billingAddress:h,cardSource:C,paymentAttributes:A,paymentMethodIdentifier:y,observability:f,extendedAddressMode:k});c&&E.push({amount:d?{value:{amount:String(S.amount),currencyCode:S.currencyCode}}:oe,paymentMethod:c})}const p={totalAmount:oe,paymentLines:E,...h&&{billingAddress:{streetAddress:le(h,{extendedAddressMode:k})}},...w&&{paymentFlexibilityTermsId:w}};return{shopId:e,delivery:o,merchandise:{merchandiseLines:t},payment:p,sessionToken:s,queueToken:i,taxes:v}}function qi({deliveryTermsInputByShop:e,merchandiseByShop:t,perShopSessionToken:o,perShopQueueToken:n,perShopTaxes:s,paymentDetailsByShop:i,isCompleting:r,shippingAddress:d,negotiatedMerchandiseLines:a,availableDeliveryAddresses:l,primaryPaymentMethod:m,observability:u,extendedAddressMode:f}){if(t.size!==0)return{remoteNegotiations:Array.from(t.entries()).map(([I,v])=>{const S=i?.get(I),T=a.filter(({stableId:y})=>v.some(h=>h.stableId===y)).some(y=>y.requiresShipping);return Gi({shopId:I,deliveryTermsInput:e[I]??{deliveryLines:[],noDeliveryRequired:[],useProgressiveRates:!1},merchandiseLines:v,paymentDetails:S,sessionToken:o?.get(I),queueToken:n?.get(I),taxesInput:s.get(I),isCompleting:r,shippingAddress:d,isShippingRequired:T,availableDeliveryAddresses:l,primaryPaymentMethod:m,observability:u,extendedAddressMode:f})})}}function Hi({deliveryInput:e,merchandiseDetails:t,paymentDetailsByShop:o,perShopSessionToken:n,perShopTaxes:s,isCompleting:i,primaryPaymentMethod:r,observability:d,perShopQueueToken:a,extendedAddressMode:l}){const{stableIdToShopId:m,merchandiseLines:u}=t;if(m==null||m.size===0||n==null||n.size===0)return{delivery:e.deliveryTermsInput,merchandiseLines:u};const{localMerchandise:f,remoteMerchandiseByShop:I}=Wi(u,m),{deliveryTermsInputByShop:v,delivery:S}=Yi(e.deliveryTermsInput,m),T=qi({deliveryTermsInputByShop:v,merchandiseByShop:I,perShopSessionToken:n,perShopQueueToken:a,perShopTaxes:s,paymentDetailsByShop:o,isCompleting:i,shippingAddress:e.shippingAddress,negotiatedMerchandiseLines:e.negotiatedMerchandiseLines,availableDeliveryAddresses:e.availableDeliveryAddresses,primaryPaymentMethod:r,observability:d,extendedAddressMode:l});return{delivery:S,merchandiseLines:f,remote:T}}function Yi(e,t){const{deliveryLines:o,...n}=e,s={},i=[];return new Set(t.values()).forEach(d=>{s[d]={...n,deliveryLines:[]}}),o.forEach(d=>{const a=d.targetMerchandiseLines.lines?.[0],l=a?t.get(a.stableId??""):void 0,m=l?s[l]:void 0;m?m.deliveryLines.push(d):i.push(d)}),{deliveryTermsInputByShop:s,delivery:{deliveryLines:i,...n}}}function Wi(e,t){const o=[],n=new Map;return e.forEach(s=>{const i=s.stableId==null?void 0:t.get(s.stableId);if(i){const r=n.get(i)||[];n.set(i,[...r,s])}else o.push(s)}),{localMerchandise:o,remoteMerchandiseByShop:n}}function Qi(e,t){return le({address1:e.address1??void 0,address2:e.address2??void 0,city:e.city,company:e.company??void 0,countryCode:e.countryCode??void 0,firstName:e.firstName??void 0,lastName:e.lastName??void 0,postalCode:e.postalCode??void 0,zoneCode:e.zoneCode??void 0,phone:e.phone??void 0,district:e.extendedFields?.district??void 0,line2:e.extendedFields?.line2??void 0,streetName:e.extendedFields?.streetName??void 0,streetNumber:e.extendedFields?.streetNumber??void 0,subdistrict:e.extendedFields?.subdistrict??void 0},{extendedAddressMode:t})}function zi({primaryPaymentMethod:e,sessionId:t,billingAddress:o,cardSource:n,paymentAttributes:s,paymentMethodIdentifier:i,observability:r,extendedAddressMode:d}){if(ji(e))return{directPaymentMethod:{sessionId:t,paymentMethodIdentifier:i,cardSource:n,paymentAttributes:s,billingAddress:{streetAddress:le(o,{extendedAddressMode:d})}}};if($i(e)){const a=e.walletContent;return a==null?null:{walletPaymentMethod:{name:"SHOP_PAY",walletContent:{shopPayWalletContent:{sessionToken:t,billingAddress:{streetAddress:Qi(a.billingAddress,d)},paymentAttributes:a.paymentAttributes,paymentMethod:a.paymentMethod,paymentMethodIdentifier:i,addressId:a.addressId,...a.hsaRequested!=null&&{hsaRequested:a.hsaRequested},...a.creditCardInstallments&&{creditCardInstallmentPlan:{installmentsCount:a.creditCardInstallments,intervalType:"MONTH"}},...a.msiEligibleCard&&{msiEligibleCard:a.msiEligibleCard}}}}}}else return r?.log("unexpected_remote_payment_method_type","Expected direct or Shop Pay wallet payment method for remote negotiation",{primaryPaymentMethodType:e.type}),null}function ji(e){return e.type==="direct"}function $i(e){return e.type==="wallet"&&e.name==="SHOP_PAY"}function Ki(e,t){return t==null?e:e.filter(({totalPrice:o})=>o==null||o.currencyCode===t)}function Ji(e){if(e===void 0||e.optIn===void 0||e.optIn===!1)return e;const{isAutoOptIn:t,...o}=e.optIn;return{...e,optIn:o}}const Xi=["SHOP_PAY","SHOPIFY_INSTALLMENTS","GOOGLE_PAY"];function fn(e){const t=e?.optIn;return!!(t&&t.isAutoOptIn===!1&&t.vaultPhone==="")}function Zi(e,t,o,n,s){const i=fn(o),r=Ji(o);if(!e)return r;if(n)return{optIn:{vaultPhone:i?"":s??"",vaultEmail:"",optInSource:"REMEMBER_ME"}};const d=r?.optIn;let a=d?d.vaultPhone:void 0;if(r?.shopUser?.uuid||(a=i?a??s:a||s),a=a??"",r?.shopUser?.uuid&&r?.optIn===void 0)return r;const m=r===void 0||r.optIn===!1?!1:{...r.optIn,vaultPhone:a,vaultEmail:t?"":r.optIn?.vaultEmail};return{...r,optIn:m}}function er({paymentLines:e,shopPayArtifact:t,shopPayRememberMeVisible:o,isManagedByMarketsPro:n,isApplePayInShopPayEnabled:s,isCompleting:i,wallets:r}){const d=!!t?.shopUser?.uuid;if(!o&&!d||r?.escalatedWallet.value||n&&Kn(e))return!1;const l=s&&i;if(Jn(e,"APPLE_PAY")&&!l)return!1;const m=e[0]?.method,u=d&&m?.type==="wallet"&&m.name==="SHOPIFY_INSTALLMENTS";return!((!d||u)&&(m?.type==="wallet"&&Xi.includes(m?.name)||m?.type==="walletsPlatformPaymentMethod"||r?.activeSession.value?.asPaymentMethod===!1)||!(!!(t?.optIn&&!d)||d))}
1class tr extends Error{constructor(){super(...arguments),this.name="MissingSessionTokenError"}}class nr extends Error{constructor(){super(...arguments),this.name="MissingShopPayAlternativePaymentMethodError"}}const or={any:!0},Ot={get:()=>"dedicated"};function sr(e,t){const{parts:o}=e,n=e.current.value,s=o.paymentLines.value,i=n.runningTotal&&n.runningTotal?.amount<=0,r=$t(n.merchandiseLines?.lines).some(m=>!!m.sellingPlan?.subscriptionDetails);if(!(!i||r||n.deferredTotal?.amount.amount))return!1;const a=zt(n.buyerIdentity?.customerProfile),l=s&&s[0];return!l||l.method.type!=="wallet"||a&&l.method.name==="APPLE_PAY"?!1:["GOOGLE_PAY","APPLE_PAY"].includes(l.method.name)?!0:l.method.name!=="PAYPAL_EXPRESS"?!1:t}function gn(e){return e.find(t=>t.method.type===Ve.CreditCard||t.method.type===Ve.PayPal)}function ir(e){return gn(e.parts.paymentLines.peek())?.method.billingAddress}function rr(e){return e.some(({method:t})=>t.type==="wallet"&&t.name==="SHOPIFY_INSTALLMENTS")}function ar(e){return!!e?.some(({paymentMethod:t})=>t.walletPaymentMethod?.name==="SHOPIFY_INSTALLMENTS"||t.walletPaymentMethodConfig?.name==="SHOPIFY_INSTALLMENTS")}function dr(e,t,o){const{parts:n,source:s,facts:i}=e,r=e.current.peek(),d=n.paymentLines.peek(),l=i.delivery?.[0]?.deliveryAddress??n.shippingAddress.peek(),m=n.billingAddress.peek(),u=!m.address1&&i.billingAddress?i.billingAddress:m,f=n.billingAddressOption.peek(),I=r.isShippingRequired,v=uo(s)?i.requiresShipping:I,S=gn(d);if(S)return o?.log("get_negotiation_input_vaulted_payment_billing_address_used","[getPaymentAddress] Using vaulted payment billing address"),S.method.billingAddress;const T=co(d),y=f==="shipping"&&T,h=(()=>{const C=r.buyerIdentity?.purchasingCompany;if(C){if(f==="billing"&&C.location.billingAddress)return C.location.billingAddress;if(y)return C.location.shippingAddress??l}})();return h?(o?.log("get_negotiation_input_company_location_address_used","[getPaymentAddress] Using company location address"),h):f==="billing-fact"?(o?.log("get_negotiation_input_billing_fact_address_used","[getPaymentAddress] Using billing-fact address"),u):sr(e,t)?(o?.log("get_negotiation_input_wallet_billing_address_used","[getPaymentAddress] Using wallet billing address"),u):v&&y?(o?.log("get_negotiation_input_shipping_address_used","[getPaymentAddress] Using shipping address"),l):(o?.log("get_negotiation_input_default_billing_address_used","[getPaymentAddress] Using default billing address"),u)}function vn(e){return e.current.token??null}function lr({proposedTotalAmount:e,proposedTotalIncludedAmount:t,proposedMixedStateTotalAmount:o}){return{amount:Oe(e),includedAmount:Oe(t),mixedState:o?{amount:Oe(o?.proposedTotalAmount),includedAmount:Oe(o?.proposedTotalIncludedAmount)}:void 0}}function Oe(e){if(!e)return{type:"none"};if(e.any)return{type:"any"};if(e.interval){const t=e.interval.upperBound;return{type:"interval",amount:t?.amount,currencyCode:t?.currencyCode}}return e.value?{type:"value",amount:e.value.amount,currencyCode:e.value.currencyCode}:{type:"unknown"}}function ur(e,t){if(t.mixedState){const o=t.mixedState.amount,n=t.mixedState.includedAmount;if(e==="available_total")return o.type==="value"||o.type==="interval"?Be(o.amount):!0;if(e==="available_total_included")return n.type==="value"||n.type==="interval"?Be(n.amount):!0}if(e==="available_total")return t.amount.type==="value"||t.amount.type==="interval"?Be(t.amount.amount):!0;if(e==="available_total_included"){const o=t.includedAmount.type==="none"?t.mixedState?.includedAmount:t.includedAmount;return o&&o.type==="value"?Be(o.amount):!0}return!0}function Be(e){if(e==null)return!0;const t=Number(e);return Number.isFinite(t)?t===0:!0}function cr({acceptEmailMarketing:e,acceptSmsMarketing:t,smsMarketingPhone:o,smsMarketingCountryCode:n,email:s,isBusinessCustomer:i,emailMarketingConsentGrantReached:r,useMessagingMarketingConsent:d,emailMarketingOptInShown:a}){const l=[];if(i)return l;if(!d&&o&&l.push({sms:{consentState:t?"GRANTED":"DECLINED",value:o,countryCode:n}}),s){const m=mr({acceptEmailMarketing:e,emailMarketingConsentGrantReached:r,emailMarketingOptInShown:a});m&&l.push({email:{consentState:m,value:s}})}return l}function mr({acceptEmailMarketing:e,emailMarketingConsentGrantReached:t,emailMarketingOptInShown:o}
1){if(e)return o&&!t?"PARTIALLY_GRANTED":"GRANTED";if(o)return"DECLINED"}function pr({acceptSmsMarketing:e,smsMarketingPhone:t,countryCode:o,disclosureCountryCode:n,isBusinessCustomer:s,smsMarketingOptInShown:i}){if(!(s||!i))return e?t?{consentState:"GRANTED",phoneNumber:t,...o?{countryCode:o}:{},...n?{disclosureCountryCode:n}:{}}:void 0:{consentState:"DECLINED",...t?{phoneNumber:t}:{},...o?{countryCode:o}:{},...n?{disclosureCountryCode:n}:{}}}function hr({proposedDeliveryLines:e,negotiatedDeliveryNext:t,shipPickupInOneOrderEnabled:o}){if(o){const i=e.filter(r=>!r.value.deliveryMethodTypes.includes("NONE"));return i.length>0&&i.every(r=>r.value.deliveryMethodTypes.includes("PICK_UP"))}const n=ho(t,"ONE_TIME_PURCHASE");return yo(n)?.methodType==="PICK_UP"}function yr(e){const t=e.email.peek().trim(),o=e.phone.peek().trim(),n=e.acceptEmailMarketing.peek(),s=e.acceptSmsMarketing.peek(),i=e.smsMarketingPhone.peek(),r=e.purchaseOrderNumber.peek(),d=e.acceptPaymentVaulting.peek(),a=e.shopPayArtifact.peek(),l=e.optionalDuties.peek(),m=e.captcha.peek(),u=e.shippingAddress.peek(),f=e.billingAddress.peek(),I=e.availableRedeemables.peek(),v=e.attribution.peek(),S=e.saleAttributions.peek(),T=e.reduction.peek(),y=e.deliveryLines.peek(),h=e.externalDeliveryIds.peek(),C=e.discountLines.peek(),A=e.merchandiseLines.peek(),w=e.locationAddress.peek(),F=e.useProgressiveRates.peek(),k=e.interfaceFlow.peek(),_=e.tipLines.peek(),E=e.note.peek(),p=e.attributes.peek(),c=e.cartMetafields.peek(),g=e.memberships.peek(),M=e.rememberMe.peek(),P=e.setShippingAddressAsDefault.peek(),L=e.shopPayRememberMeVisible.peek(),x=e.taxExemptions.peek(),O=e.useStoreCreditForSubscriptionRenewals.peek();return{attributes:p,email:t,phoneNumber:o,acceptEmailMarketing:n,acceptSmsMarketing:s,smsMarketingPhone:i,purchaseOrderNumber:r,acceptPaymentVaulting:d,shopPayArtifact:a,optionalDuties:l,captcha:m,shippingAddress:u,billingAddress:f,availableRedeemables:I,attribution:v,saleAttributions:S,reduction:T,proposedDeliveryLines:y,externalDeliveryIds:h,discountLines:C,merchandiseLines:A,locationAddress:w,useProgressiveRates:F,interfaceFlow:k,tipLines:_,note:E,rememberMe:M,setShippingAddressAsDefault:P,shopPayRememberMeVisible:L,cartMetafields:c,memberships:g,taxExemptions:x,useStoreCreditForSubscriptionRenewals:O}}function fr(e){return e.localizationExtensions.peek().map(t=>{const{key:o,value:n}=t.peek();return{key:o,value:n||""}})}function gr(e){return e.deliveryExpectations&&e.deliveryExpectations.status==="filled"&&e.deliveryExpectations.deliveryExpectationLines.filter(t=>t.signedHandle).map(t=>({signedHandle:t.signedHandle}))||[]}class vr extends Error{constructor(){super(...arguments),this.name="DirectPaymentLinesMismatchError"}}function br(e,t,o){const n=os(t);return e.cachedMembershipViolations.value.filter(s=>ss(s,o,n))}function _r(e,t,o){if(e.status!=="filled")return{memberships:[],violations:[]};const n=br(t,e,o),s=n.map(r=>r.handle);return{memberships:e.memberships.map(r=>{const d=!s.includes(r.handle);return{handle:r.handle,apply:d?r.apply:!1}}),violations:n}}function Sr(e){return{memberships:e.map(t=>({handle:t.handle,apply:t.apply}))}}function bn(e,{isCompleting:t=!1,customizeNegotiation:o,observability:n,paymentLinesObservability:s,wallets:i}={}){if(!e.sessionToken)throw new tr("No session token");const{parts:r,throttle:d,checkout:a}=e,{extendedAddressMode:l}=a.address,m=a.unstable_graphqlDataRequestInfo?.httpRequestInfo?.geolocation?.coordinates??void 0,u=e.shop.shipPickupInOneOrderEnabled,f=e.current.peek().deliveryNext,I=f?.status==="filled"||f?.status==="partial",v=u&&(!I||f.supportsSplitDeliveryMethod)?!0:void 0,S=Xn(e.context.bankIdNumberSignal.peek()),{attributes:T,email:y,phoneNumber:h,acceptEmailMarketing:C,acceptSmsMarketing:A,smsMarketingPhone:w,purchaseOrderNumber:F,acceptPaymentVaulting:k,shopPayArtifact:_,shopPayRememberMeVisible:E,optionalDuties:p,captcha:c,shippingAddress:g,billingAddress:M,availableRedeemables:P,attribution:L,saleAttributions:x,reduction:O,proposedDeliveryLines:R,externalDeliveryIds:N,discountLines:W,merchandiseLines:H,locationAddress:B,useProgressiveRates:z,interfaceFlow:X,tipLines:Q,note:D,rememberMe:G,setShippingAddressAsDefault:j,cartMetafields:te,memberships:se,taxExemptions:qe,useStoreCreditForSubscriptionRenewals:ue}=yr(r);let V=r.paymentLines.peek();const ne=V[0]?.method,ce=Wt(e.shop),fe=Zn({shop:e.shop,checkout:e.checkout,paymentMethods:e.current.peek().paymentMethods}),$=dr(e,fe,n),Z=$===ir(e)?Ot:l,ie={extendedAddressMode:Z};if(t&&_?.shopUser&&Ms(ne,e.current.fields.paymentMethods.peek(),e.shopPay.session.selectedPaymentMethod.value)){const Y=Cs(ne)?ne:Ir(e.current.fields.paymentMethods.peek(),e.shopPay.session.selectedPaymentMethod.value);Y?V=eo(V,Ar({paymentMethod:Y,billingAddress:$,extendedAddressMode:Z}),ce):n?.error(new nr("Failed to resolve Shop Pay alternative payment method from available payment methods"))}const He=rr(V)||e.shopPay.session.isInstallmentsSelected.value?[]:Q,b=e.current.peek(),Ye=to({availableDeliveryAddresses:b.availableDeliveryAddresses,mustSelectProvidedAddress:b.mustSelectProvidedAddress}),re=b.shippingAddress,me=b.contactInfo?.email,We=b.merchandiseLines?.lines?.[0]?.totalPrice.currencyCode||b.buyerIdentity?.presentmentCurrency,ge=Ki(H,We),ve=un(ge),be=Qt(b),_e=!!be?.amount,pe=!re||!no(g,re,["phone"]);pe&&re?.oneTimeUse&&(g.oneTimeUse=!1);const ae=t&&V.length===1?V[0]:void 0,Se=ae!==void 0&&ae.method.type==="wallet"&&(ae.method.name==="APPLE_PAY"||ae.method.name==="GOOGLE_PAY")&&i?.escalatedWallet.value!=="APPLE_PAY",{proposedTotalAmount:Ae,proposedTotalIncludedAmount:Ie,proposedMixedStateTotalAmount:Te}=yn(b.taxes,b.duties,{useIntervalForTaxAndPayment:Se}),Me=lr({proposedTotalAmount:Ae,proposedTotalIncludedAmount:Ie,proposedMixedStateTotalAmount:Te}),he=b.allViolations?.map(Y=>Y.code)??[],Qe=he.includes("TAX_NEW_TAX_MUST_BE_ACCEPTED"),ze=he.includes("PAYMENTS_UNACCEPTABLE_PAYMENT_AMOUNT"),je=b.taxes?.status??"missing";n&&t&&ur(je,Me)&&n.log("shop_pay_installments_tax_terms_missing_on_negotiation","[Negotiate] Completing without accepted tax terms",{hasTaxViolation:Qe,hasPaymentAmountViolation:ze,taxProposalSummary:Me,taxes:b.taxes,installmentsPaymentSet:!!e.shopPay.installments.payment.value,violationCodes:he});const $e=Bi(b.remoteTaxDetails?.perShopTaxes),Ce=b.buyerIdentity?.customerProfile,Pe=zt(Ce),ye=es(r),ke=e.context.emailMarketingOptInShownSignal.value,Ee=e.context.emailMarketingConsentGrantReachedSignal.value||b.emailMarketingConsentGrantReached,Ke=e.context.smsMarketingOptInShownSignal.value,Re=t&&A&&i?.activeSession.value&&e.context.marketingPhoneInputError.peek()?void 0:w,ht=ts({isShippingRequired:a.isShippingRequired.peek(),isPickupSelected:hr({proposedDeliveryLines:R,negotiatedDeliveryNext:f,shipPickupInOneOrderEnabled:u}),shippingCountryCode:g.countryCode,billingCountryCode:M.countryCode}),yt=e.shop.hasFlagEnabled(oo)&&!!ns(e.shop,ht),Tn=cr({acceptEmailMarketing:C,acceptSmsMarketing:A,smsMarketingPhone:Re,smsMarketingCountryCode:ye,email:y,isBusinessCustomer:Pe,emailMarketingConsentGrantReached:Ee,useMe
1ssagingMarketingConsent:yt,emailMarketingOptInShown:ke}),Mn=yt?pr({acceptSmsMarketing:A,smsMarketingPhone:Re,countryCode:ye,disclosureCountryCode:ht,isBusinessCustomer:Pe,smsMarketingOptInShown:Ke}):void 0,Cn=!Ke||!A,Pn=e.context.shopPayMobilePhoneInputShownSignal.value,kn=!h&&!g?.phone&&!M?.phone&&!Pn,{isOnePage:En}=e.checkout.configuration.layout,Rn=En.peek()?"one-page":"three-page",ft=b.smsMarketingPhone??"";let Fe;ft===""?Fe="not-in-negotiated":ft===Re?Fe="matches-negotiated":Fe="differs-from-negotiated",n&&Re&&kn&&Cn&&n.log("sms_marketing_phone_sent_without_visible_phone_input","[Proposal] SMS marketing phone included while no phone input was visible",{acceptSmsMarketing:A,checkoutLayout:Rn,contactPhonePresent:!!h,contactEmailPresent:!!y,hasSmsMarketingPhone:!0,isCompleting:t,shopSmsMarketingSetting:e.shop.smsMarketing,smsMarketingOptInShown:Ke,smsMarketingPhoneSource:Fe,sourceType:e.source?.type});const Fn=jt(b.merchandiseLines?.lines),Ln=$t(b.merchandiseLines?.lines).some(Y=>Y.sellingPlan?.isFixed),xn=b.canUpdateDiscountCodes??!1,gt=Kt({customAttributes:b.customAttributes}),Dn=Jt({customAttributes:b.customAttributes}),Nn=gt&&!!g&&Dn,vt=e.shopPay.session.secureData.value,Je=e.source?.type==="draftOrder",bt=se?_r(se,e.context,g):void 0;e.context.cachedMembershipViolations.value=bt?.violations||[];const wn=Sr(bt?.memberships||[]),Xe=le($,ie),Ze=Ft(V,$,r.billingAddressOption.peek(),ie,Je)?.streetAddress;if(Ze&&Xe){const K=["address1","city","countryCode","postalCode"].filter(q=>Xe[q]!==Ze[q]);K.length>0&&n?.log("get_negotiation_input_billing_address_mismatch_detected","Billing address mismatch detected between payment lines and billing address inputs",{mismatchedFields:K,paymentLinesBillingAddress:Xe,billingAddress:Ze,billingAddressOption:r.billingAddressOption.peek()})}if(t&&n){const Y=b.paymentMethods?.map(q=>q.type==="direct"?{paymentMethodIdentifier:q.paymentMethodIdentifier,name:q.name}:void 0).filter(Boolean),K=V.find(q=>!!(q.method.type==="direct"&&q.method.creditCardLastFourDigits&&q.method.brand))?.method.paymentMethodIdentifier;g.countryCode==="US"&&K&&!Y?.some(q=>q?.paymentMethodIdentifier===K)&&n?.error(new vr("Completing with a direct payment line mismatch with seller proposal available payment methods"),{metadata:{value:{buyerDirectPaymentMethodIdentifiers:JSON.stringify(K),availableDirectPaymentMethods:JSON.stringify(Y)}}})}const et=ei({lines:ge}),Le=b.remoteMerchandiseDetails?.stableIdToShopId;t&&so(g.postalCode,g.countryCode)&&n?.log("wallets_shipping_address_postal_code_in_submit_input","Padded postal code detected in shipping address at SubmitForCompletion time",{countryCode:g.countryCode});const _t={deliveryLines:ai({shippingAddress:g,proposedDeliveryLines:R,externalDeliveryIds:N,destinationChanged:pe,isSubmitForCompletion:t,isPointOfSale:gt,isPointOfSaleShipToHome:Nn,negotiatedDelivery:b.deliveryNext,filteredMerchandiseStableIds:ve,locationAddress:B,geolocationCoordinates:m,retailLocationId:io({customAttributes:b.customAttributes}),isShippingRequired:b.isShippingRequired,availableDeliveryAddresses:b.availableDeliveryAddresses,isConstrainedAddress:Ye,extendedAddressMode:l,marketDrivenShippingEnabled:e.shop.marketDrivenShippingEnabled,stableIdToShopId:Le,remoteShopsConfigMap:e.shop.remoteShopsConfigMap}),noDeliveryRequired:[],useProgressiveRates:z,prefetchShippingRatesStrategy:null,interfaceFlow:X,supportsSplitShipping:a.supportsSplitShipping.value,acceptSplitDelivery:v},St=!!(Le&&Le.size>0),{delivery:On,merchandise:At,remoteNegotiations:It}=St?(()=>{const Y=new Map,K=e.parts.remotePaymentDetails.peek();if(K&&V.length>0){const{method:Pt}=V.find(nt=>nt.method.type==="direct")??{};for(const[nt,qn]of K){const Hn={...qn,cardSource:Pt?.cardSource??null,paymentAttributes:Pt?.paymentAttributes,billingAddress:$,preserveBillingAddressExtendedFields:Z===Ot};Y.set(nt,Hn)}}const{delivery:q,merchandiseLines:Vn,remote:Gn}=Hi({deliveryInput:{deliveryTermsInput:_t,shippingAddress:g,negotiatedMerchandiseLines:b.merchandiseLines?.lines??[],availableDeliveryAddresses:b.availableDeliveryAddresses}
1,perShopSessionToken:b.remoteSessionDetails?.perShopSessionToken,perShopQueueToken:b.remoteSessionDetails?.perShopQueueToken,perShopTaxes:$e,merchandiseDetails:{merchandiseLines:et.merchandiseLines,stableIdToShopId:Le},paymentDetailsByShop:Y,primaryPaymentMethod:ne,observability:n,isCompleting:t,extendedAddressMode:l});return{delivery:q,merchandise:{...et,merchandiseLines:Vn},remoteNegotiations:Gn}})():{merchandise:et,delivery:_t,remoteNegotiations:void 0},xe=!(St&&At.merchandiseLines.length===0),Tt=e.checkout.rememberMe.createAccountOptIn.value,Mt=fn(_)?void 0:g.phone||M.phone,Bn=(r.shippingAddress?.dirtyFields?.value?.size??0)>0||(r.billingAddress?.dirtyFields?.value?.size??0)>0,Un=Zs({buyerEditedAddress:Bn,shopUserSecureData:vt,shopPayVerificationTrigger:e.shopPay?.session?.verificationTrigger?.value,customerProfile:Ce}),Ct={checkpointData:a.checkpointToken.value,sessionInput:{sessionToken:e.sessionToken},queueToken:vn(d),discounts:{lines:_i({lines:W},H,n),acceptUnexpectedDiscounts:Je?b.acceptUnexpectedDiscounts:xn},...xe?{delivery:On}:{},deliveryExpectations:{deliveryExpectationLines:gr(b)},merchandise:At,memberships:wn,availableRedeemables:si(P),...xe?{payment:{totalAmount:or,paymentLines:xi({runningTotal:b.runningTotal,paymentDue:b.paymentDue,deferredTotal:b.deferredTotal,checkoutTotal:b.checkoutTotal,orderDeposit:be,paymentTermsTemplateType:b.paymentFlexibilityPaymentTermsTemplate?.type,totalTaxRange:b.taxes?.status==="available_total"?b.taxes.totalTaxRange:void 0},{lines:V},le($,ie),{isCompleting:t,hasSellingPlan:Fn,hasFixedSellingPlan:Ln,acceptPaymentVaulting:k,hasPayableDeposit:_e,useIntervalForTaxAndPayment:Se,fixSubscriptionRedeemablePaymentAmount:ce,backendRedeemableCompletionAllocation:e.shop.hasFlagEnabled(lo),negotiationRedeemableRecompute:ao(e.shop),observability:n??s}),billingAddress:Ft(V,$,r.billingAddressOption.peek(),ie,Je),paymentFlexibilityTermsId:b.paymentFlexibilityPaymentTermsTemplate?.id,creditCardBin:S,allowStoreCredit:ue}}:{},buyerIdentity:{customer:{presentmentCurrency:b.buyerIdentity?.presentmentCurrency,countryCode:b.buyerIdentity?.countryCode},email:y||void 0,...y?{emailChanged:!me||me!==y}:{},phone:h||void 0,phoneCountryCode:ye||void 0,marketingConsent:Tn,messagingMarketingConsent:Mn,shopPayOptInPhone:{number:Mt,countryCode:g?.countryCode||M?.countryCode||b.buyerIdentity?.countryCode},shopUserSecureData:vt,prefillSource:Un,rememberMe:G,setShippingAddressAsDefault:t?j:void 0},tip:{tipLines:Ps(He)},poNumber:F===""?null:F,...xe?{taxes:{proposedAllocations:null,proposedTotalAmount:Ae,proposedTotalIncludedAmount:Ie,proposedMixedStateTotalAmount:Te,proposedExemptions:qe}}:{},...xe?{note:Ai(b,D,T)}:{},localizationExtension:{fields:fr(r)},shopPayArtifact:Tt||er({paymentLines:V,shopPayArtifact:_,shopPayRememberMeVisible:E,isManagedByMarketsPro:!!b.managedByMarketsPro,isApplePayInShopPayEnabled:!e.shop.hasFlagEnabled(ro),isCompleting:t,wallets:i})?Zi(t,y,_,Tt,Mt):void 0,nonNegotiableTerms:b.nonNegotiableTerms?Si(b.nonNegotiableTerms):null,
1scriptFingerprint:b.scriptFingerprint,transformerFingerprintV2:b.transformerFingerprintV2,optionalDuties:p?Ii(p.buyerRefusesDuties):null,attribution:L,captcha:ii(c),reduction:O,saleAttributions:x,alternativePaymentCurrency:oi(b.alternativePaymentCurrency),cartMetafields:te,...It?{remote:It}:{}},tt=o?o(Ct):Ct;return ar(tt.payment?.paymentLines)?{...tt,tip:{tipLines:[]}}:tt}function Ar({paymentMethod:e,billingAddress:t,extendedAddressMode:o}){return{method:{type:"wallet",name:"SHOP_PAY",walletContent:{paymentMethod:"CUSTOM_ONSITE",billingAddress:le(t,{extendedAddressMode:o}),paymentMethodIdentifier:e.paymentMethodIdentifier||"",paymentAttributes:e.paymentAttributes}}}}function Ir(e,t){if(t?.paymentMethod==="CUSTOM_ONSITE"&&"paymentBrands"in t){const n=t.paymentBrands??[],s=e.find(i=>mo(i,n));if(s)return{type:"customOnsite",paymentMethodIdentifier:s.paymentMethodIdentifier,name:s.name,paymentBrands:n}}const o=e.find(n=>po(n));if(o)return{type:"customOnsite",paymentMethodIdentifier:o.paymentMethodIdentifier,name:"iDEAL",paymentBrands:["ideal"]}}function Tr(e){return fo(e??[])?.installmentPlans?.find(n=>n.type==="MSI")?.supportedInstallments??[]}function Mr({paymentDue:e,remotePaymentDue:t,remoteMerchandiseDetails:o}){return!!o?.stableIdToShopId.size&&t?t:e}function Cr({observability:e,userEvents:t,paymentLines:o,paymentMethods:n,paymentDue:s,remotePaymentDue:i,remoteMerchandiseDetails:r,shopId:d,checkoutToken:a}){try{const l=go(o);if(!l)return;const m=Mr({paymentDue:s,remotePaymentDue:i,remoteMerchandiseDetails:r}),u=m?.amount,f=m?.currencyCode;if(u==null||!f)return;t.monorailEvent({schemaId:"checkout_credit_card_installment_track/1.0",payload:{eventName:"credit_card_installment_submit_attempted",shopId:parseInt(vo(d),10),checkoutToken:a??"",planCount:l,eligiblePlans:Tr(n).join(","),cartTotal:u.toFixed(2),cartCurrency:f}},{exportImmediately:!0})}catch(l){l instanceof Error&&e.error(l)}}function Pr(){return{requestUrl:window.location.href,pageId:window.trekkie?.trekkie?.defaultAttributes?.microSessionId}}const kr={id:"ac8dfa8e6bcefa9e2adf29ddbd83b2ff5c11ee7c1f4369f6a09b399bb6116b63",type:"mutation",name:"SubmitForCompletion",source:""};function Er(e){switch(e.parts.postPurchaseInquiryStatus.peek()){case"success":case"done":return"SUCCESS";case"declined":return"DECLINED";case"error":return"ERROR";case"timeout":return"TIMEOUT";default:return}}function _n({variables:e,errors:t,sellerProposal:o}){if(!is(t))return e;const n=ln(o.tax),s=an(o.duty),i=yn(n,s);return{...e,taxes:{...e.taxes,...o.tax?i:{}}}}function Rr(e){return e&&e.consolidated.delivery.termsStatus==="PENDING"?e.remoteNegotiations.reduce((t,{result:o})=>{if(ut(o)){const n=o.sellerProposal.delivery;if(n?.__typename==="PendingTerms")return Math.min(t,n.pollDelay)}return t},1/0):1/0}function Fr(e){return e&&e.consolidated.payment.termsStatus==="PENDING"?e.remoteNegotiations.reduce((t,{result:o})=>{if(ut(o)){const n=o.sellerProposal.payment;if(n?.__typename==="PendingTerms")return Math.min(t,n.pollDelay)}return t},1/0):1/0}function Lr(e){return e&&e.consolidated.taxes.termsStatus==="PENDING"?e.remoteNegotiations.reduce((t,{result:o})=>{if(ut(o)){const n=o.sellerProposal.tax;if(n?.__typename==="PendingTerms")return Math.min(t,n.pollDelay)}return t},1/0):1/0}const xr=1e3;function Sn(e){if(e?.__typename!=="NegotiationResultAvailable"&&e?.__typename!=="SubmitRejected")return xr;const{sellerProposal:t}=e,{delivery:o,payment:n,tax:s,taxExemptions:i,merchandiseDiscount:r,remote:d,deliveryDiscount:a,captcha:l,cartCheckoutValidation:m,deliveryExpectations:u,memberships:f,shopCashBalance:I,shopPromotion:v,shopDiscountOffer:S}=t,T=Math.min(Rr(d),Lr(d),Fr(d),l?.__typename==="PendingTerms"?l.pollDelay:1/0,o.__typename==="PendingTerms"?o.pollDelay:1/0,u?.__typename==="PendingTerms"?u.pollDelay:1/0,n.__typename==="PendingTerms"?n.pollDelay:1/0,s.__typename==="PendingTerms"?s.pollDelay:1/0,i?.__typename==="PendingTerms"?i.pollDelay:1/0,r.__typename==="PendingTerms"?r.pollDelay:1/0,a.__typename==="PendingTerms"?a.pollDelay:1/0,m?.__typename==="PendingTerms"?m.pollDelay:1/0,f?.__typename==="PendingTerms"?f.pollDelay:1/0,I?.__typename==="PendingTerms"?I.pollDelay:1/0,v?.__typename==="PendingTerms"?v.pollDelay:1/0,S?.__typename==="PendingTerms"?S.pollDelay:1/0);return T===1/0?0:T}
1class Dr extends Error{constructor(){super(...arguments),this.name="MissingSourceError"}}class Nr extends Error{constructor(){super(...arguments),this.name="ManagedMarketsOnDomesticCheckoutError"}}function An({sellerProposal:e,buyerProposal:t={__typename:"Proposal",buyerIdentity:{__typename:"UnavailableTerms"},merchandise:{__typename:"UnavailableTerms"},isShippingRequired:!0,merchandiseDiscount:{__typename:"FilledDiscountTerms",acceptUnexpectedDiscounts:!1,lines:[]},deliveryDiscount:{__typename:"FilledDiscountTerms",acceptUnexpectedDiscounts:!1,lines:[]},delivery:{__typename:"UnavailableTerms"},subtotalBeforeTaxesAndShipping:{__typename:"AnyConstraint"},runningTotal:{__typename:"AnyConstraint"},total:{__typename:"AnyConstraint"},hasOnlyDeferredShipping:!1,attribution:{__typename:"Attribution",attributions:[]},saleAttributions:{__typename:"SaleAttributions",attributions:[]},legacyAggregatedMerchandiseTermsAsFees:[],legacySubtotalBeforeTaxesShippingAndFees:{__typename:"AnyConstraint"},note:{__typename:"Note",message:null,customAttributes:[]}},violations:o=[],silenceViolations:n=void 0,proposedPaymentLines:s,currentUcp:i,observability:r,shop:d}){const{remoteMerchandise:{remoteBuyerMerchandiseLines:a,remoteSellerMerchandiseLines:l,stableIdToShopId:m},remoteDelivery:u,remotePayment:f}=bo(e?.remote),I=!!e?.remote?.remoteNegotiations.length,[v,S]=I?[Rt(e?.merchandise,l),Rt(t?.merchandise,a)]:[e?.merchandise,t?.merchandise],T=_o(e?.remote),y=Xt(o,n),h=So({sellerProposal:e,buyerProposal:t,negotiationViolations:y,sellerMerchandise:v}),C=Lt(e?.payment,h?.runningTotal);if(!e)throw new Dr("There is no receipt or sellerProposal");const A=e.buyerIdentity.__typename==="UnavailableTerms";e.buyerIdentity.__typename!=="FilledBuyerIdentityTerms"&&r?.leaveErrorBreadcrumb("getNegotiatedPartsForUI: buyer identity terms are unavailable/pending",{__typename:e.buyerIdentity.__typename});const w=Ws(e.buyerIdentity),F=t?.subtotalBeforeTaxesAndShipping,k=e.__typename==="Proposal"?Ao(e.subtotalBeforeTaxesAndShipping,F,y,v):void 0,_=t?.legacySubtotalBeforeTaxesShippingAndFees,E=e.__typename==="Proposal"?Io(e.legacySubtotalBeforeTaxesShippingAndFees,_,y,v):void 0,p=e.__typename==="Proposal"?To(e.legacyAggregatedMerchandiseTermsAsFees):{lines:[]},c=t?.runningTotal,g=e.__typename==="Proposal"?Mo(e.runningTotal,c,y,v):void 0,M=Co(e.payment),P=Po(e.payment),L=e.payment?.__typename==="FilledPaymentTerms"&&e.payment.isImmediateAmountReducedForRedeemables,x=e.__typename==="Proposal"?ko(e.deferredTotal??void 0,M?.dueDate??void 0):void 0,{checkoutTotal:O,checkoutTotalBeforeTaxesAndShipping:R,checkoutTotalTaxes:N}=t,W=e.poNumber??void 0,H=e.__typename==="Proposal"?ot(e.checkoutTotal,O,y,v):void 0,B=e.__typename==="Proposal"?ot(e.checkoutTotalBeforeTaxesAndShipping,R,y,v):void 0,z=e.__typename==="Proposal"?ot(e.checkoutTotalTaxes,N,y,v):void 0,X=e.total&&e.total.__typename!=="AnyConstraint"?De(e.total):void 0,Q=e.totalSavings&&e.totalSavings.__typename==="MoneyValueConstraint"?De(e.totalSavings):void 0,D=Eo(e.recurringTotals),G=e.subtotalAfterMerchandiseDiscounts&&e.subtotalAfterMerchandiseDiscounts.__typename!=="AnyConstraint"?De(e.subtotalAfterMerchandiseDiscounts):void 0,j=e.subtotalBeforeReductions&&e.subtotalBeforeReductions.__typename!=="AnyConstraint"?De(e.subtotalBeforeReductions):void 0,te=e.deliveryExpectations?.__typename==="PendingTerms",se=e.delivery.__typename==="PendingTerms",qe=e.captcha?.__typename==="PendingTerms",ue=Ro(v,S,y),V=jt(ue.lines),ne=Fo(ue.lines),ce=Lt(e.payment,g),fe=!!Qt({deferredTotal:x,checkoutTotal:H,paymentFlexibilityPaymentTermsTemplate:M})?.amount,$=Lo(e.payment,f.availablePaymentLines),Z=xo({availablePayments:$,hasPayableDeposit:fe}),ie=d.paymentMethodAutoSelectionDisabled,He=Wt(d)&&Yt({hasSellingPlan:V,hasFixedSellingPlan:ne,paymentTermsTemplateType:M?.type}),b=Do({payment:e.payment,sortedPaymentMethods:Z,runningTotal:g,paymentDue:ce,deferredTotal:x,checkoutTotal:H,paymentMethodAutoSelectionDisabled:ie,requiresVaulting:V,proposedPaymentLines:s,hasPayableDeposit:fe,hasFixedSellingPlan:ne,paymentTermsTemplateType:M?.type,preserveAllocatedImmediatePaymentLineAmount:He,observability:r}),Ye=e.payment.__typename==="FilledPaymentTerms"?e.payment.paymentMethodHistory:[],re=A?void 0:Qs(e.buyerIdentity),me=Kt(e.note),We=Jt(e.note),ge=me&&!!e.delivery&&We,ve=No({delivery:e.delivery,remoteDelivery:u});ve?.countryCode==="US"&&Z.some(Ee=>Ee.type==="direct"&&Ee.name==="flow_commerce")&&r?.error(new Nr("flow_commerce gateway returned from availablePaymentMethods for domestic shipping address"),{metadata:{value:{availablePaymentMethods:JSON.stringify(Z),proposedPaymentLines:JSON.stringify(s),paymentLines:JSON.stringify(b)}}});const be=wo({delivery:e.delivery,deliveryMethods:d.shipPickupInOneOrderEnabled?e.deliveryMethods:void 0,negotiatedMerchandise:v,buyerDelivery:t?.delivery,violations:y,isPointOfSale:me,isPointOfSaleShipToHome:ge,remoteDelivery:u}),_e=Oo(e.attribution),pe=ks(e.attribution),ae=Es({deliveryExpectations:e.deliveryExpectations}),pt=_e===void 0&&pe===void 0?void 0:{..._e,...pe},Se=Rs(e.saleAttributions),Ae=Fs(e.tip),Ie=Ls(e.tip),Te=e.localizationExtension?.fields,Me=e.scriptFingerprint?xs(e.scriptFingerprint):void 0,he=e.transformerFingerprintV2||void 0,Qe=Ds(e.availableRedeemables),ze=Ns(e.shopCashBalance),je=ws(e.shopPromotion),$e=Os(e.shopDiscountOffer),Ce=e.checkoutCompletionTarget??"ORDER",Pe="billingAddress"in e.payment?Bo(e.payment.billingAddress):void 0,ye=e.memberships?Bs(e.memberships):void 0,ke=u?.isShippingRequired??e.isShippingRequired??t?.isShippingRequired;return{billingAddress:Pe,...se?void 0:{deliveryNext:be},sellability:ct({shop:d,sellerProposal:e,missingSellerProposalReason:"Proposal.Unknown",isShippingRequired:ke,observability:r}),deliveryExpectations:te?void 0:ae,shippingAddress:ve,merchandiseLines:ue,paymentMethodHistory:Ye,paymentMethods:Z,paymentLines:b,paymentDue:ce,...re?{contactInfo:re}:void 0,duties:an(e.duty),optionalDuties:e.optionalDuties?Xs(e.optionalDuties):void 0,landedCostDetails:e.landedCostDetails?.incotermInformation??void 0,dutiesIncluded:e.dutiesIncluded?e.dutiesIncluded:void 0,taxes:ln(e.tax),remoteTaxDetails:Js(e.remote),taxExemptions:Yo(e.taxExemptions),discountLines:Ho({merchandiseDiscount:e.merchandiseDiscount,deliveryDiscount:e.deliveryDiscount}),legacyRepresentProductsAsFees:e.legacyRepresentProductsAsFees,totalSavings:Q,subtotal:k,legacySubtotalBeforeTaxesShippingAndFees:E,legacyMerchandiseLinesAsFees:p,runningTotal:g,deferredTotal:x,checkoutTotal:H,checkoutTotalBeforeTaxesAndShipping:B,checkoutTotalTaxes:z,total:X,purchaseOrderNumber:W,recurringTotals:D,subtotalAfterMerchandiseDiscounts:G,subtotalBeforeReductions:j,hasOnlyDeferredShipping:e.hasOnlyDeferredShipping,acceptEmailMarketing:Ks(e.buyerIdentity),emailMarketingConsentGrantReached:$s(e.buyerIdentity),acceptSmsMarketing:js(e.buyerIdentity),smsMarketingPhone:zs(e.buyerIdentity)??void 0,allViolations:o,buyerIdentity:w,tipOptions:Ae,tipLines:Ie,localizationExtensions:Te,scriptFingerprint:Me,transformerFingerprintV2:he,attribution:pt,managedByMarketsPro:e.managedByMarketsPro,managedMarketsPaymentProcessor:e.managedMarketsPaymentProcessor,...qe?void 0:{captcha:qo(e.captcha,y)},availableRedeemables:Qe,shopCashBalance:ze,shopPromotion:je,shopDiscountOffer:$e,saleAttributions:Se,alternativePaymentCurrency:Vs(e.alternativePaymentCurrency,b),lpmDisclosure:e.lpmDisclosure??void 0,isImmediateAmountReducedForRedeemables:L,checkoutCompletionTarget:Ce,paymentFlexibilityPaymentTermsTemplate:M,depositConfiguration:P,isShippingRequired:ke,cartMetafields:Go(e.cartMetafields),customFields:d.hasFlagEnabled(Vo)?Us(e.customFields):void 0,memberships:ye,remoteMerchandiseDetails:{stableIdToShopId:m,mergedBuyerProposalMerchandise:S}
1,remotePaymentDetails:f.paymentDetails,remoteSessionDetails:T,remoteConsolidatedTotals:h,remotePaymentDue:C,remoteTotalDetails:Uo({remote:e?.remote,negotiationViolations:y,sellerMerchandise:v}),shopPayEnabledForSellerOfRecord:e.shopPayEnabled,ucp:{...i,continueUrl:e.ucp?.continueUrl??void 0}}}function Bt(e){return e.split(".").reduce((o,n)=>{if(n[0]==="$")return o;const s=wr(n);return o.concat(s)},[])}function wr(e){const t=e.split("["),o=t[0],n=t[1];if(o===void 0||n===void 0)return[e];const s=n.replace(/[[\]']+/g,"");return[o,Number(s)]}function Ut(e,t){return e.reduce((o,n)=>o!=null&&typeof o=="object"?o[n]:null,t)??null}function Or(e,t,o){if(rs.has(t)){const i=Ut(Bt(e),o);return i?Wo(i)??null:null}if(!Qo.has(t))return null;const n=zo(e);if(!n)return null;const s=Ut(Bt(n.linePath),o);return typeof s?.stableId=="string"?{merchandiseLine:{stableId:s.stableId}}:null}function lt(e,t){return e.reduce((o,n)=>{if(!n.__typename)return o;const{code:s,localizedMessage:i,nonLocalizedMessage:r,localizedMessageHtml:d}=n;let a;"target"in n&&typeof n.target=="string"?a=n.target:"from"in n&&typeof n.from=="string"&&(a=n.from);const l=a?Or(a,s,t):null,m={code:s,localizedMessage:i,nonLocalizedMessage:r,localizedMessageHtml:d};switch(n.__typename){case"InputValidationError":o.push({...m,type:n.__typename});break;case"RemoveTermViolation":o.push({...m,type:n.__typename,target:n.target,targetEntity:l});break;case"AcceptNewTermViolation":o.push({...m,type:n.__typename,target:n.target});break;case"ConfirmChangeViolation":o.push({...m,type:n.__typename,from:n.from,targetEntity:l,to:n.to});break;case"UnprocessableTermViolation":o.push({...m,type:n.__typename,target:n.target,...l?{targetEntity:l}:{}});break;case"UnresolvableTermViolation":o.push({...m,type:n.__typename,target:n.target});break;case"ApplyChangeViolation":o.push({...m,type:n.__typename,target:n.target,from:n.from,to:n.to,...l?{targetEntity:l}:{}});break;default:{o.push({...m,type:"GenericError"});break}}return o},[])}class Br extends Error{constructor(){super(...arguments),this.name="UnknownCompletionTypeError"}}class Ur extends mt{constructor(){super(...arguments),this.name="SubmitRejectedMissingContactMethod"}}class Vr extends Error{constructor(){super(...arguments),this.name="UnknownMetafieldTypeError"}}const Gr={CheckpointDenied:"SubmitForCompletion.CheckpointDenied",SubmitAlreadyAccepted:"SubmitForCompletion.SubmitAlreadyAccepted",SubmitFailed:"SubmitForCompletion.SubmitFailed",SubmitRejected:"SubmitForCompletion.Unknown",SubmitSuccess:"SubmitForCompletion.SubmitSuccess",SubmittedForCompletion:"SubmitForCompletion.SubmittedForCompletion",Throttled:"SubmitForCompletion.Throttled",TooManyAttempts:"SubmitForCompletion.TooManyAttempts",TooManyRequests:"SubmitForCompletion.TooManyRequests"};function qr(e){return e==null?"SubmitForCompletion.Unknown":Gr[e]}function Hr({submitForCompletion:e,buyerProposal:t,violations:o,proposedPaymentLines:n,observability:s,negotiator:i}){switch(e.__typename){case"SubmitRejected":return An({sellerProposal:e.sellerProposal,buyerProposal:t,violations:o,proposedPaymentLines:n,currentUcp:i.current.fields.ucp.value,observability:s,shop:i.shop});case"CheckpointDenied":case"SubmitFailed":case"Throttled":case"TooManyAttempts":case"TooManyRequests":return{sellability:ct({shop:i.shop,missingSellerProposalReason:qr(e.__typename),observability:s})};case"SubmitSuccess":case"SubmitAlreadyAccepted":case"SubmittedForCompletion":return{};default:return{}}}const Vt={ATTEMPTS:5,TIMEOUT:5e3};function In(e){return"receipt"in e&&e.receipt.__typename==="ReceiptNotFound"}function Yr(){let e=0,t;return{shouldRetry(o){return In(o)?(e+=1,t??=Date.now(),e<=Vt.ATTEMPTS&&Date.now()-t<=Vt.TIMEOUT):!1},get attempts(){return e}}}function Wr(e){switch(e.valueType.toUpperCase()){case"STRING":return"STRING";case"JSON_STRING":return"JSON_STRING";case"INTEGER":return"INTEGER";default:throw new Vr(`Unexpected metafield valueType: ${e.valueType}`)}}function Qr(e){const{extensibility:t}=e.checkout;return t.ui.metafields.value.map(n=>({...n,value:String(n.value),valueType:Wr(n)}))}function Gt({paymentLineTypes:e,status:t,observability:o,interfaceFlow:n,blockedByExtension:s,activeWalletSession:i}){const r=e.at(0);(r==="APPLE_PAY"||r==="GOOGLE_PAY")&&o.counter({name:"wallet_completion_extension_result",value:1,attributes:{wallet_type:r,status:t,interface_flow:n,blocked_by_extension:s,active_wallet_session:i?.wallet,wallet_as_payment_method:i?.asPaymentMethod}})}async function Fa(e,t,o){const{negotiating:n,isActive:s}=e.start();t.leaveErrorBreadcrumb("[SubmitForCompletion] Running completion interceptors");const i=await e.runInterceptors({negotiationStage:"completion"});if(t.leaveErrorBreadcrumb("[SubmitForCompletion] completion isActive",{isActive:s()}),!s()){const u="[SubmitForCompletion] Blocked due to stale negotiation";return t.leaveErrorBreadcrumb(u),e.observability.log("submit_for_completion_progression_blocked",u,{reason:"stale_negotiation"}),{status:"stale",phase:"interceptors"}}if(!e.source.sourceId){const u=[jo.MissingSourceId];return t.leaveErrorBreadcrumb("[SubmitForCompletion] Blocked due to missing sourceId",{reasons:u}),{status:"invalid",reasons:u}}const r=e.parts.paymentLines.value.map(u=>u.method.type==="wallet"||u.method.type==="walletsPlatformPaymentMethod"?u.method.name:u.method.type),d=e.checkout.extensibility.ui.search().peek().some(u=>u.capabilities.blockProgress);if(i.behavior==="block"){const{reasons:u,errors:f,context:I}=i;return t.leaveErrorBreadcrumb("[SubmitForCompletion] Blocked by client side interceptors",{reasons:u,paymentLineNames:r,interfaceFlow:e.parts.interfaceFlow.value,activeWalletSession:e.checkout.wallets.activeSession.value}),e.observability.log("submit_for_completion_progression_blocked","[SubmitForCompletion] Blocked by client side interceptors",{reason:"interceptor_block",reasons:u,errors:f,context:I,paymentLineNames:r,interfaceFlow:e.parts.interfaceFlow.value,activeWalletSession:e.checkout.wallets.activeSession.value}),d&&Gt({paymentLineTypes:r,status:"blocked",observability:e.observability,interfaceFlow:e.parts.interfaceFlow.value,blockedByExtension:!!I?.some(v=>v?.extension),activeWalletSession:e.checkout.wallets.activeSession.value}),e.validationErrors.value=f,e.checkout.rememberMe.unstable_setCreateAccountOptIn(!1),{status:"invalid",reasons:u}}else d&&Gt({paymentLineTypes:r,status:"allowed",observability:e.observability,interfaceFlow:e.parts.interfaceFlow.value,activeWalletSession:e.checkout.wallets.activeSession.value});e.validationErrors.value=[],o?.onValidationSuccess?.(),e.track();const a=e.current.peek();Cr({observability:t,userEvents:e.userEvents,paymentLines:e.parts.paymentLines.peek(),paymentMethods:a.paymentMethods,paymentDue:a.paymentDue,remotePaymentDue:a.remotePaymentDue,remoteMerchandiseDetails:a.remoteMerchandiseDetails,shopId:e.shop.id,checkoutToken:e.source.checkoutSessionIdentifier});const l=$o(e.source,e.persistenceManager),m=e.parts.paymentLines.peek();try{let u;
1try{u=await Zt()}catch(v){return t.leaveErrorBreadcrumb("[SubmitForCompletion] Blocked completion because receipt mapper failed to load",{error:String(v)}),{status:"fetch_failed",reason:"Receipt mapper failed to load before submit for completion",isActionable:!1}}if(!s()){const v="[SubmitForCompletion] Blocked due to stale negotiation";return t.leaveErrorBreadcrumb(v),e.observability.log("submit_for_completion_progression_blocked",v,{reason:"stale_negotiation"}),{status:"stale",phase:"submission"}}const f=n([]);return await(async()=>{let v;const S=Yr();do{const T=bn(e,{isCompleting:!0,customizeNegotiation:o?.customizeCompletion,observability:e.observability,wallets:e.checkout.wallets,selectedBillingAddress:e.shopPay.session.selectedBillingAddress.value}),y=$r(T,v),{data:h,error:C}=await e.graphql.mutate(kr,{variables:{input:y,attemptToken:l,metafields:Qr(e),postPurchaseInquiryResult:Er(e),analytics:Pr()}});if(!h)return{status:"fetch_failed",reason:C?`${C.message}`:"Submit for completion failed",isActionable:dn(C).actionable};if(In(h.submitForCompletion)){if(!S.shouldRetry(h.submitForCompletion))return{status:"fetch_failed",reason:"Submit for completion returned ReceiptNotFound",isActionable:!1};t.leaveErrorBreadcrumb("[SubmitForCompletion] Receipt not found; retrying completion",{submitForCompletionType:h.submitForCompletion.__typename,receiptNotFoundAttempts:S.attempts}),await at(Ko);continue}const A=en(h.submitForCompletion.__typename==="SubmitRejected"?h.submitForCompletion.errors:void 0,h.submitForCompletion.__typename==="SubmitRejected"?h.submitForCompletion.sellerProposal:void 0,h.submitForCompletion.__typename==="SubmitRejected"?h.submitForCompletion.buyerProposal:void 0),w=nn(h.submitForCompletion,A);if(h.submitForCompletion.__typename==="SubmitRejected"&&w.length){v=h.submitForCompletion,await at(Sn(h.submitForCompletion));const E=await e.runInterceptors({negotiationStage:"completion"});if(E.behavior==="block"){const p=E.reasons;return t.leaveErrorBreadcrumb("Blocked polled completion",{reasons:p,pendingFields:w}),{status:"invalid",reasons:p}}continue}const F=h?.submitForCompletion.__typename==="SubmitRejected"?h.submitForCompletion.buyerProposal:void 0,k=Hr({submitForCompletion:h.submitForCompletion,buyerProposal:F,violations:A,proposedPaymentLines:m,observability:t,negotiator:e});f({updated:k,buyerProposal:F}),h?.submitForCompletion.__typename==="SubmitRejected"&&A&&A.length>0&&(t.leaveErrorBreadcrumb("Submit for completion was rejected",{violations:A.map(E=>E.code)}),A.some(E=>E.code==="BUYER_IDENTITY_MISSING_CONTACT_METHOD")&&(t.log("submit_for_completion_rejected_with_missing_contact_method","Missing contact method",{proposedEmail:e.parts.email.peek(),negotiatedCustomerProfileEmail:e.current.peek().buyerIdentity?.customerProfile?.email,negotiatedContactInfoEmail:e.current.peek().contactInfo?.email}),t.error(new Ur("SubmitForCompletion returned BUYER_IDENTITY_MISSING_CONTACT_METHOD",{groupingHash:zr(e)}),{severity:"info"})),on(A,e.parts,e.context,e.observability));const _=jr(h,e,k,A??[],u);return(_.status==="alreadyCompleted"||_.status==="success")&&(e.checkout.configuration.renderContextToken.update(_.renderContextToken??void 0),e.checkout.configuration.update({deferredProfileChangeId:_.configurationRecordId})),_}while(!0)})()}finally{e.checkout.rememberMe.unstable_setCreateAccountOptIn(!1)}}function zr(e){const t=e.current.peek().buyerIdentity?.customerProfile?.email,o=e.current.peek().contactInfo?.email,n=e.current.peek().buyerIdentity?.customerProfile?.__typename,s=[];return!t&&!o&&e.source.type==="orderEdit"?s.push("orderEditWithBlankNegotiatedEmail"):(e.checkout.configuration.layout.isOnePage.value?s.push("onePage"):s.push("threePage"),e.checkout.wallets.escalatedWallet.value?s.push(e.checkout.wallets.escalatedWallet.value):e.checkout.identity.current.value==="shopPay"?s.push("shopPay"):n==="CustomerProfile"?s.push("customerAccount"):n==="BusinessCustomerProfile"?s.push("businessCustomer"):s.push("guest")),s.join("::")}function jr({submitForCompletion:e},{throttle:t,persistenceManager:o,router:n,lastJourneyProgression:s,source:i},r,d,a){switch(e.__typename){case"SubmitSuccess":case"SubmitAlreadyAccepted":{const l=a(e.receipt);return(l.status==="processed"||l.status==="failed")&&o&&J(o,i),{status:"success",receipt:l,configurationRecordId:e.configurationRecordId??void 0,renderContextToken:e.renderContextToken??void 0}}case"SubmittedForCompletion":{const l=a(e.receipt,{skipToThankYouPage:!0});return o&&J(o,i),{status:"alreadyCompleted",receipt:l,configurationRecordId:e.configurationRecordId??void 0,renderContextToken:e.renderContextToken??void 0}}case"Throttled":return o&&J(o,i),t.set(rt(e)),{status:"throttled"};case"SubmitRejected":return o&&J(o,i),{status:"rejected",negotiated:r,violations:d,errors:lt(d,e.buyerProposal)};case"TooManyRequests":{o&&J(o,i);const l={type:"failed",negotiationStage:"completion",fetchFailed:!1,reason:"tooManyRequests"};return s.value=l,{status:"tooManyRequests"}}case"SubmitFailed":return o&&J(o,i),{status:"failed",reason:e.reason};case"CheckpointDenied":{o&&J(o,i);const l=typeof window>"u",m=l?n.currentUrl.value.toString():void 0,u=tn(e.redirectUrl,m);return l||window.location.assign(u.href),{status:"denied"}}case"TooManyAttempts":{if(o&&J(o,i),!(typeof window>"u")){const m=new URL(e.redirectUrl);window.location.assign(m.href)}return{status:"denied"}}default:throw o&&J(o,i),new Br(`Unknown submitForCompletion type: ${e.__typename}`)}}function $r(e,t){return t?_n({variables:e,errors:t.errors,sellerProposal:{tax:t.sellerProposal?.tax,duty:t.sellerProposal?.duty}}):e}function Kr(e){return{email:qs(e,{emptyContactFallback:void 0})??null,phone:Gs(e,{emptyContactFallback:void 0})??null}}
1class ee extends Error{constructor(){super(...arguments),this.name="StaleNegotiationError"}}class qt extends Error{constructor(){super(...arguments),this.name="MissingNegotiationDataError"}}class Jr extends mt{constructor(){super(...arguments),this.name="NegotiationFailedError"}}class Xr extends mt{constructor(){super(...arguments),this.name="UnactionableNegotiationFailedError",this.unactionable=!0}}class Zr extends Error{constructor(){super(...arguments),this.name="GenericError"}}class ea extends Error{constructor(){super(...arguments),this.name="UnexpectedNegotiationResult"}}class st extends Error{constructor(){super(...arguments),this.name="EmptyMerchandiseLinesNegotiationResult"}}const ta={id:"c9a41027b82c27d382f3a66dae10bc89c1c35907dd111e6eb5eb401575ebcf2f",type:"query",name:"Proposal",source:""};function na(e,t){const{lines:o}=e;return o.length>0&&Jo(o,t).length===0}function oa(e){return e.ui.search().peek().filter(t=>t.type==="persisted")}function sa(e,t,o){if(!na(e,t))return;const n=oa(o);n.length>0&&o.ui.remove(n.map(s=>s.targetPublicIdentifier),{keepAlive:!1,reason:"remote_only_transition"})}function ia(e){return e.sent+=1,e.sent}function ra({state:e,sendSequence:t,result:o,fromNetwork:n,checkout:s,throttle:i}){if(!n||o?.__typename!=="NegotiationResultAvailable"||t<=e.seen)return;e.seen=t,s.unstable_overwriteCheckpointToken(o.checkpointData??void 0);const r=i.current;r.status==="complete"&&o.queueToken!=null?i.set({...r,token:o.queueToken}):(r.status==="inactive"||r.status==="complete")&&i.set({status:"inactive",token:o.queueToken??void 0})}function aa(e){return!e?.remoteNegotiations||e.remoteNegotiations.length===0?!1:e.remoteNegotiations.some(t=>{if(t.result?.__typename!=="RemoteNegotiationResultAvailable")return!1;const o=t.result.sellerProposal?.merchandise,n=t.result.buyerProposal?.merchandise,s=o?.__typename==="FilledMerchandiseTerms"&&(o.merchandiseLines?.length??0)>0,i=n?.__typename==="FilledMerchandiseTerms"&&(n.merchandiseLines?.length??0)>0;return s||i})}const da=new Set(["orderEdit","paymentCollection"]);function la(e,t){if(t.result.__typename!=="NegotiationResultAvailable"||da.has(e)||t.errors.some(s=>Xo.has(s.code)))return!1;const n=t.result.sellerProposal.merchandise;return n.__typename==="FilledMerchandiseTerms"&&n.merchandiseLines.length===0?!aa(t.result.sellerProposal?.remote):!1}async function*ua(e,t,o,n={reportedMissingContact:!1,reportedMissingContactCommit:!1}){const{identifier:s,negotiationStage:i}=o,r=e.checkout.wallets.activeSession.peek()?.wallet,d=o.startedInAcceleratedWalletSession??(r==="APPLE_PAY"||r==="GOOGLE_PAY"),{isActive:a,negotiating:l}=e.start();t.leaveErrorBreadcrumb("[Negotiate] Running negotiation interceptors",{identifier:s.toString(),negotiationStage:i});const m=await e.runInterceptors({negotiationStage:i,skipEffects:o.skipStateUpdates});if(!a()){t.leaveErrorBreadcrumb("[Negotiate] Not doing negotiation due to stale negotiation"),yield{status:"stale"};return}if(!o.skipStateUpdates){const{errors:h}=m;e.validationErrors.value=h}if(m.behavior==="block"){const{reasons:h,errors:C,context:A}=m;t.leaveErrorBreadcrumb("[Negotiate] Blocked negotiation",{reasons:h,errors:C,context:A}),yield{status:"invalid",reasons:h};return}let u=bn(e,{customizeNegotiation:o?.customizeNegotiation,paymentLinesObservability:t,selectedBillingAddress:e.shopPay.session.selectedBillingAddress.value}),f;o.skipStateUpdates||(f=l(o.loading));function I(){f?.({updated:{}})}const{graphql:v,throttle:S}=e,T=e.parts.paymentLines.peek(),y=e.shop.hasFlagEnabled(Zo);try{let h=!0,C;do{if(!a())throw new ee;!h&&!n.reportedMissingContact&&(n.reportedMissingContact=ca({variables:u,negotiator:e,negotiationStage:i,customized:o.customizeNegotiation!=null})),u=ha(u,C);const{dirty:A}=e.track(u),w=!A&&h&&!o.force,F=e.collectPendingNegotiationEventIds(s,i),k=await gs(async()=>{const p=()=>v.staticQuery(ta,{cache:w,variables:u,getCacheKey({id:L},x){return`${L}${as(x?vs(x):{})}`},...F.length&&{additionalHeaders:{"Shopify-Checkout-Event-Ids":F.join(",")}}}),c=Date.now(),{data:g,error:M}=await e.serializeNegotiationRequest(async()=>
1{if(!a())throw new ee;u={...u,checkpointData:e.checkout.checkpointToken.value,queueToken:vn(S)},ma({negotiator:e,negotiationStage:i,waitedMs:Date.now()-c}),e.serializedTokenRotation??={sent:0,seen:0};const L=e.serializedTokenRotation,x=ia(L),O=p(),R=O instanceof Promise,N=await O;return ra({state:L,sendSequence:x,result:N.data?.session?.negotiate?.result,fromNetwork:R,checkout:e.checkout,throttle:e.throttle}),N});if(M)throw M;const P=g?.session?.negotiate;if(P==null)throw new qt("negotiation data is missing");if(pa({result:P.result,negotiator:e,negotiationStage:i,customized:o.customizeNegotiation!=null,superseded:!a(),telemetry:n}),!a()){const L="[Negotiate] Negotiation is stale";throw t.leaveErrorBreadcrumb(L),e.observability.log("negotiate_stale_negotiation_detected",L),new ee}if(la(e.source.type,P))throw new st;return P},{shouldRetry:p=>p!=null&&!(p instanceof ee)&&!(p instanceof st)&&!(p instanceof qt)}),_=k.result,E=k.errors;switch(t.leaveErrorBreadcrumb("[Negotiate] Negotiation completed",{negotiationResult:_.__typename,negotiationViolations:E.map(p=>p.nonLocalizedMessage)}),_.__typename){case"NegotiationResultAvailable":{const p=en(E,_.sellerProposal,_.buyerProposal)??[];e.checkout.unstable_overwriteCheckpointToken(_.checkpointData??void 0),S.set(rt(_));const c=nn(_,p);e.checkout.configuration.renderContextToken.update(_.renderContextToken??void 0),C=k;const g=_.buyerProposal,M=An({sellerProposal:_.sellerProposal,buyerProposal:g,violations:p,silenceViolations:o.silenceViolations,proposedPaymentLines:T,currentUcp:e.current.fields.ucp.value,observability:t,shop:e.shop}),P=Object.entries(M).reduce((G,j)=>{const[te,se]=j;return o.fieldsToResolve?.includes(te)&&c.includes(te)?G:{...G,[te]:se}},{}),L=Xt(p,o.silenceViolations);ds({observability:t,negotiationStage:i,silenceViolations:o.silenceViolations,violations:p,retainedViolations:L,reportedCodes:e.reportedSilencedViolationCodes});const x=on(L,e.parts,e.context,e.observability),{autoResolved:O,blockingProgress:R,informational:N,removingItems:W,invalidInputs:H,mustAcceptTerms:B,unresolvable:z,other:X}=ls(L);if(t.leaveErrorBreadcrumb("[Negotiate]: Violation handling result",{silenceViolations:o.silenceViolations,hasErrors:x.hasErrors,requiresRenegotiation:x.requiresRenegotiation,surfacedToBuyer:{blockingProgress:R,informational:N,removingItems:W,invalidInputs:H,mustAcceptTerms:B,unresolvable:z},autoResolved:O,other:X}),x.requiresRenegotiation){yield*ua(e,t,{...o,startedInAcceleratedWalletSession:d},n);return}let Q=us({checkout:e.checkout,shop:e.shop,profileId:_.configurationRecordId??e.checkout.configuration.profileId.peek()});if(Q&&d&&!o.threePageWalletEscalation&&!e.hasPendingThreePageWalletEscalation()){const G=e.checkout.configuration.profileKey.peek();Q=G?.id===Q.id?G:{...Q,requireBusinessCriticalOnly:!1}}const D=await cs(()=>{f?.({updated:P,loadingFields:c,buyerProposal:g})},{trigger:"negotiation",profileRequest:Q,graphql:e.graphql,extensibility:e.checkout.extensibility,configuration:e.checkout.configuration,observability:e.observability,userEvents:e.userEvents,isActive:a,runInterceptors:e.runInterceptors.bind(e),validationErrors:e.validationErrors,telemetryContext:{source:e.source,shop:e.shop,sessionToken:e.sessionToken,current:e.current}});if(!a())throw D?.(),new ee;if(D&&Ys(D,["checkout-profile-change"]),sa(e.current.fields.merchandiseLines.value??{lines:[]},e.current.fields.remoteMerchandiseDetails.value,e.checkout.extensibility),(ms(p).length||ps(p).length)&&e.track(u),y&&!o.skipStateUpdates&&a()&&x.hasErrors){const{inventoryRecoverySignal:G}=e.context,j=G.value;j&&!j.dismissed&&(G.value={...j,dismissed:!0})}if(yield x.hasErrors?{status:"error",negotiated:e.current.peek(),violations:p,errors:lt(p??[],_.buyerProposal),pendingFields:c}:{status:"success",negotiated:e.current.peek(),violations:p,errors:lt(p??[],_.buyerProposal),pendingFields:c},c.length===0)return;break}case"CheckpointDenied":{f?.({updated:de({negotiator:e,observability:t,typename:_.__typename})});const p=typeof window>"u",c=p?e.router.currentUrl.value.toString():void 0,g=tn(_.redirectUrl,c);p||window.location.assign(g.href),yield{status:"denied"};return}case"Throttled":{f?.({updated:de({negotiator:e,observability:t,typename:_.__typename})}),yield{status:"throttled"},S.set(rt(_));return}case"TooManyRequests":{f?.({updated:de({negotiator:e,observability:t,typename:_.__typename})});const p={type:"failed",negotiationStage:i,fetchFailed:!1,reason:"tooManyRequests"};e.lastJourneyProgression.value=p,yield{status:"tooManyRequests"},e.observability.log("negotiate_result_returned","[Negotiate] Negotiation halted due to too many requests"),e.observability.counter({name:"negotiation_result_too_many_requests",value:1});return}case"SubmittedForCompletion":{f?.({updated:de({negotiator:e,observability:t,typename:_.__typename})});let p;try{p=await Zt()}catch(g){if(!a())throw new ee;const M=_.receipt,P=Hs(M);if(t.leaveErrorBreadcrumb("[Negotiate] Receipt mapper failed to load for already completed negotiation",{error:String(g),receiptType:M.__typename}),P){yield{status:"alreadyCompleted",receipt:P};return}if(M.__typename==="ProcessedReceipt"&&M.orderStatusPageUrl){window.location.replace(M.orderStatusPageUrl);return}yield{status:"fetch_failed",reason:"Receipt mapper failed to load after submitted for completion",isActionable:!1};return}if(!a())throw new ee;yield{status:"alreadyCompleted",receipt:p(_.receipt,{skipToThankYouPage:!0})};return}case"NegotiationResultFailed":{f?.({updated:de({negotiator:e,observability:t,typename:_.__typename})});const p=k.errors.map(c=>c.code);throw _.reportable===!1&&(e.observability.log("negotiate_result_returned",`[Negotiate] Negotiation result failed, violations: ${p.join(",")}`),e.observability.counter({name:"negotiation_result_failed",value:1})),new Zr("Server failed to fulfill the request and to identify the exact issue.",{cause:_.reportable?new Jr(`Negotiation request failed. Violations = ${p.join(",")}`):new Xr(`Negotiation request failed. Violations = ${p.join(",")}`)})}default:throw f?.({updated:de({negotiator:e,observability:t,typename:void 0})}),new ea(`Negotiation result type not implemented yet: ${_.__typename}`)}if(h=!1,o.skipStateUpdates)break;await at(Sn(_))}while(!0)}catch(h){if([bs,_s,Ss].some(C=>h instanceof C)){const{actionable:C}=dn(h),A=h.message??"Negotiation fetch failed";if(hs(A)||!C){e.observability.log("negotiate_result_error_returned","[Negotiate] Negotiation network error",{reason:A}),e.observability.counter({name:"negotiation_network_error",value:1,attributes:{reason:ys(A)}}),I(),yield{status:"fetch_failed",reason:A,isActionable:C,networkError:!0};return}}if(h instanceof ee){yield{status:"stale"};return}if(h instanceof st){e.checkout.configuration.allowRedirectToStorefront?(e.observability.counter({name:"empty_merchandise_lines_redirect",value:1,attributes:{source:e.source.type}}),fs({client:e.client,url:e.url,source:e.source,configuration:e.checkout.configuration})):(I(),yield{status:"stale"});return}throw e.track(),h}}function ca({variables:e,negotiator:t,negotiationStage:o,customized:n}){const s=e.buyerIdentity,i=!!t.parts.email.peek().trim()&&s?.email===void 0,r=!!t.parts.p
1hone.peek().trim()&&s?.phone===void 0;if(!i&&!r)return!1;let d="both";r||(d="email"),i||(d="phone");const a={negotiationStage:o,customized:n,channel:d};return t.observability.counter({name:"negotiate_missing_contact_snapshot",value:1,attributes:a}),t.observability.log("negotiate_missing_contact_snapshot","[Negotiate] Poll is about to re-send a snapshot missing the contact method the buyer has since supplied",a),!0}function ma({negotiator:e,negotiationStage:t,waitedMs:o}){if(o<=0)return;let n=">=5000ms";o<100?n="<100ms":o<500?n="100-500ms":o<1e3?n="500-1000ms":o<5e3&&(n="1000-5000ms"),e.observability.counter({name:"negotiation_request_serialized_wait",value:1,attributes:{negotiationStage:t,bucket:n}})}function pa({result:e,negotiator:t,negotiationStage:o,customized:n,superseded:s,telemetry:i}){if(e.__typename!=="NegotiationResultAvailable")return;const r=e.buyerProposal.buyerIdentity;if(r.__typename!=="FilledBuyerIdentityTerms")return;const d=Kr(r),a=t.lastNegotiatedContactEcho;if(t.lastNegotiatedContactEcho=d,!i.reportedMissingContact||i.reportedMissingContactCommit)return;const l=!!t.parts.email.peek().trim()&&d.email==null&&!!a?.email,m=!!t.parts.phone.peek().trim()&&d.phone==null&&!!a?.phone;if(!l&&!m)return;i.reportedMissingContactCommit=!0;let u="both";m||(u="email"),l||(u="phone");const f={negotiationStage:o,customized:n,channel:u,superseded:s};t.observability.counter({name:"negotiate_missing_contact_committed",value:1,attributes:f}),t.observability.log("negotiate_missing_contact_committed","[Negotiate] Server committed a poll snapshot missing the contact method a previous response had confirmed",f)}function ha(e,t){return t&&t.result.__typename==="NegotiationResultAvailable"?_n({variables:e,errors:t.errors,sellerProposal:{tax:t.result.sellerProposal?.tax,duty:t.result.sellerProposal?.duty}}):e}function de({negotiator:e,observability:t,typename:o}){return{sellability:ct({shop:e.shop,missingSellerProposalReason:ya(o),observability:t})}}function ya(e){switch(e){case"CheckpointDenied":return"Proposal.CheckpointDenied";case"NegotiationResultFailed":return"Proposal.NegotiationResultFailed";case"SubmittedForCompletion":return"Proposal.SubmittedForCompletion";case"Throttled":return"Proposal.Throttled";case"TooManyRequests":return"Proposal.TooManyRequests";default:return"Proposal.Unknown"}}export{Fa as complete,bn as getNegotiationInput,ua as negotiate};

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.