PageSourceSearch

https://shop.realfaith.com/cdn/shopifycloud/checkout-web/assets/c1/web-mcp-runtime.1uGx4Kpb.js

js realfaith.com collected 2026-09-24 10:58:32 UTC 79,744 bytes, 1 lines download raw bytes

1import{n as x,c as ct,a as lt,b as ut,j as pt}from"./esnext-vendor.D7ldIee_.js";import{s as pe,c as oe,a as fe,R as he,b as ft,i as P,d as ht,n as Fe,e as Be,f as _t,g as mt,h as yt,C as gt,j as vt,V as X,p as bt,k as Et,l as At,m as It,F as Tt,o as Ct,r as Ee,q as Ae,t as St,u as Nt,v as Dt,w as Lt,x as wt,y as kt}from"./addresses-is-address-empty.-MuOhIyI.js";import{i as Pt}from"./constants.DowbVE6J.js";import{c as Mt}from"./checkout-updaters-helpers.DKDxNKY0.js";import{a as O,i as Rt}from"./context-browser.CzQjCL-z.js";function Ie(e){return e?.replace(/[\s-]/g,"").toUpperCase()}function Ot(e,t){return!!e?.coordinates&&e?.countryCode===t.countryCode&&(!t.zoneCode||e.zoneCode===t.zoneCode)&&Ie(e.postalCode)===Ie(t.postalCode)}class Ut{#e;#t=0;get current(){return this.#e}async during(t,n){this.#e=t,this.#t+=1;try{return await n()}finally{this.#t-=1,this.#t===0&&(this.#e=void 0)}}}const Te="tax_number",xt=["TAX_CREDENTIAL_BR","SHIPPING_CREDENTIAL_BR","TAX_CREDENTIAL_CL","SHIPPING_CREDENTIAL_CL","SHIPPING_CREDENTIAL_CN","TAX_CREDENTIAL_CO","SHIPPING_CREDENTIAL_CO","TAX_CREDENTIAL_CR","SHIPPING_CREDENTIAL_CR","TAX_CREDENTIAL_EC","SHIPPING_CREDENTIAL_EC","TAX_CREDENTIAL_ES","SHIPPING_CREDENTIAL_ES","TAX_CREDENTIAL_GT","SHIPPING_CREDENTIAL_GT","TAX_CREDENTIAL_ID","SHIPPING_CREDENTIAL_ID","TAX_CREDENTIAL_IT","SHIPPING_CREDENTIAL_KR","TAX_CREDENTIAL_MX","SHIPPING_CREDENTIAL_MX","TAX_CREDENTIAL_MY","SHIPPING_CREDENTIAL_MY","TAX_CREDENTIAL_PE","SHIPPING_CREDENTIAL_PE","TAX_CREDENTIAL_PT","SHIPPING_CREDENTIAL_PT","TAX_CREDENTIAL_PY","SHIPPING_CREDENTIAL_PY","TAX_CREDENTIAL_TR","SHIPPING_CREDENTIAL_TR","SHIPPING_CREDENTIAL_TW"],Ht=new Set(["TAX_CREDENTIAL_BR","SHIPPING_CREDENTIAL_BR","SHIPPING_CREDENTIAL_CN","SHIPPING_CREDENTIAL_KR","SHIPPING_CREDENTIAL_MX"]),qt=xt.map(e=>({key:e,required:Ht.has(e)}));function Ft(e){const t={key:Te,read(){const n=Ce(e);if(!n)return;const{title:i,value:o}=n.extension.fields;return{key:Te,purpose:"dev.shopify.shopping.declared_fields.generic",title:i.value,description:`Enter the buyer's ${i.value} tax number for this checkout.`,value_schema:{type:"string"},value:o.value||null,required:n.definition.required}},prepare(n){return n!==null&&typeof n!="string"?{requirement:"must be a string or null"}:{phase:"stage",get changed(){return n!==t.read()?.value},negotiation:{include:["localizationExtensions"],loading:[],fieldsToResolve:["localizationExtensions"]},async apply(){const i=Ce(e);return i?(i.extension.fields.value.value=n??"",!0):!1}}}};return t}function Ce(e){const n=e.proposal.proposed.localizationExtensions.value.flatMap(i=>{const o=qt.find(({key:r})=>r===i.fields.key.value);return o?[{definition:o,extension:i}]:[]});return n.length===1?n[0]:void 0}function _e(e,t){const n=new Map(t.flatMap(({targetMerchandiseLines:o})=>o.map(r=>[r.stableId,r]))),i=new Set;for(const o of e){const r=(o.lineComponents?.length?o.lineComponents:[o]).filter(s=>s.requiresShipping??n.get(s.stableId)?.requiresShipping);for(const{stableId:s}of r)i.add(s);r.length&&o.lineComponents?.length&&i.add(o.stableId)}return i}function re(e,t){return[...new Set(e.filter(({targetMerchandiseLines:n})=>n.some(({stableId:i})=>t.has(i))).flatMap(({deliveryMethodTypes:n})=>n).filter(n=>n!=="NONE"))]}function Bt(e,{proposed:t}){return{getAvailableMethodTypes:()=>e.getAvailableMethodTypes().filter(n=>!n.includes("PICKUP_POINT")),setDesiredMethod(n,i){const o=e.getSelectedMethodTypes();e.markBuyerSelection();const r=t.deliveryLines.value.map(a=>a.value),s=_e(t.merchandiseLines.value,r);if(!jt(o,n)){e.applyMethodChange(n,o,i);return}x(()=>{for(const a of t.deliveryLines.value){const c=a.value;c.targetMerchandiseLines.some(({stableId:d})=>s.has(d))&&(c.deliveryMethodTypes.length!==n.length||c.deliveryMethodTypes.some(d=>!n.includes(d)))&&(a.value={...c,deliveryMethodTypes:n})}if(e.reconcileSameMethod(n),i){if(i!==t.locationAddress.value)for(const a of t.deliveryLines.value)a.value={...a.value,deliveryMethodHandle:void 0};t.locationAddress.value=i}})}}}function jt(e,t){return e.length>0&&e.every(n=>n==="SHIPPING"||n==="LOCAL"?t.includes("SHIPPING")||t.includes("LOCAL"):t.includes(n))}function $t(e,t=[]){const n={};for(const i of t)i.name&&(n[i.name]??=[]).push(i);return{version:"2026-08-25",status:e,services:{"dev.ucp.shopping":[{version:"2026-08-25",transport:"webmcp"}]},capabilities:{"dev.ucp.shopping.checkout":[{version:"2026-08-25",spec:"https://ucp.dev/2026-08-25/specification/shopping/checkout/",schema:"https://ucp.dev/2026-08-25/schemas/shopping/checkout.json"}],"dev.ucp.shopping.fulfillment":[{version:"2026-08-25",spec:"https://ucp.dev/2026-08-25/specification/shopping/extensions/fulfillment/",schema:"https://ucp.dev/2026-08-25/schemas/shopping/fulfillment.json",extends:["dev.ucp.shopping.checkout"],requires:{protocol:{min:"2026-08-25"}}}],"dev.ucp.shopping.discount":[{version:"2026-08-25",extends:"dev.ucp.shopping.checkout",spec:"https://ucp.dev/2026-08-25/specification/discount",schema:"https://ucp.dev/2026-08-25/schemas/shopping/discount.json"}],"dev.shopify.shopping.declared_fields":[{version:"2026-09-04",extends:"dev.ucp.shopping.checkout",spec:"https://shopify.dev/ucp/specification/declared-fields",schema:"https://shopify.dev/ucp/schemas/2026-09-04/declared_fields.json",requires:{protocol:{min:"2026-04-08"}}}]},payment_handlers:n}}function $(e,t){return{...e,ucp:$t("error"in e?"error":"success",t.proposal.negotiated.fields.ucp.value?.paymentHandlers)}}function Gt(e){return Array.from(e.values()).flatMap(t=>{const n=t.read();return n?[n]:[]}).sort((t,n)=>Yt(t.key,n.key))}function Yt(e,t){return e===t?0:e<t?-1:1}function G(e,t){const n=e??[],i=new Map;for(const[r,{key:s,value:a}]of n.entries()){const c=`$.checkout.declared_fields[${r}]`,d=t.get(s);if(!d?.read())return Q(`${c}.key`,"must identify a declared field available in the current checkout");const l=d.prepare(a);if("requirement"in l)return Q(`${c}.value`,l.requirement);i.set(s,l)}const o=[];for(const[r,s]of t){if(!s.read())continue;const a=i.get(r)??s.prepare(null);if("requirement"in a)return Q("$.checkout.declared_fields",a.requirement);o.push({...a,get changed(){return a.changed},async apply(){return t.get(r)===s&&s.read()?a.apply():!1}})}return o}function Q(e,t){return{error:{code:"rejected",message:`${e}: ${t}. Nothing was applied. Call get_checkout before retrying.`}}}function Wt(e){const{email:t,phone:n}=e??{};if(!(!t&&!n))return{...t?{email:t}:{},...n?{phone_number:n}:{}}}function N(e){if(!e)return 0;const t=ct(e.currencyCode),n=new Intl.NumberFormat("en",{style:"decimal",useGrouping:!1,minimumFractionDigits:t,maximumFractionDigits:t}),[i,o=""]=n.format(e.amount).split(".");return Number(i+o.padEnd(t,"0"))}function Vt(e,t){if(!e?.lines.length)return;const n=t?new Map(t.map(({id:r},s)=>[r,s])):void 0,i=new Map,o=[];for(const r of e.lines){const{discount:s}=r;if(s.type==="code"||s.type==="discountCodeTrigger"){const a=s.title.toUpperCase();i.has(a)||i.set(a,s.title)}if("allocations"in r){const a=zt(r,n);a.amount>0&&o.push(a)}}return{codes:[...i.values()],applied:o}}function zt(e,t){const{discount:n}=e,i=[];let o=0,r=!1;for(const{target:c}of e.allocations){let d=c.index;if(c.type==="MERCHANDISELINE"&&t&&(d=c.stableId==null?void 0:t.get(c.stableId),d==null)){r=!0;continue}const l=N(c.amount);o+=l,c.type==="MERCHANDISELINE"&&d!=null?i.push({path:`$.line_items[${d}]`,amount:l}):c.type==="DELIVERYLINE"&&i.push({path:"$.totals.shipping",amount:l})}const s=n.type==="code"&&n.codeHidden,a=r?0:N(e.amount);return{title:s?"Discount":n.title,amount:o||a,...n.type==="code"&&!s&&{code:n.title},...n.type!=="code"&&{automatic:!0},...n.allocationMethod==="EACH"&&{method:"each"},...n.allocationMethod==="ACROSS"&&{method:"across"},...i.length>0&&{allocations:i}}}function K(e,{extendedAddressMode:t}){const n=e.address_country?.toUpperCase()??"",i=t.get(n),o=i===null?Xt(n,e):Kt(n,e,i);return{...Mt({...e,street_address:o.address1,extended_address:o.address2}),company:e.company??"",district:void 0,subdistrict:void 0,...o}}function me(e,t){const n=e.countryCode??"",i=t?.extendedAddressMode.get(n)??null;return{company:e.company,first_name:e.firstName,last_name:e.lastName,phone_number:e.phone,...i===null?Zt(n,e):tn(n,e,i),address_locality:e.city,address_regi
1on:e.zoneCode,address_country:e.countryCode,postal_code:e.postalCode}}function je({street_address:e="",street_name:t,street_number:n=""}){return t?.trim()?{streetName:t,streetNumber:n}:{line:e}}function Xt(e,t){const n=je(t);return{address1:"line"in n?n.line:rn(e,n),address2:t.extended_address??""}}function Kt(e,t,n){const{packedLine2:i,...o}=Jt(e,je(t)),{neighborhood:r,...s}=Qt(e,t,i);return{...o,...s,...n==="dedicated"?r!==void 0&&{district:r,neighborhood:""}:{neighborhood:r}}}function Jt(e,t){if("line"in t){const i=pe(e,t.line,!0);if(!i?.streetNumber)return{address1:t.line};const o=oe({countryCode:e,streetName:i.streetName??"",streetNumber:i.streetNumber});return o==null?{address1:t.line}:{address1:o,packedLine2:i.line2}}const n=oe({countryCode:e,...t});return n==null?{address1:We(t)}:{address1:n,...t}}function Qt(e,{extended_address:t="",district:n},i){const o=fe(e,t);if(!o)return{address2:Se(t,i)};const r=Se(o.line2??"",i),s=n??o.neighborhood??"";return{address2:Ye(e,r,s),line2:r,neighborhood:s}}function Se(e,t){return!t||t===e.trim()?e:Ve(e,t)}function Zt(e,t){return{street_address:$e(e,t),extended_address:en(e,t)}}function $e(e,{address1:t,streetName:n,streetNumber:i}){return t||!(n||i)?t:Ge(e,{streetName:n??"",streetNumber:i??""})}function en(e,{address2:t,line2:n,district:i,neighborhood:o}){const r=i||o;return n==null&&!r?t:Ye(e,n??"",r??"")}function tn(e,t,n){const i=nn(e,t,n);return{...i?.streetName?{street_name:i.streetName,street_number:i.streetNumber??""}:{street_address:$e(e,t)},...on(e,t,n)}}function nn(e,t,n){return n==="dedicated"&&(t.streetName!=null||t.streetNumber!=null)?t:t.address1?.includes(he)?pe(e,t.address1):null}function on(e,t,n){if(n==="dedicated"&&(t.line2!=null||t.district!=null)){const o=t.district??t.neighborhood;return{extended_address:t.line2,...o!=null&&{district:o}}}const i=t.address2?.includes(he)?fe(e,t.address2):null;return i?{extended_address:i.line2??"",district:i.neighborhood??""}:{extended_address:t.address2||t.line2,...n==="concatenated"&&t.neighborhood!=null&&{district:t.neighborhood}}}function Ge(e,t){return oe({countryCode:e,...t})??We(t)}function Ye(e,t,n){return ft({countryCode:e,line2:t,neighborhood:n})??Ve(t,n)}function rn(e,t){return sn(Ge(e,t))}function We({streetName:e,streetNumber:t}){return[t,e].filter(Boolean).join(" ")}function Ve(e,t){return[e,t].filter(Boolean).join(", ")}function sn(e){return e.split(he).join("")}function an(e){if(!e?.length)return{lineItems:[],itemsDiscountAmount:0,cartLevelDiscountAmount:0};let t=0,n=0;return{lineItems:e.map(o=>{const{itemPrice:r}=o,s=r?{...r,amount:r.amount*o.quantity}:void 0,{lineLevel:a,cartLevel:c}=cn(o.lineAllocations),d=[];n+=c,s&&d.push({type:"subtotal",amount:N(s)}),a!==0&&s&&(t+=a,d.push({type:"items_discount",amount:N({...s,amount:-a})}));const l=s?{...s,amount:s.amount-a}:o.totalPrice;return d.push({type:"total",amount:N(l)}),{id:A(o),...o.parentRelationship?.parent?.stableId?{parent_id:o.parentRelationship.parent.stableId}:{},quantity:o.quantity,item:{id:o.variantId??o.stableId,title:o.title,price:N(r),...o.image?.url?{image_url:o.image.url}:{}},totals:d}}),itemsDiscountAmount:t,cartLevelDiscountAmount:n}}function ye(e){return e?.flatMap(t=>(t.lineComponents.length?t.lineComponents:[t]).filter(n=>n.requiresShipping).map(A))??[]}function dn(e){if(e)return e.reduce((t,n)=>{const{itemPrice:i}=n;if(!i)return t;const o=i.amount*n.quantity;return t?{...t,amount:t.amount+o}:{...i,amount:o}},void 0)}function A(e){return e.stableId}function cn(e){let t=0,n=0;for(const i of e)for(const{discountDetails:o,amount:r}of i.allocations)ln(o.discount)?n+=r.amount:t+=r.amount;return{lineLevel:t,cartLevel:n}}function ln(e){return"presentationLevel"in e&&e.presentationLevel==="CART"}function W(e){return e==="SHIPPING"||e==="LOCAL"||P(e)}function un(e,t,n){return!!(e&&!n&&(t.some(i=>!W(i))||t.some(P)&&t.some(i=>i==="SHIPPING"||i==="LOCAL")))}function pn(e,t,n){return!n||e===t}function J(e,t){switch(t){case"phone_number":return!!e.phoneRequired;case"instructions":return!!e.acceptsInstructions}}function F(e,t){if(!e?.length||!t?.length)return!1;const n=new Set(t),i=e.filter(o=>o.requiresShipping).map(o=>A(o));return i.length===n.size&&i.every(o=>n.has(o))}const se="pickup";function B(e){const t=e.methods.find(({handle:i})=>i===e.selectedDeliveryMethodHandle),n=e.proposedLine?t?.methodType??e.proposedLine.deliveryMethodTypes[0]:(t??e.methods[0])?.methodType;if(n)return P(n)?"pickup":"shipping"}function ze(e){const t=e.filter(r=>B(r)==="pickup"),n=t.map(r=>{const s=new Map;for(const a of r.methods){if(!a.pickupLocation)continue;const c=fn(a.pickupLocation);(!s.has(c)||a.handle===r.selectedDeliveryMethodHandle)&&s.set(c,a)}return s}),i=n[0];if(!i)return[];const o=[];for(const[r,s]of i){const a=[];for(const[c,d]of t.entries()){const l=n[c].get(r);if(!l)break;a.push({line:d,method:l})}a.length===t.length&&o.push({id:s.handle,selections:a})}return o}function fn(e){if(e.type==="PickupPointLocation"&&e.handle)return JSON.stringify([e.type,e.carrierCode||e.carrierName,e.handle]);const{address:t}=e;return JSON.stringify([e.type,e.name??"",t.address1??"",t.address2??"",t.city??"",t.zoneCode??"",t.countryCode??"",t.postalCode?.replace(/\s+/g,"").toUpperCase()??"",t.streetName??"",t.streetNumber??"",t.neighborhood??"",t.district??"",t.subdistrict??"",t.line2??""])}function hn(e,t){const n=new Map;for(const r of e)n.has(r.id)||n.set(r.id,r);const i=[...n.values()],o=t?i.find(({address:r})=>ht(r,t)):void 0;return{destinations:i,selectedDestinationId:o?.id}}function _n(e){const t=yn(e);return t.length?{methods:t}:void 0}function mn(e){if(e?.status!=="filled"||!e.lines)return;let t=0,n;for(const i of e.lines){if(i.status!=="available")continue;const o=i.selectedDeliveryMethodHandle;if(!o)continue;const r=i.methods.find(s=>s.handle===o);r?.cost&&(t+=r.cost.amount,n??=r.cost.currencyCode)}if(n!=null)return{amount:t,currencyCode:n}}const ge=me;function yn(e){const{deliveryNext:t}=e;if(e.readMode!=="proposed"&&(t?.status!=="filled"&&t?.status!=="partial"||!t.lines))return Ne(e);const n=(t?.status==="filled"||t?.status==="partial")&&t.lines?t.lines.filter(Nn):[],o=(e.readMode==="proposed"?Tn(n,e.proposedDeliveryLines,e.merchandiseLines):n).filter(c=>(c.proposedLine?c.proposedLine.deliveryMethodTypes.some(De):c.methods.some(d=>De(d.methodType)))&&c.targetMerchandiseLines?.some(d=>d.requiresShipping));if(e.readMode==="proposed"&&!o.length)return Ne(e);const r=t?.status==="partial"?Xe(e,o):new Map,s=new Set([...gn(o),...r.keys()]),a=[];for(const c of s){const d=o.filter(p=>B(p)===c),l=d.map(p=>In(p,p.proposedLine?[p.proposedLine]:e.proposedDeliveryLines)),u=[...new Set([...l.flatMap(p=>p.line_item_ids),...r.get(c)??[]])];a.push({id:c,type:c,line_item_ids:u,destinations:[],...vn(c,d,e),groups:l})}return a}function Xe(e,t){const n=new Set(t.flatMap(r=>r.targetMerchandiseLines?.map(A)??[])),i=new Map,o=new Set;for(const r of e.merchandiseLines??[]){if(e.readMode!=="proposed"&&!r.requiresShipping)continue;const s=A(r);if(n.has(s)||o.has(s))continue;o.add(s);const a=new Set((r.lineComponents.length?r.lineComponents:[r]).filter(u=>u.requiresShipping&&!n.has(A(u))).map(A));if(!a.size)continue;const c=e.proposedDeliveryLines?.filter(u=>u.targetMerchandiseLines.some(p=>A(p)===s||a.has(A(p)))).flatMap(u=>u.deliveryMethodTypes),d=c?.length&&c.every(P)?"pickup":"shipping",l=i.get(d)??[];l.push(...e.readMode==="proposed"?a:[s]),i.set(d,l)}return i}function Ne(e){return[...Xe(e,[])].map(([n,i])=>({id:n,type:n,line_item_ids:i,destinations:[],...n==="shipping"?Ke(e):{},groups:[]}))}function gn(e){const t=new Set;for(const n of e){const i=B(n);i&&t.add(i)}return Array.from(t)}function De(e){return e==="SHIPPING"||e==="LOCAL"||P(e)}
1function vn(e,t,n){if(e==="shipping")return Ke(n);const i=ze(t);if(!i.length)return{};const o=i.find(({selections:r})=>r.every(({line:s,method:a})=>s.selectedDeliveryMethodHandle===a.handle));return{destinations:i.flatMap(({id:r,selections:s})=>{const a=bn(s[0].method,n.addressContext);return a?[{...a,id:r}]:[]}),...o&&{selected_destination_id:o.id}}}function Ke({savedDestinations:e,shippingAddress:t,addressContext:n}){if(e===void 0)return t&&Be(t)?{destinations:[En(t,n)]}:{};const{destinations:i,selectedDestinationId:o}=hn(e,t);return i.length?{destinations:i.map(({id:r,address:s})=>({id:r,type:"shipping_address",...ge(s,n)})),...o&&{selected_destination_id:o}}:{}}function bn(e,t){const{pickupLocation:n}=e;if(n)return{id:e.handle,type:"business_location",name:n.name??"",pickup_location_address:ge(n.address,t)}}function En(e,t){return{...ge(e,t),id:An(e),type:"shipping_address"}}function An(e){return["shipping",e.countryCode,e.postalCode].filter(Boolean).join("-").replace(/\s+/g,"")}function In(e,t){const n=Je(e),i=Fe(e),o=e.proposedLine?e.selectedDeliveryMethodHandle:i?.handle,r=o?Cn(e,n,t):void 0,s=B(e)==="pickup",a=s?[{...i?Le(i):{totals:[]},id:se,title:"Pickup"}]:e.methods.filter(({methodType:c})=>c==="SHIPPING"||c==="LOCAL").map(Le);return{id:e.id??"",line_item_ids:n,options:a,...o&&{selected_option_id:s?se:o},...r&&{selected_option_details:r}}}function Tn(e,t,n){const i=new Map;for(const o of n??[]){i.set(A(o),ye([o]).length>0);for(const r of o.lineComponents)i.set(A(r),r.requiresShipping)}return(t??[]).map(o=>{const r=o.targetMerchandiseLines.filter(a=>a.requiresShipping).map(a=>A(a)),s=e.find(a=>o.id!==void 0&&a.id===o.id)??e.find(a=>a.type===o.type&&F(a.targetMerchandiseLines,r));return{...s,status:"available",id:o.id,type:o.type,targetMerchandiseLines:o.targetMerchandiseLines.flatMap(a=>{const c=i.get(A(a));return c===void 0?[]:[{...a,requiresShipping:c}]}),selectedDeliveryMethodHandle:o.deliveryMethodHandle,methods:s?.methods.filter(a=>o.deliveryMethodTypes.includes(a.methodType))??[],proposedLine:o}})}function Cn(e,t,n){const i=Sn(e,n,t);if(!i||!e.selectedDeliveryMethodHandle||i.deliveryMethodHandle!==e.selectedDeliveryMethodHandle)return;const o=i.deliveryMethodOptions;if(!o)return;const r=Fe(e),s=r&&!J(r,"phone_number")?void 0:o.phone,a=r&&!J(r,"instructions")?void 0:o.instructions;if(!(s===void 0&&a===void 0))return{...s!==void 0&&{phone_number:s},...a!==void 0&&{instructions:a}}}function Sn(e,t,n=Je(e)){return t?.find(i=>!!e.id&&i.id===e.id)??t?.find(i=>F(i.targetMerchandiseLines,n))}function Je(e){return e.targetMerchandiseLines?.filter(t=>t.requiresShipping).map(t=>A(t))??[]}function Le(e){return{id:e.handle,title:e.title,...e.description&&{description:{plain:e.description}},...e.carrierName&&{carrier:e.carrierName},...e.minDeliveryDateTime&&{earliest_fulfillment_time:e.minDeliveryDateTime},...e.maxDeliveryDateTime&&{latest_fulfillment_time:e.maxDeliveryDateTime},totals:[{type:"fulfillment",display_text:P(e.methodType)?"Pickup":"Shipping",amount:N(e.costAfterDiscounts)}]}}function Nn(e){return e.status==="available"}const Dn=new Map([["terms-of-service","terms_of_service"],["privacy-policy","privacy_policy"],["refund-policy","refund_policy"],["shipping-policy","shipping_policy"]]);function Ln(e){const t=[];for(const{handle:n,url:i}of e){const o=Dn.get(n);o&&t.push({type:o,url:i})}return t}function wn(e){if(e?.status!=="processed")return;const t=e.orderIdentity.buyerIdentifier,n=_t(e.orderIdentity.id);return{...n?{id:mt("Order",n)}:{},...t?{label:t}:{},permalink_url:e.confirmationPage.url}}function kn(e,t){return{instruments:e?[{billing_address:me(e,t)}]:[]}}const Pn={DELIVERY_NO_DELIVERY_STRATEGY_AVAILABLE_FOR_MERCHANDISE_LINE:"address_undeliverable",DELIVERY_OUT_OF_STOCK_AT_ORIGIN_LOCATION:"out_of_stock",DELIVERY_ZONE_NOT_FOUND:"address_undeliverable",DELIVERY_ZONE_REQUIRED_FOR_COUNTRY:"address_undeliverable",DISCOUNTS_ADDITIONAL_REQUESTED_DISCOUNT_CODE_DISCARDED:"discount_code_not_applied",DISCOUNTS_ALLOCATIONS_MISMATCH:"discount_changed",DISCOUNTS_CURRENTLY_INACTIVE:"discount_code_expired",DISCOUNTS_CUSTOMER_NOT_ELIGIBLE:"discount_code_user_ineligible",DISCOUNTS_CUSTOMER_USAGE_LIMIT_REACHED:"discount_code_user_ineligible",DISCOUNTS_CUSTOM_DISCOUNT_NOT_HONOURED:"discount_code_rejected",DISCOUNTS_DISCOUNTS_NOT_ALLOWED_FOR_B2B:"discount_code_rejected",DISCOUNTS_DISCOUNT_ALREADY_APPLIED:"discount_code_already_applied",DISCOUNTS_DISCOUNT_CODE_APPLICATION_FAILED:"discount_code_rejected",DISCOUNTS_DISCOUNT_CODE_NOT_HONOURED:"discount_code_rejected",DISCOUNTS_DISCOUNT_TITLE_TOO_LONG:"checkout_warning",DISCOUNTS_ELIGIBLE_CUSTOMER_MISSING:"discount_code_user_ineligible",DISCOUNTS_HIGHER_VALUE_DISCOUNT_APPLIED:"discount_code_not_applied",DISCOUNTS_INCOMPATIBLE_PURCHASE_TYPE:"discount_code_combination_disallowed",DISCOUNTS_INCOMPATIBLE_SCRIPT_DISCOUNT:"discount_code_combination_disallowed",DISCOUNTS_INVALID_SIGNATURE:"checkout_warning",DISCOUNTS_MAXIMUM_DISCOUNT_CODE_LIMIT_REACHED:"discount_code_rejected",DISCOUNTS_MIXED_DESTINATION_COUNTRIES:"discount_code_rejected",DISCOUNTS_NOT_FOUND:"discount_code_invalid",DISCOUNTS_NO_ENTITLED_LINE_ITEMS:"discount_code_rejected",DISCOUNTS_NO_ENTITLED_SHIPPING_LINES:"discount_code_rejected",DISCOUNTS_ONLY_EMPTY_TERMS_ACCEPTED:"checkout_warning",DISCOUNTS_PURCHASE_NOT_IN_RANGE:"discount_code_rejected",DISCOUNTS_QUANTITY_NOT_IN_RANGE:"discount_code_rejected",DISCOUNTS_UNSUPPORTED_EXPECTATION:"checkout_warning",DISCOUNTS_USAG
1E_LIMIT_REACHED:"discount_code_rejected",MERCHANDISE_INVENTORY_NOT_FOUND:"out_of_stock",MERCHANDISE_NOT_APPLICABLE:"item_unavailable",MERCHANDISE_NOT_ENOUGH_STOCK_AVAILABLE:"out_of_stock",MERCHANDISE_NOT_FOUND:"item_unavailable",MERCHANDISE_OUT_OF_STOCK:"out_of_stock",MERCHANDISE_OUT_OF_STOCK_IN_CONTEXT:"out_of_stock",MERCHANDISE_PRODUCT_NOT_PUBLISHED:"item_unavailable",MERCHANDISE_PRODUCT_NOT_PUBLISHED_IN_BUYER_LOCATION:"item_unavailable",MERCHANDISE_PRODUCT_VARIANT_NOT_FOUND:"item_unavailable",PAYMENTS_CREDIT_CARD_BASE_EXPIRED:"payment_failed",PAYMENTS_CREDIT_CARD_BASE_GATEWAY_NOT_SUPPORTED:"payment_failed",PAYMENTS_CREDIT_CARD_GENERIC:"payment_failed",PAYMENTS_CREDIT_CARD_YEAR_EXPIRED:"payment_failed",PAYMENTS_PAYMENT_METHOD_INCOMPATIBLE_WITH_PAYMENT_TERMS:"payment_failed",PAYMENTS_PROPOSED_GATEWAY_UNAVAILABLE:"payment_failed"};function Mn(e){return Pn[e]}const Rn=new Set(["AcceptNewTermViolation","RequiredArtifactsUnavailableViolation"]),On=new Set(["PendingTermViolation"]),Un=new Set(["PAYMENTS_UNACCEPTABLE_PAYMENT_AMOUNT"]),xn={type:"error",severity:"requires_buyer_review",code:"buyer_review_required",content:"The buyer must review the order on the checkout page. After the buyer authorizes submission, call complete_checkout again to submit."};function Hn(e){const{receipt:t,isShippingRequired:n,hasShippingAddress:i,deliveryNext:o,skipsShippingAddress:r=yt(o)}=e,s=qn(e),a=Bn({receipt:t,isShippingRequired:n,hasShippingAddress:i,skipsShippingAddress:r,requiresBuyerReview:e.requiresBuyerReview??!1,requiresCaptcha:e.requiresCaptcha??!1});return a==="incomplete"&&e.requiresCaptcha&&t?.status!=="action_required"&&s.push({type:"error",severity:"requires_buyer_input",code:"buyer_action_required",content:"The buyer must complete the CAPTCHA on the checkout page. After the buyer completes it, call get_checkout before retrying complete_checkout. Do not attempt to solve the CAPTCHA on the buyer's behalf."}),a==="requires_escalation"&&s.push(xn),{status:a,messages:s}}function qn(e){const t=[];for(const n of e.violations??[]){if(Rn.has(n.__typename)||Un.has(n.code)||e.requiresCaptcha&&gt.has(n.code))continue;const i=n.code.startsWith("DISCOUNTS_"),o=i||On.has(n.__typename),r=Mn(n.code)??(o?"checkout_warning":"checkout_error"),s="target"in n?n.target:void 0,a=i?"$.discounts.codes":s;t.push({...o?{type:"warning"}:{type:"error",severity:"recoverable"},code:r,content:Fn(n,r,e.i18n),...a?{path:a}:{}})}return e.receipt?.status==="action_required"&&t.push({type:"error",severity:"requires_buyer_input",code:"buyer_action_required",content:"Payment requires buyer action. Ask the buyer to complete the payment challenge on the checkout page, then call get_checkout. Do not resubmit checkout."}),t}function Fn(e,t,n){if(e.localizedMessage)return e.localizedMessage;switch(t){case"address_undeliverable":return n.translate("shipping_errors.shipping_method_not_available_generic.one");case"checkout_error":case"checkout_warning":case"discount_changed":case"discount_code_already_applied":case"discount_code_combination_disallowed":case"discount_code_expired":case"discount_code_invalid":case"discount_code_not_applied":case"discount_code_rejected":case"discount_code_user_ineligible":return n.translate("notice_banner.generic_processing_error.title");case"item_unavailable":case"out_of_stock":return n.translate("ucp.standard_errors.item_unavailable");case"payment_failed":return n.translate("payment_errors.generic_error")}}function Bn({receipt:e,isShippingRequired:t,hasShippingAddress:n,skipsShippingAddress:i,requiresBuyerReview:o,requiresCaptcha:r}){const s=e?.status;return s==="processed"?"completed":s==="processing"||s==="processing_remote_checkouts"||s==="polling_for_order"?"complete_in_progress":s==="action_required"||r?"incomplete":o?"requires_escalation":t&&!n&&!i?"incomplete":"ready_for_complete"}function jn({subtotal:e,itemsDiscountAmount:t,cartLevelDiscountAmount:n,discountLines:i,fulfillmentTotal:o,tax:r,duty:s,dutiesIncluded:a,runningTotal:c}){const d=[];return e!=null&&(d.push({type:"subtotal",display_text:"Subtotal",amount:N(e)}),d.push(...$n({currencyCode:e.currencyCode,discountLines:i,itemsDiscountAmount:t,cartLevelDiscountAmount:n}))),o!=null&&d.push({type:"fulfillment",display_text:"Shipping",amount:N(o)}),s!=null&&!a&&d.push({type:"duty",display_text:"Duties",amount:N(s)}),r!=null&&d.push({type:"tax",display_text:"Taxes",amount:N(r)}),c!=null&&d.push({type:"total",display_text:"Total",amount:N(c)}),d}function $n({currencyCode:e,discountLines:t,itemsDiscountAmount:n,cartLevelDiscountAmount:i}){let o=i;for(const s of t?.lines??[])if(vt(s))for(const a of s.allocations)a.target.type==="DELIVERYLINE"&&(o+=a.target.amount.amount);const r=[];return n>0&&r.push({type:"items_discount",display_text:"Discounts",amount:N({amount:-n,currencyCode:e})}),o>0&&r.push({type:"discount",display_text:"Discount",amount:N({amount:-o,currencyCode:e})}),r}function Gn(e){const t=e.merchandiseLines?.lines;if(!t||!Wn(t)||e.runningTotal==null)return;const n=e.readMode==="proposed"&&t.length===0?{...e.runningTotal,amount:0}:dn(t)??e.subtotal;if(n==null)return;const{lineItems:i,itemsDiscountAmount:o,cartLevelDiscountAmount:r}=an(t),s=mn(e.deliveryNext),a=e.receipt?.status==="processed"&&e.receipt.isRedacted?void 0:Wt(e.contactInfo),c=Vt(e.discountLines,e.readMode==="proposed"?i:void 0),d=_n({readMode:e.readMode,deliveryNext:e.deliveryNext,shippingAddress:e.shippingAddress,merchandiseLines:t,savedDestinations:e.savedDestinations,addressContext:e.addressContext,proposedDeliveryLines:e.proposedDeliveryLines}),{status:l,messages:u}=Hn({i18n:e.i18n,requiresBuyerReview:e.buyerReviewUrl!=null,requiresCaptcha:e.requiresCaptcha,violations:e.violations,receipt:e.receipt,isShippingRequired:e.readMode==="proposed"?ye(t).length>0:e.isShippingRequired,hasShippingAddress:e.readMode==="proposed"?Be(e.shippingAddress):e.shippingAddress!=null,deliveryNext:e.deliveryNext,skipsShippingAddress:e.readMode==="proposed"?Yn(d,t):void 0}),p=wn(e.receipt);return{...e.id?{id:e.id}:{},...e.continueUrl?{continue_url:e.continueUrl}:{},currency:e.runningTotal.currencyCode,status:l,...l==="requires_escalation"&&e.buyerReviewUrl?{continue_url:e.buyerReviewUrl}:{},links:Ln(e.merchantPolicies),line_items:i,payment:kn(e.billingAddress,e.addressContext),totals:jn({subtotal:n,itemsDiscountAmount:o,cartLevelDiscountAmount:r,discountLines:e.discountLines,fulfillmentTotal:s,tax:e.tax,duty:e.duty,dutiesIncluded:e.dutiesIncluded,runningTotal:e.runningTotal}),...a&&{buyer:a},...c&&{discounts:c},...d&&{fulfillment:d},...u.length?{messages:u}:{},...p&&{order:p}}}function Yn(e,t){const n=new Set(e?.methods.filter(i=>i.type==="pickup").flatMap(i=>(i.groups??[]).filter(o=>!!o.selected_option_id).flatMap(o=>o.line_item_ids))??[]);return t.every(i=>n.has(A(i))||ye([i]).every(o=>n.has(o)))}function Wn(e){return e.every(t=>t.itemPrice!=null&&t.title!=null)}function ve({checkout:e,i18n:t,shop:n,router:i,readMode:o="negotiated",declaredFields:r=new Map,paymentInstrument:s}){const a=Gn(zn(e,t,n,o,i));if(!a)return;const c=Gt(r),d={...a,...s?{payment:{instruments:[Vn(s,e,a.payment.instruments[0]?.billing_address??{})]}}:{},...c.length>0?{declared_fields:c}:{}},l=e.proposal.proposed.locationAddress.value;return d.fulfillment?.methods.length!==1||d.fulfillment.methods[0].type!=="pickup"||!l?.countryCode||!l.postalCode||!l.coordinates?d:{...d,context:{address_country:l.countryCode,...l.zoneCode&&{address_regi
1on:l.zoneCode},postal_code:l.postalCode}}}function Vn(e,t,n){const i=t.proposal.proposed.paymentLines.value[0]?.method.type;return{id:e.id,handler_id:e.handler_id,type:e.type,...e.credential?{credential:{type:e.credential.type}}:{},selected:e.handler_id==="shopify.card"?i==="direct":i==="shopWallet",billing_address:n}}function zn(e,t,n,i,o){const{proposed:r,negotiated:s}=e.proposal,a=e.addressManager.shipping.value,c=e.identity.current.value==="shopPay"?a:void 0,d=c?[...c.addresses.value,...c.immutableAddresses.value]:void 0,l=s.fields.shippingAddress.value,u=o?.currentUrl.value,p=r.captcha.value;return{i18n:t,readMode:i,requiresCaptcha:!!(p?.provider==="hcaptcha"&&p.sitekey&&(!p.token||p.violationCode)),buyerReviewUrl:u?.normalizedPath==="/review"?u.href:void 0,id:s.fields.ucp.value?.id,continueUrl:s.fields.ucp.value?.continueUrl,merchantPolicies:n.merchantPolicies,merchandiseLines:i==="proposed"?{lines:r.merchandiseLines.value}:s.fields.merchandiseLines.value,subtotal:s.fields.subtotal.value,discountLines:i==="proposed"?{lines:r.discountLines.value}:s.fields.discountLines.value,tax:e.proposal.facts.tax??Jn(s.fields.taxes.value),duty:e.proposal.facts.duty??Qn(s.fields.duties.value),dutiesIncluded:!!s.fields.dutiesIncluded.value||!!e.proposal.facts.dutiesIncluded,runningTotal:s.fields.runningTotal.value,contactInfo:i==="proposed"?{email:r.email.value,phone:r.phone.value}:s.fields.contactInfo.value,deliveryNext:s.fields.deliveryNext.value,shippingAddress:i==="proposed"?r.shippingAddress.value:l,billingAddress:Xn(e,n,i),addressContext:e.address,savedDestinations:d,proposedDeliveryLines:r.deliveryLines.value.map(m=>m.value),isShippingRequired:!!s.fields.isShippingRequired.value,violations:s.fields.allViolations.value,receipt:e.latestReceipt.value}}function Xn(e,t,n){const i=e.latestReceipt.value;if(i?.status==="processed")return i.purchaseOrder.billingAddress;if(!(i?.status==="processing"||i?.status==="processing_remote_checkouts"||i?.status==="polling_for_order"))return n==="proposed"?Kn(e,t):e.proposal.negotiated.fields.billingAddress.value}function Kn(e,t){const{proposed:n,negotiated:i,facts:o}=e.proposal,r=n.paymentLines.value;for(const{method:d}of r)if(d.type===X.CreditCard||d.type===X.PayPal)return d.billingAddress;const s=n.billingAddress.value,a=!s.address1&&o.billingAddress?o.billingAddress:s;if(n.billingAddressOption.value!=="shipping"||!i.fields.isShippingRequired.value||!bt(r))return a;const c=r[0]?.method;if(c?.type==="wallet"){const d=i.fields.runningTotal.value,l=d&&d.amount<=0,u=Et(i.fields.merchandiseLines.value?.lines).some(m=>!!m.sellingPlan?.subscriptionDetails);if((!l||u||i.fields.deferredTotal.value?.amount.amount)&&(c.name==="GOOGLE_PAY"||c.name==="APPLE_PAY"||c.name==="PAYPAL_EXPRESS"&&Pt({checkout:e,shop:t,paymentMethods:i.fields.paymentMethods.value})))return a}return o.delivery?.[0]?.deliveryAddress??n.shippingAddress.value}function Jn(e){return e?.status==="available_total"?e.totalTax:void 0}function Qn(e){return e?.status==="available_total"?e.totalDuty:void 0}function Z(e,{checkout:t},n){const i=e.fulfillmentMethods.methods;if(i.length>1)return k("At most one fulfillment method is supported.");const o=i[0];if(o?.id!==void 0&&o.id!==o.type)return k("Method id must match its shipping or pickup type; omit id when requesting a new method.");const{proposed:r,negotiated:s}=t.proposal,a=r.deliveryLines.value.map(f=>f.value),c=_e(r.merchandiseLines.value,a),d=re(a,c);if(d.some(P)&&d.some(ee)){const f=s.fields.deliveryNext.value,v=f?.status==="filled"||f?.status==="partial"?f.lines.filter(y=>y.status==="available"):[],T=a.map(y=>{const L=(v.find(({id:g})=>!!y.id&&g===y.id)??v.find(g=>F(g.targetMerchandiseLines,y.targetMerchandiseLines.filter(R=>R.requiresShipping).map(A))))?.methods.find(({handle:g,methodType:R})=>g===y.deliveryMethodHandle&&y.deliveryMethodTypes.includes(R))?.methodType??(y.deliveryMethodHandle?void 0:y.deliveryMethodTypes[0]);return L?{...y,deliveryMethodTypes:[L]}:y}),h=re(T,c);if(h.some(P)&&h.some(ee))return k("Updates to checkouts with both shipping and pickup are not supported. Ask the buyer to continue in checkout.")}if(!i.length&&!e.context)return;const l=o?.type??(d.length&&d.every(P)?"pickup":void 0),u=!!(e.context&&!ae(r.locationAddress.value,e.context));if(u&&l!=="pickup")return k("Changing context locality requires a pickup method.");if(!o&&l!=="pickup")return;const p=f=>l==="pickup"?P(f):ee(f);if(o&&(o.selected_destination_id!==void 0||o.groups.length))return u||d.length&&!d.some(p)?k("Change the method/search origin first, then select a destination or option returned by that update."):void 0;if(l==="pickup"&&d.length&&d.every(f=>f==="PICKUP_POINT"))return u?k("Pickup-point locality discovery is not supported. Select an existing destination instead."):void 0;if(!c.size)return k("This checkout has no physical items to fulfill.");if(l==="pickup"&&e.context){const f=r.shippingAddress.value?.countryCode||r.locationAddress.value?.countryCode;if(!f)return k("Pickup search requires an established checkout country. Ask the buyer to choose a country in checkout.");if(e.context.address_country!==f)return k("Pickup search must remain in the checkout country.")}if(!n&&!u&&d.every(p)&&d.length)return;const m=!d.length||!d.every(p);if(!n&&m)return k("The delivery selector is not ready.");
1const I=n?n.getAvailableMethodTypes().find(f=>l==="pickup"?f.includes("PICK_UP"):f.some(p)):d;if(!I)return k(`The checkout does not offer ${l}.`);const E=s.fields;return(m||u)&&(E.mustSelectProvidedShippingRate.value||E.mustSelectProvidedAddress.value||E.canUpdateDeliveryAddress.value===!1)?k("The checkout locks its delivery method or address."):{methodTypes:I,needsLocalityLookup:u,changesMode:m}}function ee(e){return e==="SHIPPING"||e==="LOCAL"}function ae(e,t){return Ot(e,{countryCode:t.address_country,zoneCode:t.address_region,postalCode:t.postal_code})}function k(e){return{error:{code:"rejected",message:`fulfillment: ${e} Nothing was applied. Call get_checkout before retrying.`}}}const V="Unable to confirm the checkout update. Call get_checkout to review the checkout and its messages. Do not retry if the requested change is already present. Otherwise, build a complete replacement from the latest checkout, change only the requested values, and resend all other buyer, fulfillment, discount-code, and declared-field values to retain them. Do not attempt to update the checkout by interacting with the page.",H={status:"written"};function Zn(e){return e.paymentLines.value.some(t=>t.method.type===X.CreditCard||t.method.type===X.PayPal||ei(t))}function ei(e){if(e.method.type!=="wallet")return!1;switch(e.method.name){case"APPLE_PAY":return Lt(e);case"GOOGLE_PAY":return Dt(e);case"PAYPAL_EXPRESS":return Nt(e);default:return!1}}const ti=({buyer:e},{checkout:t,shopPay:n})=>{const i=Rt({identity:t.identity,proposal:t.proposal,shopPay:n});if(i&&t.identity.current.value==="shopPay")return;const{proposed:o}=t.proposal;return{status:"ready",negotiation:{include:["contactInfo"],loading:["contactInfo"],fieldsToResolve:["contactInfo"]},async apply(){return i||(o.email.value=e.email),o.phone.value=e.phone_number,H}}},Qe=({shippingAddress:e},t)=>{if("saved_address_id"in e)return ni(e.saved_address_id,t);const{checkout:n,observability:i,clearShippingAddressErrors:o}=t,r=n.addressManager.shipping.value;if(r.applyAddressChangeBlockReason("ucp").value)return;const a=K(e,n.address);return{status:"ready",negotiation:{include:["shippingAddress","deliveryNext"],loading:["deliveryNext"],fieldsToResolve:["shippingAddress","deliveryNext"]},async apply(){const c=await r.applyAddressChange({source:"ucp",address:a});return c.type!=="success"?(i.log("web_mcp_address_change_declined","[WebMcp] address manager declined an admitted address",{reason:c.reason}),{status:"failed"}):(o(),H)}}};function ni(e,t){const{checkout:n,clearShippingAddressErrors:i}=t;if(n.identity.current.value!=="shopPay")return{status:"rejected",field:"shippingAddress"};const o=n.addressManager.shipping.value,r=[...o.addresses.value,...o.immutableAddresses.value].find(a=>a.id===e);if(!r||r.disabled)return{status:"rejected",field:"shippingAddress"};const s=o.applyAddressChangeBlockReason("ucp").value;if(!(s&&s!=="MUST_SELECT_PROVIDED_ADDRESS"))return{status:"ready",negotiation:{include:["shippingAddress","deliveryNext"],loading:["deliveryNext"],fieldsToResolve:["shippingAddress","deliveryNext"]},async apply(){return await o.selectAddress(e)?(i(),H):{status:"failed"}}}}function de({fulfillmentMethods:e},{checkout:t},n=!1){const{proposed:i,negotiated:o}=t.proposal,r=o.fields.deliveryNext.peek(),s=r?.status==="filled"||r?.status==="partial"?r.lines.filter(mi):[],a=new Map;for(const d of i.deliveryLines.peek()){const{id:l,targetMerchandiseLines:u,deliveryMethodTypes:p,deliveryMethodHandle:m}=d.peek();if(p.filter(W).length===0)continue;const f=(s.find(v=>!!l&&v.id===l)??s.find(v=>F(v.targetMerchandiseLines,u.filter(T=>T.requiresShipping).map(A))))?.methods.find(v=>v.handle===m);if(f){if(!W(f.methodType))continue}else if(un(m,p,f))return{status:"rejected",field:"fulfillmentMethods"};a.set(d,{deliveryLine:d,selectedOptionId:void 0,selectedOptionDetails:void 0})}try{for(const d of pi(e,i.deliveryLines.peek(),s))a.set(d.deliveryLine,d)}catch(d){if(!(d instanceof M))throw d;return{status:"rejected",field:"fulfillmentMethods",reason:d.reason}}const c=o.fields.mustSelectProvidedShippingRate.peek();return[...a.values()].some(({deliveryLine:d,selectedOptionId:l})=>!pn(d.peek().deliveryMethodHandle,l,c))?{status:"rejected",field:"fulfillmentMethods"}:{status:"ready",negotiation:{include:["deliveryNext"],loading:["deliveryNext"],fieldsToResolve:["deliveryNext"]},async apply(){for(const d of i.deliveryLines.value){const l=a.get(d);if(!l&&(!n||!d.value.deliveryMethodTypes.some(W)))continue;
1const{selectedOptionId:u,selectedOptionDetails:p}=l??{};d.value={...d.peek(),deliveryMethodHandle:u,deliveryMethodOptions:_i(p),...u===void 0&&{isCustomRate:void 0,customDeliveryStrategy:void 0}}}return H}}}const ii=({discountCodes:e=[]},t)=>{const{checkout:n,source:i}=t,{proposed:o,negotiated:r}=n.proposal,s=new Map,a=[];for(const c of o.discountLines.value){const{discount:d}=c;if(d.type==="code"||d.type==="discountCodeTrigger"){const l=d.title.toUpperCase(),u=s.get(l);u?u.push(c):s.set(l,[c])}else a.push(c)}if(r.fields.canUpdateDiscountCodes.value===!1||i.type==="orderEdit"||i.type==="paymentCollection"){const c=new Set(e.map(l=>l.toUpperCase()));return c.size===s.size&&[...c].every(l=>s.has(l))?void 0:{status:"rejected",field:"discountCodes"}}return{status:"ready",negotiation:{include:["discountLines","deliveryNext"],loading:["discountLines","deliveryNext"],fieldsToResolve:["discountLines","totalSavings","merchandiseLines","deliveryNext"]},async apply(){const c=new Set;for(const d of e){const l=d.toUpperCase();if(c.has(l))continue;c.add(l);const u=s.get(l);u?a.push(...u):a.push({title:d,discount:{type:"discountCodeTrigger",title:d}})}return x(()=>{o.discountLines.value=a,o.reduction.value=void 0;const{discountCodeWarningSignal:d,currentDiscountCodeAttemptSignal:l}=t.negotiator.context;d.value=null,l.value=null}),H}}},oi=[ti,ii,Qe,de];function we(e,t,{fulfillmentRequest:n,fulfillment:i,locationAddress:o}={}){const r=[];for(const s of oi){if(s===Qe&&n){const{methodTypes:c}=n,{proposed:d}=t.checkout.proposal;r.push({status:"ready",negotiation:{include:["deliveryNext"],loading:["deliveryNext"],fieldsToResolve:["deliveryNext"]},async apply(){return i?i.setDesiredMethod(c,o):o&&(d.locationAddress.value=o),H}})}const a=s===de?de(e,t,n!==void 0):s(e,t);if(a!==void 0){if(a.status==="rejected")return ui(a.field,a.reason);r.push(a)}}return r}class Ze{#e;constructor(t){this.#e=t}writePayment({payment:t,billingAddress:n=t?.billing_address,applyBilling:i=!0}){const o=i?this.#t(n):void 0,r=this.#n(t);return r&&"error"in r?r:(x(()=>{r?.apply(),o?.apply()}),{status:"applied"})}#t(t){const{checkout:n}=this.#e;if(!O(n))return;const i=t===void 0?void 0:K(t,n.address);return{apply({replacement:o=!1}={}){if(!O(n))return!1;const{proposed:r,negotiated:s,facts:a}=n.proposal,c=s.fields.isShippingRequired.value===!1;if(i&&!At(i)&&(c||!li(i,n)))return x(()=>{r.billingAddress.value=i,r.billingAddressOption.value="custom"}),!0;if(o&&c)return a.billingAddress||Zn(r)?!1:(x(()=>{r.billingAddress.value=K({address_country:r.billingAddress.value.countryCode},n.address),r.billingAddressOption.value="custom"}),!0);const d=r.billingAddressOption.value;return r.billingAddressOption.value="shipping",i!==void 0||d!=="shipping"}}}#n(t){const{checkout:n,shop:i,paymentInstrument:o}=this.#e;if(!O(n)||!t&&!o.value)return;const{proposed:r,negotiated:s}=n.proposal,a=s.fields.paymentMethods.value,c=r.paymentLines.value.find(l=>!l.due&&l.method.type==="direct"),d=It(a??[],c?.method.type==="direct"&&!!c.method.alternative);return t&&(t.handler_id==="shopify.card"?!d:!i.hasFlagEnabled(Tt)||!Ct(a))?di():{apply(){O(n)&&x(()=>{const l=o.value;if(l?.handler_id==="shop_pay"&&l.credential?.approval_id&&(r.paymentLines.value=r.paymentLines.value.map(u=>u.method.type==="shopWallet"&&u.method.shopPayApprovalId===l.credential?.approval_id?{...u,method:{...u.method,shopPayApprovalId:void 0}}:u)),o.value=t,!!t){t.handler_id==="shopify.card"&&t.credential?.token&&d?(c?.method.type!=="direct"||c.method.paymentMethodIdentifier!==d.paymentMethodIdentifier)&&(r.paymentLines.value=Ee(r.paymentLines.value,{method:{type:"direct",paymentMethodIdentifier:d.paymentMethodIdentifier,alternative:d.alternative}},Ae(i))):t.handler_id==="shop_pay"&&t.credential?.approval_id&&(r.paymentLines.value=Ee(r.paymentLines.value,{method:{type:"shopWallet",shopPayApprovalId:t.credential.approval_id}},Ae(i)));for(const u of Object.values(r.directPaymentErrors))u.value=void 0;r.generalPaymentError.value=void 0,r.generalPaymentErrorCode.value=void 0}})}}}async applyUpdate(t,{isExpired:n}={}){const{shippingAddress:i}=t;if(await this.loadAddressMetadata(["saved_address_id"in i?void 0:i,O(this.#e.checkout)?t.payment?.billing_address:void 0]),n?.())return C();if(this.#e.isSubmitting.value)return j();let o=G(t.declaredFields,this.#e.declaredFields);if("error"in o)return o;if(o.some(({changed:h})=>h)){if(await this.#e.waitForPendingNegotiations(),n?.())return C();if(this.#e.isSubmitting.value)return j();if(o=G(t.declaredFields,this.#e.declaredFields),"error"in o)return o}let r=this.#e.getFulfillmentController?.(),s=Z(t,this.#e,r);
1if(s&&"error"in s)return s;let a;if(s?.needsLocalityLookup&&t.context){try{const h=this.#e.resolvePickupLocality;if(!h)throw new te;a=await h(t.context)}catch(h){return this.#e.observability.error(h instanceof te?h:new te(h)),n?.()?C():{error:{code:"update_failed",message:"context: Pickup locality lookup is unavailable. Nothing was applied. Call get_checkout and retry with the latest checkout. Do not attempt to update the checkout by interacting with the page."}}}if(n?.())return C();if(!a)return{error:{code:"rejected",message:"context: Could not resolve a unique postal locality. Nothing was applied. Check address_country, address_region and postal_code, then retry."}};if(o=G(t.declaredFields,this.#e.declaredFields),"error"in o)return o}if(t.context){const h=this.#e.checkout.proposal.proposed.locationAddress.value;ae(h,t.context)&&(a=h)}if(r=this.#e.getFulfillmentController?.(),s=Z(t,this.#e,r),s&&"error"in s)return s;let c=this.#t(t.payment?.billing_address);const d=t.payment&&"handler_id"in t.payment?t.payment:void 0;let l=this.#n(d);if(l&&"error"in l)return l;let u=we(t,this.#e,{fulfillmentRequest:s,fulfillment:r,locationAddress:a});if("error"in u)return u;if(n?.())return C();const p=[];let m=!1;for(const h of["negotiate","stage"]){if(h==="stage"&&m&&(o=G(t.declaredFields,this.#e.declaredFields),"error"in o))return C();for(const y of o)if(!(y.phase!==h||!y.changed)){if(n?.())return C();try{if(!await y.apply()||n?.())return C()}catch{return C()}if(y.phase==="stage")p.push(y.negotiation);else if(m=!0,r=this.#e.getFulfillmentController?.(),s=Z(t,this.#e,r),s&&"error"in s||(u=we(t,this.#e,{fulfillmentRequest:s,fulfillment:r,locationAddress:a}),"error"in u)||(c=this.#t(t.payment?.billing_address),l=this.#n(d),l&&"error"in l))return C()}}if(l){const h=l;u.push({status:"ready",negotiation:{include:["paymentLines"],loading:["paymentLines"],fieldsToResolve:["paymentLines"]},async apply(){return h.apply(),H}})}if(u.length===0&&p.length===0&&!c)return{status:"applied"};if(n?.())return C();if(this.#e.isSubmitting.value)return j();if((await Promise.all(x(()=>u.map(h=>h.apply())))).find(h=>h.status==="failed")||n?.())return C();if(this.#e.isSubmitting.value)return j();const f=c?.apply({replacement:!0})??!1;if(u.length===0&&p.length===0&&!f)return{status:"applied"};const v=await this.#i(si([...u.map(h=>h.negotiation),...p,...f?[{include:["billingAddress"],loading:["billingAddress"],fieldsToResolve:["billingAddress"]}]:[]]));await this.#e.waitForPendingNegotiations();const T=ai(v);if(!("error"in T)&&!n?.()&&s?.needsLocalityLookup&&a&&t.context&&ae(this.#e.checkout.proposal.proposed.locationAddress.value,t.context)){const{proposed:h}=this.#e.checkout.proposal,y=h.deliveryLines.value.map(L=>L.value),w=_e(h.merchandiseLines.value,y),b=re(y,w);b.length&&b.every(P)&&this.#e.announcePickupLocality?.(a)}return n?.()?C():T}async loadAddressMetadata(t){const n=new Set;for(const o of t){const r=o?.address_country?.toUpperCase();o&&r&&ri(r,o)&&n.add(r)}const{countryDetails:i}=this.#e.checkout.address;for(const o of n){const r=i.get(o);(!r||r.isFallback)&&await i.fetch(o)}}async#i(t){let n;return await this.#e.journey.negotiate({...t,runListenersOnError:t.include.includes("shippingAddress")||t.include.includes("discountLines"),onComplete:i=>{n=i}}),n}}class te extends Error{constructor(t){super("WebMCP pickup locality lookup failed",{cause:t}),this.name="WebMcpLocalityLookupError"}}function ri(e,t){const n=!!(t.street_address||t.street_name||t.street_number),i=!!(t.extended_address||t.district),o=pe(e,"")!==null,r=fe(e,"")!==null;return n&&o||i&&r}function si(e){return{include:ne(e,"include"),loading:ne(e,"loading"),fieldsToResolve:ne(e,"fieldsToResolve")}}function ne(e,t){return[...new Set(e.flatMap(n=>n[t]))]}function ai(e){return e?.status==="success"||e?.status==="error"?{status:"applied"}:C()}function j(){return{error:{code:"completion_in_progress",message:"A credentialed completion is in progress. Wait for it to finish before updating payment."}}}function di(){return{error:{code:"invalid_request",message:"This checkout does not accept the supplied payment handler. Call get_checkout for the current checkout state."}}}function C(){return{error:{code:"update_failed",message:V}}}const ci={context:"context",buyer:"buyer",discountCodes:"discounts",declaredFields:"declared_fields",shippingAddress:"fulfillment",fulfillmentMethods:"fulfillment",payment:"payment"};function li(e,t){const n=me(t.proposal.proposed.shippingAddress.value,t.address);return St(e,K(n,t.address))}function ui(e,t){if(t==="unsupported_option_instructions"||t==="unsupported_option_phone"){const n=t==="unsupported_option_instructions"?"instructions":"phone_number";return{error:{code:"rejected",message:`The selected delivery option does not support selected_option_details.${n}. Nothing was applied. Remove ${n} from selected_option_details or choose an option that supports it, then retry. Do not attempt to update the checkout by interacting with the page.`}}}return{error:{code:"update_failed",message:`Unable to update ${ci[e]}. Call get_checkout to review the checkout and its messages before retrying. Do not attempt to update the checkout by interacting with the page.`}}}
1class M extends Error{constructor(t){super(t),this.name="WebMcpFulfillmentMethodUpdateError",this.reason=t}}function pi(e,t,n){return e.methods.flatMap(i=>i.type==="pickup"?fi(i,t,n):i.groups.map(o=>{const r=et(o,n),s=r.methods.find(({handle:a,methodType:c})=>a===o.selected_option_id&&(c==="SHIPPING"||c==="LOCAL"));if(!s||B(r)!=="shipping")throw new M("unknown_fulfillment_option");return ce(r,s,o.selected_option_details,t)}))}function fi(e,t,n){const i=e.selected_destination_id===void 0?void 0:ze(n).find(({id:r})=>r===e.selected_destination_id);if(e.selected_destination_id!==void 0&&!i)throw new M("unknown_pickup_destination");const o=new Map;for(const r of e.groups){if(r.selected_option_id!==se)throw new M("unknown_fulfillment_option");const s=et(r,n);if(B(s)!=="pickup"||i&&!i.selections.some(a=>a.line===s)||o.has(s))throw new M("unknown_fulfillment_group");o.set(s,r)}return i?i.selections.map(({line:r,method:s})=>ce(r,s,o.get(r)?.selected_option_details,t)):[...o].map(([r,s])=>{const a=r.methods.find(c=>c.handle===r.selectedDeliveryMethodHandle&&P(c.methodType)&&c.pickupLocation);if(!a)throw new M("unknown_pickup_destination");return ce(r,a,s.selected_option_details,t)})}function et(e,t){const n=t.find(i=>!!e.id&&i.id===e.id)??t.find(i=>F(i.targetMerchandiseLines,e.line_item_ids));if(!n)throw new M("unknown_fulfillment_group");return n}function ce(e,t,n,i){const o=i.find(r=>!!e.id&&r.value.id===e.id)??i.find(r=>F(r.value.targetMerchandiseLines,e.targetMerchandiseLines?.filter(s=>s.requiresShipping).map(A)));if(!o)throw new M("unknown_fulfillment_group");if(!o.value.deliveryMethodTypes.includes(t.methodType))throw new M("unsupported_fulfillment_transition");return hi(t,n),{deliveryLine:o,selectedOptionId:t.handle,selectedOptionDetails:n}}function hi(e,t){if(t){if(t.instructions!==void 0&&!J(e,"instructions"))throw new M("unsupported_option_instructions");
1if(t.phone_number!==void 0&&!J(e,"phone_number"))throw new M("unsupported_option_phone")}}function _i(e){return{phone:e?.phone_number,instructions:e?.instructions}}function mi(e){return e.status==="available"}const ke=ut()(["shipping","pickup"]);class _ extends Error{constructor(t,n,i){super(`${t}: expected ${n}, got ${i} instead.`),this.name="UpdateCheckoutInputError"}}const tt='Give the street either as street_address (e.g. "123 Yonge St") or as street_name plus street_number (e.g. "Yonge St" and "123"). Partial addresses are accepted; checkout reports missing or invalid address information in messages.',nt={id:{type:"string"},street_address:{type:"string",description:'First address line, typically the street address or PO Box number, e.g. "123 Yonge St". Ignored when street_name is nonempty.'},street_name:{type:"string",description:'Street name without the house or building number, e.g. "Yonge St". When nonempty, street_name and street_number replace street_address.'},street_number:{type:"string",description:'House or building number, e.g. "123". Used only with a nonempty street_name.'},extended_address:{type:"string",description:"Apartment, suite, unit, or other address complement."},district:{type:"string",description:"A regional or city subdivision, such as a neighborhood, district, or block. An empty string clears it. Ignored when the address country has no district field."},address_locality:{type:"string",description:"The city, town, or village used as the locality in the address country."},address_region:{type:"string",description:'State/province/region code (e.g. "ON", "NY") or full name; required for some countries. get_checkout returns the code.'},address_country:{type:"string",description:'ISO 3166-1 alpha-2 country code, e.g. "CA", "US". Not a country name.'},postal_code:{type:"string",description:'Postal or ZIP code in the address country format, e.g. "K1A 0B1", "94103". Case and spacing are normalized.'},company:{type:"string"},first_name:{type:"string"},last_name:{type:"string"},phone_number:{type:"string",description:"Contact phone: address-country national format or E.164 (e.g. +16135550123)."}},yi={type:"object",description:`Replacement address. Include all fields to retain; omitted fields are cleared. Use PUT semantics, not PATCH. ${tt}`,properties:nt},z={type:"object",properties:{instruments:{type:"array",maxItems:1,items:{type:"object",properties:{handler_id:{type:"string",enum:["shopify.card","shop_pay"]},credential:{type:"object"},id:{type:"string"},type:{type:"string",enum:["card","shop_pay"]},selected:{type:"boolean"},billing_address:yi}}}}};function gi(e,{ignorePayment:t=!1}={}){const n=D(e,"input");return le({object:n,allowedFields:["payment"],path:"input"}),t||n.payment===void 0?{}:{payment:it(n.payment,{path:"input.payment",requireCredential:!0})}}function it(e,{path:t,requireCredential:n=!1}){const i=D(e,t);if(!n&&(i.instruments===void 0||Array.isArray(i.instruments)&&i.instruments.length===0))return;const o=`${t}.instruments[0]`,r=Mi(i.instruments,`${t}.instruments`),s=r.handler_id;if(!n&&s===void 0&&r.credential===void 0){const m=Me(r,o);return m===void 0?void 0:{billing_address:m}}if(s!=="shopify.card"&&s!=="shop_pay")throw new _(`${o}.handler_id`,"shopify.card or shop_pay","an unsupported handler");const a=U(r,{id:void 0,type:void 0},o),c=s==="shopify.card"?"card":"shop_pay";if(a.type!==void 0&&a.type!==c)throw new _(`${o}.type`,c,"an unsupported instrument type");const d=Me(r,o),l={id:a.id??wt(),...d===void 0?{}:{billing_address:d}},u=`${o}.credential`,p=!n&&r.credential===void 0?void 0:D(r.credential,u);if(s==="shopify.card"){if(p===void 0)return{...l,handler_id:s,type:"card"};if(le({object:p,allowedFields:["type","token"],path:u}),p.type!==void 0&&p.type!=="shopify_token")throw new _(`${u}.type`,"shopify_token","an unsupported credential type");return{...l,handler_id:s,type:"card",credential:{type:"shopify_token",...n||p.token!==void 0?{token:Pe(p.token,`${u}.token`)}:{}}}}if(p===void 0)return{...l,handler_id:s,type:"shop_pay"};if(le({object:p,allowedFields:["type","approval_id"],path:u}
1),p.type!==void 0&&p.type!=="shop_token")throw new _(`${u}.type`,"shop_token","an unsupported credential type");return{...l,handler_id:s,type:"shop_pay",credential:{type:"shop_token",...n||p.approval_id!==void 0?{approval_id:Pe(p.approval_id,`${u}.approval_id`).trim()}:{}}}}function Pe(e,t){if(typeof e!="string"||e.trim().length===0)throw new _(t,"a non-empty string",S(e));return e}function Me(e,t){if(e.billing_address!==void 0)return U(e.billing_address,rt,`${t}.billing_address`)}function le({object:e,allowedFields:t,path:n}){if(Object.keys(e).some(i=>!t.includes(i)))throw new _(n,"only supported fields","extra properties")}const ot={email:"",phone_number:""},q={first_name:"",last_name:"",phone_number:"",street_address:void 0,extended_address:void 0,address_locality:"",address_region:"",address_country:"",postal_code:""},rt={...q,company:void 0,street_name:void 0,street_number:void 0,district:void 0},Re={phone_number:void 0,instructions:void 0};function vi(e,{ignorePayment:t=!1}={}){const n=Ai(e,{ignorePayment:t});return Ei(bi(),n)}function bi(){return{buyer:{...ot},discountCodes:[],declaredFields:[],shippingAddress:{...q},fulfillmentMethods:{methods:[]},payment:void 0}}function Ei(e,t){return{...e,...t,buyer:{...e.buyer,...t.buyer}}}function Ai(e,{ignorePayment:t}){const n=D(D(e,"input").checkout,"input.checkout"),i={};if(n.context!==void 0){const o="input.checkout.context",r=U(n.context,{address_country:void 0,address_region:void 0,postal_code:void 0},o);if(!r.address_country?.trim()||!r.postal_code?.trim())throw new _(o,"address_country and postal_code for a pickup search","incomplete locality");i.context={address_country:r.address_country.trim().toUpperCase(),postal_code:r.postal_code.trim(),...r.address_region?.trim()&&{address_region:r.address_region.trim().toUpperCase()}}}return n.buyer!==void 0&&(i.buyer=U(n.buyer,ot,"input.checkout.buyer")),n.discounts!==void 0&&(i.discountCodes=Ci(n.discounts)??[]),n.declared_fields!==void 0&&(i.declaredFields=Ti(n.declared_fields)),n.fulfillment!==void 0&&Object.assign(i,Si(n.fulfillment)),!t&&n.payment!==void 0&&(i.payment=it(n.payment,{path:"input.checkout.payment"})),i}const Ii=new Set(["purpose","title","description","value_schema","presentation","required"]);function Ti(e){const t="input.checkout.declared_fields";if(!Array.isArray(e))throw new _(t,"an array",S(e));const n=new Set;return e.map((i,o)=>{const r=`${t}[${o}]`,s=D(i,r);for(const a of Object.keys(s))if(!["key","value"].includes(a)&&!Ii.has(a))throw new _(`${r}.${a}`,"a declared field key or value","an unknown field");if(typeof s.key!="string"||s.key.length===0)throw new _(`${r}.key`,"a non-empty string",S(s.key));if(n.has(s.key))throw new _(`${r}.key`,"a unique declared field key",`duplicate ${JSON.stringify(s.key)}`);if(n.add(s.key),!Object.hasOwn(s,"value")||s.value===void 0)throw new _(`${r}.value`,"a value","undefined");return{key:s.key,value:s.value}})}function Ci(e){const t="input.checkout.discounts",{codes:n}=D(e,t);if(n!==void 0){if(!st(n))throw new _(`${t}.codes`,"an array of strings",S(n));return n}}function Si(e){const t="input.checkout.fulfillment",n=D(e,t);if(!Array.isArray(n.methods))throw new _(`${t}.methods`,"an array",S(n.methods));if(n.methods.length>1)throw new _(`${t}.methods`,"at most 1 fulfillment method",`${n.methods.length} methods`);let i={...q};const o=[];for(const[r,s]of n.methods.entries()){const a=`${t}.methods[${r}]`,c=D(s,a),d=Ni(c.type??"shipping",`${a}.type`),{id:l}=U(c,{id:void 0},a),u={...l!==void 0&&{id:l}},p=c.groups===void 0?[]:ki(c.groups,`${a}.groups`),m=Li(c,a);switch(d){case"pickup":{m===void 0&&Di(c.destinations,`${a}.destinations`),o.push({...u,type:d,...m!==void 0&&{selected_destination_id:m},groups:p});break}case"shipping":{i=m===void 0?wi(c,a):{saved_address_id:m},o.push({...u,type:d,groups:p});break}default:lt(d)}}return{shippingAddress:i,fulfillmentMethods:{methods:o}}}function Ni(e,t){const n=ke.find(i=>i===e);if(n!==void 0)return n;throw new _(t,ke.map(i=>JSON.stringify(i)).join(" or "),typeof e=="string"?JSON.stringify(e):S(e))}function Di(e,t){if(e!==void 0){if(!Array.isArray(e))throw new _(t,"an array",S(e));for(const[n,i]of e.entries()){const o=D(i,`${t}[${n}]`);if(o.type!=="business_location")throw new _(`${t}[${n}].type`,'a read-only "business_location" from get_checkout; select pickup through selected_destination_id',S(o.type))}}}function Li(e,t){if(e.selected_destination_id===null)return;const{selected_destination_id:n}=U(e,{selected_destination_id:void 0},t);
1if(n==="")throw new _(`${t}.selected_destination_id`,"a non-empty string or null","an empty string");return n}function wi(e,t){const n=`${t}.destinations[0]`,i=`${t}.destinations`,{destinations:o}=e;if(o===void 0)return{...q};if(!Array.isArray(o))throw new _(i,"an array",S(o));if(o.length===0)return{...q};if(o.length!==1)throw new _(i,"1 item",`${o.length} items`);const r=D(o[0],n);if(r.pickup_location_address!==void 0||r.type==="business_location")throw new _(n,"a flat shipping address","a pickup location");return{...q,...U(r,rt,n)}}function ki(e,t){if(!Array.isArray(e))throw new _(t,"an array",S(e));return e.flatMap((n,i)=>{const o=`${t}[${i}]`,r=D(n,o),s=r.selected_option_id,a=r.selected_option_details;if(s===void 0){if(a!==void 0)throw new _(`${o}.selected_option_details`,"selected_option_id to also be present","selected_option_details without selected_option_id");return[]}if(typeof s!="string")throw new _(`${o}.selected_option_id`,"a string",S(s));const c=r.id;if(typeof c!="string")throw new _(`${o}.id`,"a string",S(c));const d=r.line_item_ids;if(d!==void 0&&!st(d))throw new _(`${o}.line_item_ids`,"an array of strings",S(d));const l={...Re,...U(a===void 0?{}:a,Re,`${o}.selected_option_details`)};return[{id:c,line_item_ids:d,selected_option_id:s,selected_option_details:l}]})}function D(e,t){if(!Pi(e))throw new _(t,"an object",S(e));return e}function Pi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Mi(e,t){if(!Array.isArray(e))throw new _(t,"an array",S(e));if(e.length!==1)throw new _(t,"1 item",`${e.length} items`);return D(e[0],`${t}[0]`)}function U(e,t,n){const i=D(e,n),o={};for(const r in t){if(!Object.hasOwn(i,r))continue;const s=i[r];if(typeof s!="string")throw new _(`${n}.${r}`,"a string",S(s));o[r]=s}return o}function st(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function S(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"an array":typeof e=="object"?"an object":`a ${typeof e}`}const be="Recoverable messages may be stale and do not by themselves mean completion is blocked. Use supported update_checkout fields to correct known missing or invalid data. When status is ready_for_complete and the buyer has authorized the purchase, call complete_checkout even if recoverable messages remain. Do not retry an unchanged update just to clear messages. After a completion failure, inspect the current checkout and resolve the cause before retrying. requires_buyer_input means a confirmed buyer action, such as a payment challenge: follow the message instructions and do not resubmit checkout. requires_buyer_review means the buyer must review the checkout on the page and authorize submission before complete_checkout is called again to submit.",Ri={type:"object",additionalProperties:!1,properties:{payment:{...z,required:["instruments"],properties:{instruments:{...z.properties.instruments,minItems:1,items:{...z.properties.instruments.items,required:["handler_id","credential"]}}}}}},ie="Checkout is still initializing. Retry shortly. Do not attempt to complete the checkout by interacting with the page.",Y="Checkout completion could not be confirmed. Call get_checkout for the current state and its messages before retrying. Do not attempt to complete the checkout by interacting with the page.";class Oi extends Error{constructor(){super("WebMCP complete_checkout failed"),this.name="WebMcpCompleteCheckoutError"}}function Oe(e){return!!(e?.handler_id==="shopify.card"?e.credential?.token:e?.credential?.approval_id)}function Ui({isSubmitting:e,paymentInstrument:t,signal:n,checkout:i,i18n:o,shop:r,shopPay:s,router:a,source:c,observability:d,getPreactContext:l,declaredFields:u}){let p=!1;return{name:"complete_checkout",title:"Complete checkout",description:`Advances the current checkout toward placing an order, with optional payment details. Use this tool—not browser or DOM controls—to progress or submit, and only after the buyer authorizes the purchase. Read get_checkout first and follow the field schemas. If a review step is configured, the first call opens it without placing an order and returns buyer_review_required. Call complete_checkout again from review only after the buyer reviews the checkout and authorizes submission. Returns checkout state or an error. Use get_checkout to verify the outcome before retrying. Do not resubmit while status is complete_in_progress or completed; only completed confirms the order was placed. If buyer_action_required is returned, ask the buyer to follow the returned instructions on the page; do not act on their behalf. ${be}`,inputSchema:Ri,annotations:{consequentialHint:!0,readOnlyHint:!1,untrustedContentHint:!0},execute:async E=>$(await m(E),i)};async function m(E){if(p||e.value)return{error:{code:"completion_in_progress",message:"A checkout completion is already in progress. Wait for it to finish, then call get_checkout before retrying."}};p=!0;try{if(!r.hasFlagEnabled(kt))return{error:{code:"buyer_action_required",message:"The buyer must manually complete checkout on the page. Do not attempt to complete checkout on their behalf."}};const{payment:f}=gi(E,{ignorePayment:!O(i)}),v=i.latestReceipt.value?.status;if(v==="processing"||v==="processing_remote_checkouts"||v==="polling_for_order"||v==="processed"||v==="action_required")return I()??{error:{code:"completion_failed",message:Y}};const T=l();if(!T||n?.aborted)return{error:{code:"internal_error",message:ie}};if(O(i)&&(f||t.value)){if(await T.waitForPendingNegotiations(),n?.aborted)return{error:{code:"internal_error",message:ie}};const b=O(i)?f??t.value:void 0;if(b&&f&&!i.isPaymentRequired.value)return{error:{code:"invalid_request",message:"This checkout requires no payment. Retry complete_checkout without the payment field."}};if(b&&Oe(b)&&i.isPaymentRequired.value){const L=new Ze({isSubmitting:e,paymentInstrument:t,checkout:i,shop:r,shopPay:s,source:c,observability:d,declaredFields:u,...T});if(f&&(await L.loadAddressMetadata([f.billing_address]),n?.aborted))return{error:{code:"internal_error",message:ie}};const g=L.writePayment({payment:b,applyBilling:f!==void 0});if("error"in g)return g}}let h=!1,y=!1;try{e.value=O(i)&&i.isPaymentRequired.value&&Oe(t.value),await T.journey.progress("web-mcp-complete-checkout",b=>{h=b.status==="success"||b.status==="alreadyCompleted",y||="negotiated"in b||"receipt"in b})}finally{e.value&&y&&(t.value=void 0),e.value=!1}const w=I();return!h&&!w?.messages?.some(b=>b.type==="error"&&b.severity==="requires_buyer_input")?{error:{code:"completion_failed",message:Y}}:w??{error:{code:"completion_failed",message:Y}}}catch(f){return f instanceof _?{error:{code:"invalid_request",message:`${f.message} Correct the input and retry. Do not attempt to complete the checkout by interacting with the page.`}}:(d.error(new Oi),{error:{code:"internal_error",message:Y}})}finally{p=!1}}function I(){return ve({checkout:i,i18n:o,shop:r,router:a,declaredFields:u,paymentInstrument:t.value})}}const xi="Checkout data is not available yet. Retry shortly. Do not attempt to read checkout state by interacting with the page.",Hi="Unable to read the checkout. Do not attempt to read checkout state by interacting with the page.";
1class qi extends Error{constructor(){super("WebMCP get_checkout failed to read the checkout"),this.name="WebMcpGetCheckoutError"}}function Fi({paymentInstrument:e,checkout:t,i18n:n,shop:i,router:o,observability:r,declaredFields:s}){return{name:"get_checkout",title:"Get checkout",description:`Reads the current checkout without changing it. Use it before updating, to inspect validation messages, or to check completion and order confirmation. A status of completed means the order was successfully placed. Monetary amounts are integers in the currency’s minor units. Returns the checkout or an error with a code and message. ${be}`,inputSchema:{type:"object",properties:{}},annotations:{consequentialHint:!1,readOnlyHint:!0,untrustedContentHint:!0},execute:()=>$(a(),t)};function a(){try{const c=ve({checkout:t,i18n:n,shop:i,router:o,readMode:t.latestReceipt.value?.status==="processed"?"negotiated":"proposed",declaredFields:s,paymentInstrument:e?.value});return c||{error:{code:"internal_error",message:xi}}}catch{return r.error(new qi),{error:{code:"internal_error",message:Hi}}}}}const Bi=3e4;
1class ji extends Error{constructor(t){super("WebMCP navigate_to_storefront failed",{cause:t}),this.name="WebMcpStorefrontNavigationError"}}function at({shop:e,url:t}){if(e.hasStorefront)try{const n=new URL(e.previewReturnUrl??t.storefront());return n.protocol!=="https:"&&n.protocol!=="http:"||n.username||n.password?void 0:n.href}catch{return}}function $i({checkout:e,shop:t,url:n,observability:i,signal:o,getPreactContext:r}){return{name:"navigate_to_storefront",title:"Return to storefront",description:"Leaves checkout and navigates this tab to the store’s storefront to continue shopping. Does not place an order or change the cart. After navigation, refresh the available tools before searching for products or changing the cart.",inputSchema:{type:"object",properties:{},additionalProperties:!1},annotations:{readOnlyHint:!1,consequentialHint:!1},execute:async(c,d)=>$(await s(c,d?.signal??o),e)};async function s(c,d){let l;try{if(c===null||typeof c!="object"||Array.isArray(c)||Object.keys(c).length>0)return{error:{code:"invalid_request",message:"navigate_to_storefront takes no input. Retry with an empty object."}};if(d.aborted||o.aborted)return Ue();const u=r();if(!u)return{error:{code:"internal_error",message:"Checkout is still initializing. Retry shortly."}};if(a(u))return xe();const p=at({shop:t,url:n});if(!p)return Gi();const m=new Promise(E=>{l=setTimeout(()=>E("timeout"),Bi)}),I=await Promise.race([u.waitForPendingNegotiations(),m]);return d.aborted||o.aborted?Ue():I==="timeout"?(i.log("web_mcp_storefront_navigation_timed_out","Storefront navigation timed out waiting for pending checkout updates"),{error:{code:"navigation_failed",message:"Checkout updates are still pending. Navigation was not started. Retry after updates finish."}}):a(u)?xe():(window.location.assign(p),{status:"navigation_started",destination_url:p,message:"Refresh the available tools after the storefront loads."})}catch(u){return i.error(new ji(u)),{error:{code:"navigation_failed",message:"Unable to navigate to the storefront. Refresh the available tools and check the current page before retrying."}}}finally{clearTimeout(l)}}function a({journey:c}){const d=e.latestReceipt.value;return c.completing.value||c.progressing.value||d!=null&&!["processed","failed","abandoned"].includes(d.status)}}function Ue(){return{error:{code:"navigation_failed",message:"Navigation was cancelled. The tool did not leave checkout."}}}function xe(){return{error:{code:"checkout_busy",message:"Checkout submission or payment is in progress. Wait for it to finish and call get_checkout before navigating away."}}}function Gi(){return{error:{code:"navigation_failed",message:"A supported storefront destination is not available. Stay on the current checkout."}}}const He=3e4,Yi="Checkout is not available for updates. Retry shortly. Do not attempt to update the checkout by interacting with the page.",Wi="Correct the input and retry. Do not attempt to update the checkout by interacting with the page.",Vi={type:"object",required:["checkout"],properties:{checkout:{type:"object",description:"Replacement buyer, fulfillment, and discount-code state. Omitted sections and fields are cleared; resend values to retain them.",properties:{context:{type:"object",required:["address_country","postal_code"],description:"Optional pickup search origin. Omission retains the current search origin. An unchanged origin may be echoed when switching to shipping. Does not replace shipping or billing addresses. Resolve discovery before selecting a destination in a subsequent call.",properties:{address_country:{type:"string",description:"ISO country code."},address_region:{type:"string",description:"Province or region code."},postal_code:{type:"string"}}},payment:{...z,description:"Payment and billing replacement. Billing may be supplied without a handler or credential. When shipping is required, omitted billing or billing matching shipping uses shipping as billing; a different address becomes custom billing."},buyer:{type:"object",description:"Buyer contact details.",properties:{email:{type:"string",description:'Buyer email address, e.g. "[email protected]".'},phone_number:{type:"string",description:"Buyer phone number; E.164 recommended (e.g. +16135550123)."}}},discounts:{type:"object",description:"Buyer-entered discount codes.",properties:{codes:{type:"array",items:{type:"string"}}}},declared_fields:{type:"array",description:"Replacement values for declared checkout fields. Each field's description in get_checkout states its omission behavior. Echoed descriptor metadata is ignored; only key and value are used.",items:{type:"object",required:["key","value"],properties:{key:{type:"string"},value:{type:["string","boolean","null"]}}}},fulfillment:{type:"object",description:"Use a method type to switch all physical items between shipping and pickup while the delivery selector is mounted. Supply context locality to search for pickup locations. Select a returned destination in a subsequent call. selected_destination_id wins when both it and destinations are supplied.",required:["methods"],properties:{methods:{type:"array",maxItems:1,description:"At most one fulfillment method. Mode changes apply to all physical items; split shipping is not supported. Updates to checkouts with both shipping and pickup are rejected. Omitted methods clear selections without changing the active mode.",items:{type:"object",properties:{id:{type:"string",description:"Existing method ID; omit when changing type."},type:{type:"string",enum:["shipping","pickup"],description:"shipping or pickup. Defaults to shipping. Mode changes and locality discovery support store pickup only. Existing pickup-point destinations remain selectable. A new type or search origin cannot be combined with destination or option selections."},selected_destination_id:{type:["string","null"],description:"Pickup: a location id from get_checkout. Shipping: Shop Pay saved destination ids only. Null selects nothing, so destinations applies instead."},destinations:{type:"array",items:{type:"object",description:`One replacement shipping address, ignored when selected_destination_id is set. Use PUT semantics, not PATCH. ${tt}`,properties:nt}},groups:{type:"array",items:{type:"object",required:["id"],properties:{id:{type:"string"},line_item_ids:{type:"array",items:{type:"string"}},options:{type:"array",items:{type:"object",required:["id"],properties:{id:{type:"string"}}}},selected_option_id:{type:"string",description:'Option ID from get_checkout; "pickup" for pickup groups.'},selected_option_details:{type:"object",description:"Requires selected_option_id.",properties:{phone_number:{type:"string"},instructions:{type:"string"}}}}}}}}}}}}}}},zi="Updates the current checkout without placing an order. Use this tool—not browser or DOM controls—whenever checkout data needs to change, even if visible fields are partially filled. Supports buyer contact details, shipping addresses and options, billing addresses, discounts, and payment details. Read get_checkout first and follow the field schemas’ replacement rules; do not assume omitted data is preserved. Returns the resulting checkout or an error. If an update fails, call get_checkout and inspect its messages before retrying.";
1class Xi extends Error{constructor(){super("WebMCP update_checkout failed to apply"),this.name="WebMcpUpdateCheckoutError"}}function Ki({isSubmitting:e,paymentInstrument:t,signal:n,checkout:i,i18n:o,shop:r,shopPay:s,source:a,router:c,observability:d,getPreactContext:l,declaredFields:u,getFulfillmentController:p}){return{name:"update_checkout",title:"Update checkout",description:`${zi} ${be}`,inputSchema:Vi,annotations:{consequentialHint:!1,readOnlyHint:!1,untrustedContentHint:!0},execute:async I=>$(await m(I),i)};async function m(I){let E;try{if(e.value)return j();const f=vi(I,{ignorePayment:!O(i)}),v=l();if(!v||n?.aborted)return{error:{code:"internal_error",message:Yi}};c.currentUrl.value.normalizedPath==="/review"&&c.navigate("/");const{loadPickupLocalityServices:T}=v;let h;const y=new Ze({isSubmitting:e,paymentInstrument:t,checkout:i,shop:r,shopPay:s,source:a,observability:d,declaredFields:u,...v,getFulfillmentController:p,resolvePickupLocality:T?async g=>(h=await T(),h.resolvePickupLocality(g)):void 0,announcePickupLocality:g=>h?.announcePickupLocality(g),get negotiator(){return v.negotiator}});let w=!1;const b=new Promise(g=>{E=setTimeout(()=>{w=!0,g("timeout")},He)}),L=await Promise.race([y.applyUpdate(f,{isExpired:()=>w||!!n?.aborted}),b]);return L==="timeout"?(d.log("web_mcp_update_timed_out","[WebMcp] Update did not finish in time; update outcome is unknown",{timeoutMs:He}),{error:{code:"update_failed",message:V}}):"error"in L?L:ve({checkout:i,i18n:o,shop:r,router:c,declaredFields:u,paymentInstrument:t.value})??{error:{code:"update_failed",message:V}}}catch(f){return f instanceof _?{error:{code:"invalid_request",message:`${f.message} ${Wi}`}}:(d.error(new Xi),{error:{code:"internal_error",message:V}})}finally{clearTimeout(E)}}}function Ji(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="object"}function Qi(e){if(typeof e!="object"||e===null||!("error"in e))return"unknown";const{error:t}=e;if(typeof t!="object"||t===null||!("code"in t))return"unknown";switch(t.code){case"buyer_action_required":case"checkout_busy":case"completion_failed":case"completion_in_progress":case"internal_error":case"invalid_request":case"navigation_failed":case"rejected":case"update_failed":return t.code;default:return"unknown"}}function ue(e,t,n,i){const o=Math.round(performance.now()-i),r=Ji(n),s={tool:t,outcome:r?"error":"success",...r&&{errorCode:Qi(n)}};e.log("web_mcp_tool_executed","[WebMcp] tool executed",{...s,durationMs:o}),e.histogram({name:"web_mcp_tool_execution",value:o,unit:"ms",attributes:s})}function qe(e,{activeTool:t,observability:n,checkout:i}){const o=e.name;return{...e,execute:async(...r)=>{const s=performance.now();if(t.current==="navigate_to_storefront"||o==="navigate_to_storefront"&&t.current!==void 0){const a=$({error:{code:"checkout_busy",message:"Another checkout tool is running. Wait for it to finish before retrying."}},i);return ue(n,o,a,s),a}return t.during(o,async()=>{const a=await e.execute(...r);return ue(n,o,a,s),a})}}}function Zi(e,t){const n=e.name;return{...e,execute:(...i)=>{const o=performance.now(),r=e.execute(...i);return ue(t,n,r,o),r}}}
1class eo extends Error{constructor(t,n){super(`WebMCP tool registration failed for ${t}: ${String(n)}`),this.name="WebMcpRegistrationError",n instanceof Error&&(this.cause=n)}}function to(e,t){const n=new AbortController,i=pt(function(){e.latestReceipt.value?.status==="processed"&&(this.dispose(),n.abort())});return t.addEventListener("abort",()=>{i(),n.abort()},{once:!0,signal:n.signal}),n.signal}function no({modelContext:e,signal:t,isSubmitting:n,paymentInstrument:i,checkout:o,i18n:r,shop:s,shopPay:a,source:c,url:d,router:l,observability:u,activeTool:p,onActiveToolCreated:m,getPreactContext:I,declaredFields:E,getFulfillmentProvider:f,unregisterInitializingTool:v}){if(t.aborted)return;const T=Ft(o);E.set(T.key,T);const h=p??new Ut;m?.(h);const w=[{tool:Zi(Fi({checkout:o,i18n:r,shop:s,router:l,observability:u,declaredFields:E,paymentInstrument:i}),u),signal:t}],b=to(o,t);b.aborted||w.push(...[Ki({isSubmitting:n,paymentInstrument:i,signal:t,checkout:o,i18n:r,shop:s,shopPay:a,source:c,router:l,observability:u,getPreactContext:I,declaredFields:E,getFulfillmentController:()=>{const g=f?.();return g?Bt(g,o.proposal):void 0}}),Ui({isSubmitting:n,paymentInstrument:i,signal:t,checkout:o,i18n:r,shop:s,shopPay:a,source:c,router:l,observability:u,getPreactContext:I,declaredFields:E})].map(g=>({tool:qe(g,{activeTool:h,observability:u,checkout:o}),signal:b}))),at({shop:s,url:d})&&w.push({tool:qe($i({checkout:o,shop:s,url:d,observability:u,signal:t,getPreactContext:I}),{activeTool:h,observability:u,checkout:o}),signal:t}),v?.();const L=w.map(({tool:g,signal:R})=>e.registerTool(g,{signal:R}).then(()=>"registered",dt=>R.aborted?"withdrawn":(u.error(new eo(g.name,dt)),"failed")));return Promise.all(L).then(g=>{t.aborted||u.log("web_mcp_tools_registered","[WebMcp] tools registered",{registered:g.filter(R=>R==="registered").length,failed:g.filter(R=>R==="failed").length})}).catch(()=>{}),h}const co=Object.freeze(Object.defineProperty({__proto__:null,registerWebMcpTools:no},Symbol.toStringTag,{value:"Module"}));export{Ie as n,co as w};

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.