PageSourceSearch

https://store.drdishbasketball.com/cdn/shopifycloud/checkout-web/assets/c1/web-mcp-runtime.D64LTNwp.js

js drdishbasketball.com collected 2026-09-25 00:26:00 UTC 83,416 bytes, 1 lines download raw bytes

1import{c as _t,n as B,a as yt,b as gt,j as vt}from"./esnext-vendor.BBoIVOQW.js";import{c as bt,s as ge,a as ce,b as ve,R as be,d as At,i as M,e as It,n as We,f as Ve,g as Et,h as Ct,j as Tt,C as St,k as wt,V as Z,p as Pt,l as Dt,m as Lt,o as Nt,U as kt,q as Mt,r as Rt,t as Ot,u as Ut,F as xt,v as Ht,w as Se,x as we,y as qt,z as Ft,A as Bt,B as jt,D as $t,E as Gt}from"./addresses-is-address-empty.ZJ1ThpFy.js";import{i as Yt}from"./helpers-credit-card-disabled.CM3LQmkz.js";import{s as Wt}from"./helpers-derivations.f29j39ws.js";import{a as U,i as Vt}from"./context-browser.Eq5uMdYA.js";class zt{#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)}}}function Xt(e){return Array.from(e.values()).flatMap(t=>{const n=t.read();return n?[n]:[]}).sort((t,n)=>Kt(t.key,n.key))}function Kt(e,t){return e===t?0:e<t?-1:1}function z(e,t){const n=e??[],i=new Map;for(const[r,{key:s,value:a}]of n.entries()){const d=`$.checkout.declared_fields[${r}]`,c=t.get(s);if(!c?.read())return ie(`${d}.key`,"must identify a declared field available in the current checkout");const l=c.prepare(a);if("requirement"in l)return ie(`${d}.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 ie("$.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 ie(e,t){return{error:{code:"rejected",message:`${e}: ${t}. Nothing was applied. Call get_checkout before retrying.`}}}function Jt(e){const{email:t,phone:n}=e??{};if(!(!t&&!n))return{...t?{email:t}:{},...n?{phone_number:n}:{}}}function P(e){if(!e)return 0;const t=_t(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 Qt(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:d}of e.allocations){let c=d.index;if(d.type==="MERCHANDISELINE"&&t&&(c=d.stableId==null?void 0:t.get(d.stableId),c==null)){r=!0;continue}const l=P(d.amount);o+=l,d.type==="MERCHANDISELINE"&&c!=null?i.push({path:`$.line_items[${c}]`,amount:l}):d.type==="DELIVERYLINE"&&i.push({path:"$.totals.shipping",amount:l})}const s=n.type==="code"&&n.codeHidden,a=r?0:P(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 ee(e,{extendedAddressMode:t}){const n=e.address_country?.toUpperCase()??"",i=t.get(n),o=i===null?en(n,e):tn(n,e,i);return{...bt({...e,street_address:o.address1,extended_address:o.address2}),company:e.company??"",district:void 0,subdistrict:void 0,...o}}function Ae(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?rn(n,e):an(n,e,i),address_locality:e.city,address_region:e.zoneCode,address_country:e.countryCode,postal_code:e.postalCode}}function ze({street_address:e="",street_name:t,street_number:n=""}){return t?.trim()?{streetName:t,streetNumber:n}:{line:e}}function en(e,t){const n=ze(t);return{address1:"line"in n?n.line:ln(e,n),address2:t.extended_address??""}}function tn(e,t,n){const{packedLine2:i,...o}=nn(e,ze(t)),{neighborhood:r,...s}=on(e,t,i);return{...o,...s,...n==="dedicated"?r!==void 0&&{district:r,neighborhood:""}:{neighborhood:r}}}function nn(e,t){if("line"in t){const i=ge(e,t.line,!0);if(!i?.streetNumber)return{address1:t.line};const o=ce({countryCode:e,streetName:i.streetName??"",streetNumber:i.streetNumber});return o==null?{address1:t.line}:{address1:o,packedLine2:i.line2}}const n=ce({countryCode:e,...t});return n==null?{address1:Qe(t)}:{address1:n,...t}}function on(e,{extended_address:t="",district:n},i){const o=ve(e,t);if(!o)return{address2:Pe(t,i)};const r=Pe(o.line2??"",i),s=n??o.neighborhood??"";return{address2:Je(e,r,s),line2:r,neighborhood:s}}function Pe(e,t){return!t||t===e.trim()?e:Ze(e,t)}function rn(e,t){return{street_address:Xe(e,t),extended_address:sn(e,t)}}function Xe(e,{address1:t,streetName:n,streetNumber:i}){return t||!(n||i)?t:Ke(e,{streetName:n??"",streetNumber:i??""})}function sn(e,{address2:t,line2:n,district:i,neighborhood:o}){const r=i||o;return n==null&&!r?t:Je(e,n??"",r??"")}function an(e,t,n){const i=dn(e,t,n);return{...i?.streetName?{street_name:i.streetName,street_number:i.streetNumber??""}:{street_address:Xe(e,t)},...cn(e,t,n)}}function dn(e,t,n){return n==="dedicated"&&(t.streetName!=null||t.streetNumber!=null)?t:t.address1?.includes(be)?ge(e,t.address1):null}function cn(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(be)?ve(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 Ke(e,t){return ce({countryCode:e,...t})??Qe(t)}function Je(e,t,n){return At({countryCode:e,line2:t,neighborhood:n})??Ze(t,n)}function ln(e,t){return un(Ke(e,t))}function Qe({streetName:e,streetNumber:t}
1){return[t,e].filter(Boolean).join(" ")}function Ze(e,t){return[e,t].filter(Boolean).join(", ")}function un(e){return e.split(be).join("")}function pn(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:d}=hn(o.lineAllocations),c=[];n+=d,s&&c.push({type:"subtotal",amount:P(s)}),a!==0&&s&&(t+=a,c.push({type:"items_discount",amount:P({...s,amount:-a})}));const l=s?{...s,amount:s.amount-a}:o.totalPrice;return c.push({type:"total",amount:P(l)}),{id:C(o),...o.parentRelationship?.parent?.stableId?{parent_id:o.parentRelationship.parent.stableId}:{},quantity:o.quantity,item:{id:o.variantId??o.stableId,title:o.title,price:P(r),...o.image?.url?{image_url:o.image.url}:{}},totals:c}}),itemsDiscountAmount:t,cartLevelDiscountAmount:n}}function Ie(e){return e?.flatMap(t=>(t.lineComponents.length?t.lineComponents:[t]).filter(n=>n.requiresShipping).map(C))??[]}function fn(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 C(e){return e.stableId}function hn(e){let t=0,n=0;for(const i of e)for(const{discountDetails:o,amount:r}of i.allocations)mn(o.discount)?n+=r.amount:t+=r.amount;return{lineLevel:t,cartLevel:n}}function mn(e){return"presentationLevel"in e&&e.presentationLevel==="CART"}function K(e){return e==="SHIPPING"||e==="LOCAL"||M(e)}function _n(e,t,n){return!!(e&&!n&&(t.some(i=>!K(i))||t.some(M)&&t.some(i=>i==="SHIPPING"||i==="LOCAL")))}function yn(e,t,n){return!n||e===t}function te(e,t){switch(t){case"phone_number":return!!e.phoneRequired;case"instructions":return!!e.acceptsInstructions}}function Y(e,t){if(!e?.length||!t?.length)return!1;const n=new Set(t),i=e.filter(o=>o.requiresShipping).map(o=>C(o));return i.length===n.size&&i.every(o=>n.has(o))}const le="pickup";function W(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 M(n)?"pickup":"shipping"}function et(e){const t=e.filter(r=>W(r)==="pickup"),n=t.map(r=>{const s=new Map;for(const a of r.methods){if(!a.pickupLocation)continue;const d=gn(a.pickupLocation);(!s.has(d)||a.handle===r.selectedDeliveryMethodHandle)&&s.set(d,a)}return s}),i=n[0];if(!i)return[];const o=[];for(const[r,s]of i){const a=[];for(const[d,c]of t.entries()){const l=n[d].get(r);if(!l)break;a.push({line:c,method:l})}a.length===t.length&&o.push({id:s.handle,selections:a})}return o}function gn(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 vn(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})=>It(r,t)):void 0;return{destinations:i,selectedDestinationId:o?.id}}function bn(e){const t=In(e);return t.length?{methods:t}:void 0}function An(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 Ee=Ae;function In(e){const{deliveryNext:t}=e;if(e.readMode!=="proposed"&&(t?.status!=="filled"&&t?.status!=="partial"||!t.lines))return De(e);const n=(t?.status==="filled"||t?.status==="partial")&&t.lines?t.lines.filter(kn):[],o=(e.readMode==="proposed"?Dn(n,e.proposedDeliveryLines,e.merchandiseLines):n).filter(d=>(d.proposedLine?d.proposedLine.deliveryMethodTypes.some(Le):d.methods.some(c=>Le(c.methodType)))&&d.targetMerchandiseLines?.some(c=>c.requiresShipping));if(e.readMode==="proposed"&&!o.length)return De(e);const r=t?.status==="partial"?tt(e,o):new Map,s=new Set([...En(o),...r.keys()]),a=[];for(const d of s){const c=o.filter(p=>W(p)===d),l=c.map(p=>Pn(p,p.proposedLine?[p.proposedLine]:e.proposedDeliveryLines)),u=[...new Set([...l.flatMap(p=>p.line_item_ids),...r.get(d)??[]])];a.push({id:d,type:d,line_item_ids:u,destinations:[],...Cn(d,c,e),groups:l})}return a}function tt(e,t){const n=new Set(t.flatMap(r=>r.targetMerchandiseLines?.map(C)??[])),i=new Map,o=new Set;for(const r of e.merchandiseLines??[]){if(e.readMode!=="proposed"&&!r.requiresShipping)continue;const s=C(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(C(u))).map(C));if(!a.size)continue;const d=e.proposedDeliveryLines?.filter(u=>u.targetMerchandiseLines.some(p=>C(p)===s||a.has(C(p)))).flatMap(u=>u.deliveryMethodTypes),c=d?.length&&d.every(M)?"pickup":"shipping",l=i.get(c)??[];l.push(...e.readMode==="proposed"?a:[s]),i.set(c,l)}return i}function De(e){return[...tt(e,[])].map(([n,i])=>({id:n,type:n,line_item_ids:i,destinations:[],...n==="shipping"?nt(e):{},groups:[]}))}function En(e){const t=new Set;for(const n of e){const i=W(n);i&&t.add(i)}return Array.from(t)}function Le(e){return e==="SHIPPING"||e==="LOCAL"||M(e)}function Cn(e,t,n){if(e==="shipping")return nt(n);const i=et(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=Tn(s[0].method,n.addressContext);return a?[{...a,id:r}]:[]}),...o&&{selected_destination_id:o.id}}}function nt({savedDestinations:e,shippingAddress:t,addressContext:n}){if(e===void 0)return t&&Ve(t)?{destinations:[Sn(t,n)]}:{};const{destinations:i,selectedDestinationId:o}=vn(e,t);return i.length?{destinations:i.map(({id:r,address:s})=>({id:r,type:"shipping_address",...Ee(s,n)})),...o&&{selected_destination_id:o}}:{}}function Tn(e,t){const{pickupLocation:n}=e;if(n)return{id:e.handle,type:"business_location",name:n.name??"",pickup_location_address:Ee(n.address,t)}}function Sn(e,t){return{...Ee(e,t),id:wn(e),type:"shipping_address"}}function wn(e){return["shipping",e.countryCode,e.postalCode].filter(
1Boolean).join("-").replace(/\s+/g,"")}function Pn(e,t){const n=it(e),i=We(e),o=e.proposedLine?e.selectedDeliveryMethodHandle:i?.handle,r=o?Ln(e,n,t):void 0,s=W(e)==="pickup",a=s?[{...i?Ne(i):{totals:[]},id:le,title:"Pickup"}]:e.methods.filter(({methodType:d})=>d==="SHIPPING"||d==="LOCAL").map(Ne);return{id:e.id??"",line_item_ids:n,options:a,...o&&{selected_option_id:s?le:o},...r&&{selected_option_details:r}}}function Dn(e,t,n){const i=new Map;for(const o of n??[]){i.set(C(o),Ie([o]).length>0);for(const r of o.lineComponents)i.set(C(r),r.requiresShipping)}return(t??[]).map(o=>{const r=o.targetMerchandiseLines.filter(a=>a.requiresShipping).map(a=>C(a)),s=e.find(a=>o.id!==void 0&&a.id===o.id)??e.find(a=>a.type===o.type&&Y(a.targetMerchandiseLines,r));return{...s,status:"available",id:o.id,type:o.type,targetMerchandiseLines:o.targetMerchandiseLines.flatMap(a=>{const d=i.get(C(a));return d===void 0?[]:[{...a,requiresShipping:d}]}),selectedDeliveryMethodHandle:o.deliveryMethodHandle,methods:s?.methods.filter(a=>o.deliveryMethodTypes.includes(a.methodType))??[],proposedLine:o}})}function Ln(e,t,n){const i=Nn(e,n,t);if(!i||!e.selectedDeliveryMethodHandle||i.deliveryMethodHandle!==e.selectedDeliveryMethodHandle)return;const o=i.deliveryMethodOptions;if(!o)return;const r=We(e),s=r&&!te(r,"phone_number")?void 0:o.phone,a=r&&!te(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 Nn(e,t,n=it(e)){return t?.find(i=>!!e.id&&i.id===e.id)??t?.find(i=>Y(i.targetMerchandiseLines,n))}function it(e){return e.targetMerchandiseLines?.filter(t=>t.requiresShipping).map(t=>C(t))??[]}function Ne(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:M(e.methodType)?"Pickup":"Shipping",amount:P(e.costAfterDiscounts)}]}}function kn(e){return e.status==="available"}const Mn=new Map([["terms-of-service","terms_of_service"],["privacy-policy","privacy_policy"],["refund-policy","refund_policy"],["shipping-policy","shipping_policy"]]);function Rn(e){const t=[];for(const{handle:n,url:i}of e){const o=Mn.get(n);o&&t.push({type:o,url:i})}return t}function On(e){if(e?.status!=="processed")return;const t=e.orderIdentity.buyerIdentifier,n=Et(e.orderIdentity.id);return{...n?{id:Ct("Order",n)}:{},...t?{label:t}:{},permalink_url:e.confirmationPage.url}}function Un(e,t,n){const i=n?.filter(({instrument:o,usable:r})=>o.selected||r).map(({instrument:o})=>o);return i?.length?{instruments:i}:{instruments:e?[{billing_address:Ae(e,t)}]:[]}}function xn(e){return e.some(({instrument:n,usable:i})=>n.selected&&!i)?[{type:"error",severity:e.some(({usable:n})=>n)?"recoverable":"requires_buyer_input",code:"payment_instrument_unusable",path:"$.payment",content:"The selected card cannot be used for this checkout. Select another instrument by id, or ask the buyer to update payment on the page."}]:[]}const Hn={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 qn(e){return Hn[e]}const Fn=new Set(["AcceptNewTermViolation","RequiredArtifactsUnavailableViolation"]),Bn=new Set(["PendingTermViolation"]),jn=new Set(["PAYMENTS_UNACCEPTABLE_PAYMENT_AMOUNT"]),$n={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 Gn(e){const{receipt:t,isShippingRequired:n,hasShippingAddress:i,deliveryNext:o,skipsShippingAddress:r=Tt(o)}=e,s=Yn(e),a=Vn({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($n),{status:a,messages:s}}function Yn(e){const t=[];for(const n of e.violations??[]){if(Fn.has(n.__typename)||jn.has(n.code)||e.requiresCaptcha&&St.has(n.code))continue;const i=n.code.startsWith("DISCOUNTS_"),o=i||Bn.has(n.__typename),r=qn(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:Wn(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 Wn(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 Vn({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 zn({subtotal:e,itemsDiscountAmount:t,cartLevelDiscountAmount:n,discountLines:i,fulfillmentTotal:o,tax:r,duty:s,dutiesIncluded:a,runningTotal:d}){const c=[];return e!=null&&(c.push({type:"subtotal",display_text:"Subtotal",amount:P(e)}),c.push(...Xn({currencyCode:e.currencyCode,discountLines:i,itemsDiscountAmount:t,cartLevelDiscountAmount:n}))),o!=null&&c.push({type:"fulfillment",display_text:"Shipping",amount:P(o)}),s!=null&&!a&&c.push({type:"duty",display_text:"Duties",amount:P(s)}),r!=null&&c.push({type:"tax",display_text:"Taxes",amount:P(r)}),d!=null&&c.push({type:"total",display_text:"Total",amount:P(d)}),c}function Xn({currencyCode:e,discountLines:t,itemsDiscountAmount:n,cartLevelDiscountAmount:i}){let o=i;for(const s of t?.lines??[])if(wt(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:P({amount:-n,currencyCode:e})}),o>0&&r.push({type:"discount",display_text:"Discount",amount:P({amount:-o,currencyCode:e})}),r}function Kn(e){const t=e.merchandiseLines?.lines;if(!t||!Qn(t)||e.runningTotal==null)return;const n=e.readMode==="proposed"&&t.length===0?{...e.runningTotal,amount:0}:fn(t)??e.subtotal;if(n==null)return;const{lineItems:i,itemsDiscountAmount:o,cartLevelDiscountAmount:r}=pn(t),s=An(e.deliveryNext),a=e.receipt?.status==="processed"&&e.receipt.isRedacted?void 0:Jt(e.contactInfo),d=Qt(e.discountLines,e.readMode==="proposed"?i:void 0),c=bn({readMode:e.readMode,deliveryNext:e.deliveryNext,shippingAddress:e.shippingAddress,merchandiseLines:t,savedDestinations:e.savedDestinations,addressContext:e.addressContext,proposedDeliveryLines:e.proposedDeliveryLines}),{status:l,messages:u}=Gn({i18n:e.i18n,requiresBuyerReview:e.buyerReviewUrl!=null,requiresCaptcha:e.requiresCaptcha,violations:e.violations,receipt:e.receipt,isShippingRequired:e.readMode==="proposed"?Ie(t).length>0:e.isShippingRequired,hasShippingAddress:e.readMode==="proposed"?Ve(e.shippingAddress):e.shippingAddress!=null,deliveryNext:e.deliveryNext,skipsShippingAddress:e.readMode==="proposed"?Jn(c,t):void 0}),p=On(e.receipt),f=Un(e.billingAddress,e.addressContext,e.savedCards),y=xn(e.savedCards??[]),g=[...u,...y];return{...e.id?{id:e.id}:{},...e.continueUrl?{continue_url:e.continueUrl}:{},currency:e.runningTotal.currencyCode,status:l==="ready_for_complete"&&y.length?"incomplete":l,...l==="requires_escalation"&&e.buyerReviewUrl?{continue_url:e.buyerReviewUrl}:{},links:Rn(e.merchantPolicies),line_items:i,totals:zn({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},...d&&{discounts:d},...c&&{fulfillment:c},payment:f,...g.length?{messages:g}:{},...p&&{order:p}}}function Jn(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(C(i))||Ie([i]).every(o=>n.has(o)))}function Qn(e){return e.every(t=>t.itemPrice!=null&&t.title!=null)}function Zn({checkout:e,i18n:t,shop:n,router:i,readMode:o="negotiated",savedCards:r,declaredFields:s=new Map,paymentInstrument:a}){const d=Kn({...ti(e,t,n,o,i),savedCards:e.isPaymentRequired.value?r:void 0});if(!d)return;const c=Xt(s),l=d.payment.instruments[0],u={...d,...a?{payment:{instruments:[ei(a,e,l&&"billing_address"in l?l.billing_address:{})]}}:{},...c.length>0?{declared_fields:c}:{}},p=e.proposal.proposed.locationAddress.value;return u.fulfillment?.methods.length!==1||u.fulfillment.methods[0].type!=="pickup"||!p?.countryCode||!p.postalCode||!p.coordinates?u:{...u,context:{address_country:p.countryCode,...p.zoneCode&&{address_regi
1on:p.zoneCode},postal_code:p.postalCode}}}function ei(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 ti(e,t,n,i,o){const{proposed:r,negotiated:s}=e.proposal,a=e.addressManager.shipping.value,d=e.identity.current.value==="shopPay"?a:void 0,c=d?[...d.addresses.value,...d.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??oi(s.fields.taxes.value),duty:e.proposal.facts.duty??ri(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:e.identity.current.value==="shopPay"?void 0:ni(e,n,i),addressContext:e.address,savedDestinations:c,proposedDeliveryLines:r.deliveryLines.value.map(f=>
1f.value),isShippingRequired:!!s.fields.isShippingRequired.value,violations:s.fields.allViolations.value,receipt:e.latestReceipt.value}}function ni(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"?ii(e,t):e.proposal.negotiated.fields.billingAddress.value}function ii(e,t){const{proposed:n,negotiated:i,facts:o}=e.proposal,r=n.paymentLines.value;for(const{method:c}of r)if(c.type===Z.CreditCard||c.type===Z.PayPal)return c.billingAddress;const s=n.billingAddress.value,a=!s.address1&&o.billingAddress?o.billingAddress:s;if(n.billingAddressOption.value!=="shipping"||!i.fields.isShippingRequired.value||!Pt(r))return a;const d=r[0]?.method;if(d?.type==="wallet"){const c=i.fields.runningTotal.value,l=c&&c.amount<=0,u=Dt(i.fields.merchandiseLines.value?.lines).some(f=>!!f.sellingPlan?.subscriptionDetails);if((!l||u||i.fields.deferredTotal.value?.amount.amount)&&(d.name==="GOOGLE_PAY"||d.name==="APPLE_PAY"||d.name==="PAYPAL_EXPRESS"&&Lt({checkout:e,shop:t,paymentMethods:i.fields.paymentMethods.value})))return a}return o.delivery?.[0]?.deliveryAddress??n.shippingAddress.value}function oi(e){return e?.status==="available_total"?e.totalTax:void 0}function ri(e){return e?.status==="available_total"?e.totalDuty:void 0}const ke="tax_number",si=["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"],ai=new Set(["TAX_CREDENTIAL_BR","SHIPPING_CREDENTIAL_BR","SHIPPING_CREDENTIAL_CN","SHIPPING_CREDENTIAL_KR","SHIPPING_CREDENTIAL_MX"]),di=si.map(e=>({key:e,required:ai.has(e)}));function ci(e){const t={key:ke,read(){const n=Me(e);if(!n)return;const{title:i,value:o}=n.extension.fields;return{key:ke,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=Me(e);return i?(i.extension.fields.value.value=n??"",!0):!1}}}};return t}function Me(e){const n=e.proposal.proposed.localizationExtensions.value.flatMap(i=>{const o=di.find(({key:r})=>r===i.fields.key.value);return o?[{definition:o,extension:i}]:[]});return n.length===1?n[0]:void 0}function Ce(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 ue(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 li(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=Ce(t.merchandiseLines.value,r);if(!ui(o,n)){e.applyMethodChange(n,o,i);return}B(()=>{for(const a of t.deliveryLines.value){const d=a.value;d.targetMerchandiseLines.some(({stableId:c})=>s.has(c))&&(d.deliveryMethodTypes.length!==n.length||d.deliveryMethodTypes.some(c=>!n.includes(c)))&&(a.value={...d,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 ui(e,t){return e.length>0&&e.every(n=>n==="SHIPPING"||n==="LOCAL"?t.includes("SHIPPING")||t.includes("LOCAL"):t.includes(n))}function pi(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 V(e,t){return{...e,ucp:pi("error"in e?"error":"success",t.proposal.negotiated.fields.ucp.value?.paymentHandlers)}}function fi({checkout:e,shopPay:t}){const n=Wt({identity:e.identity,shopPay:t,negotiatedFields:e.proposal.negotiated.fields},{isApplePayAvailable:t.user.isApplePayAvailable}),i=e.proposal.negotiated.fields.paymentMethods,o=t.session.isInstallmentsSelected,r=e.installments.paymentMethodMustSupportInterestBearingLoans;return()=>{if(e.identity.current.value!=="shopPay"||t.session.isLoading.value)return;const s=t.user.paymentMethods.value.filter(Nt).filter(({id:l})=>l!==kt).sort(Mt),a=Rt(s,n.value),d=t.session.selectedPaymentMethod.value,c=e.proposal.proposed.paymentLines.value.some(({method:l})=>l.type==="wallet"&&l.name==="SHOP_PAY");return s.map(l=>{const u=l.paymentAttributes;return{instrument:{id:l.id,type:"card",selected:c&&d?.paymentMethod==="CREDIT_CARD"&&d.id===l.id,display:{brand:u.brand,last_digits:u.lastDigits}},usable:!u.expired&&u.verified&&a.includes(l)&&!Yt(u,i,o,r)}})}}function Re(e){return e?.replace(/[\s-]/g,"").toUpperCase()}function hi(e,t){return!!e?.coordinates&&e?.countryCode===t.countryCode&&(!t.zoneCode||e.zoneCode===t.zoneCode)&&Re(e.postalCode)===Re(t.postalCode)}function oe(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(m=>m.value),d=Ce(r.merchandiseLines.value,a),c=ue(a,d);if(c.some(M)&&c.some(re)){const m=s.fields.deliveryNext.value,A=m?.status==="filled"||m?.status==="partial"?m.lines.filter(v=>v.status==="available"):[],S=a.map(v=>{const I=(A.find(({id:R})=>!!v.id&&R===v.id)??A.find(R=>Y(R.targetMerchandiseLines,v.targetMerchandiseLines.filter(N=>N.requiresShipping).map(C))))?.methods.find(({handle:R,methodType:N})=>R===v.deliveryMethodHandle&&v.deliveryMethodTypes.includes(N))?.methodType??(v.deliveryMethodHandle?void 0:v.deliveryMethodTypes[0]);return I?{...v,deliveryMethodTypes:[I]}:v}),w=ue(S,d);if(w.some(M)&&w.some(re))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??(c.length&&c.every(M)?"pickup":void 0),u=!!(e.context&&!pe(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=m=>l==="pickup"?M(m):re(m);if(o&&(o.selected_destination_id!==void 0||o.groups.length))return u||c.length&&!c.some(p)?k("Change the method/search origin first, then select a destination or option returned by that update."):void 0;if(l==="pickup"&&c.length&&c.every(m=>m==="PICKUP_POINT"))return u?k("Pickup-point locality discovery is not supported. Select an existing destination instead."):void 0;if(!d.size)return k("This checkout has no physical items to fulfill.");if(l==="pickup"&&e.context){const m=r.shippingAddress.value?.countryCode||r.locationAddress.value?.countryCode;if(!m)return k("Pickup search requires an established checkout country. Ask the buyer to choose a country in checkout.");if(e.context.address_country!==m)return k("Pickup search must remain in the checkout country.")}if(!n&&!u&&c.every(p)&&c.length)return;const f=!c.length||!c.every(p);if(!n&&f)return k("The delivery selector is not ready.");const y=n?n.getAvailableMethodTypes().find(m=>l==="pickup"?m.includes("PICK_UP"):m.some(p)):c;if(!y)return k(`The checkout does not offer ${l}.`);const g=s.fields;return(f||u)&&(g.mustSelectProvidedShippingRate.value||g.mustSelectProvidedAddress.value||g.canUpdateDeliveryAddress.value===!1)?k("The checkout locks its delivery method or address."):{methodTypes:y,needsLocalityLookup:u,changesMo
1de:f}}function re(e){return e==="SHIPPING"||e==="LOCAL"}function pe(e,t){return hi(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 J="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.",q={status:"written"};function mi(e){return e.paymentLines.value.some(t=>t.method.type===Z.CreditCard||t.method.type===Z.PayPal||_i(t))}function _i(e){if(e.method.type!=="wallet")return!1;switch(e.method.name){case"APPLE_PAY":return jt(e);case"GOOGLE_PAY":return Bt(e);case"PAYPAL_EXPRESS":return Ft(e);default:return!1}}const yi=({buyer:e},{checkout:t,shopPay:n})=>{const i=Vt({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,q}}},ot=({shippingAddress:e},t)=>{if("saved_address_id"in e)return vi(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=ee(e,n.address);return{status:"ready",negotiation:{include:["shippingAddress","deliveryNext"],loading:["deliveryNext"],fieldsToResolve:["shippingAddress","deliveryNext"]},async apply(){const d=await r.applyAddressChange({source:"ucp",address:a});return d.type!=="success"?(i.log("web_mcp_address_change_declined","[WebMcp] address manager declined an admitted address",{reason:d.reason}),{status:"failed"}):(o(),q)}}};function Oe(e,{readSavedCards:t,getSavedCardSelector:n}){return t()?.find(({instrument:o})=>o.id===e)?.usable?{status:"ready",negotiation:{include:["paymentLines","billingAddress"],loading:["paymentLines"],fieldsToResolve:["paymentLines"]},async apply(){const o=n?.();return o&&await o(e)?q:{status:"failed"}}}:{status:"rejected",field:"payment"}}function gi(e,{readSavedCards:t}){return!!t()?.some(({instrument:n,usable:i})=>n.id===e&&n.selected&&i)}function vi(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(),q):{status:"failed"}}}}function fe({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(ki):[],a=new Map;for(const c of i.deliveryLines.peek()){const{id:l,targetMerchandiseLines:u,deliveryMethodTypes:p,deliveryMethodHandle:f}=c.peek();if(p.filter(K).length===0)continue;const m=(s.find(A=>!!l&&A.id===l)??s.find(A=>Y(A.targetMerchandiseLines,u.filter(S=>S.requiresShipping).map(C))))?.methods.find(A=>A.handle===f);if(m){if(!K(m.methodType))continue}else if(_n(f,p,m))return{status:"rejected",field:"fulfillmentMethods"};a.set(c,{deliveryLine:c,selectedOptionId:void 0,selectedOptionDetails:void 0})}try{for(const c of Pi(e,i.deliveryLines.peek(),s))a.set(c.deliveryLine,c)}catch(c){if(!(c instanceof O))throw c;return{status:"rejected",field:"fulfillmentMethods",reason:c.reason}}const d=o.fields.mustSelectProvidedShippingRate.peek();return[...a.values()].some(({deliveryLine:c,selectedOptionId:l})=>!yn(c.peek().deliveryMethodHandle,l,d))?{status:"rejected",field:"fulfillmentMethods"}:{status:"ready",negotiation:{include:["deliveryNext"],loading:["deliveryNext"],fieldsToResolve:["deliveryNext"]},async apply(){for(const c of i.deliveryLines.value){const l=a.get(c);if(!l&&(!n||!c.value.deliveryMethodTypes.some(K)))continue;
1const{selectedOptionId:u,selectedOptionDetails:p}=l??{};c.value={...c.peek(),deliveryMethodHandle:u,deliveryMethodOptions:Ni(p),...u===void 0&&{isCustomRate:void 0,customDeliveryStrategy:void 0}}}return q}}}const bi=({discountCodes:e=[]},t)=>{const{checkout:n,source:i}=t,{proposed:o,negotiated:r}=n.proposal,s=new Map,a=[];for(const d of o.discountLines.value){const{discount:c}=d;if(c.type==="code"||c.type==="discountCodeTrigger"){const l=c.title.toUpperCase(),u=s.get(l);u?u.push(d):s.set(l,[d])}else a.push(d)}if(r.fields.canUpdateDiscountCodes.value===!1||i.type==="orderEdit"||i.type==="paymentCollection"){const d=new Set(e.map(l=>l.toUpperCase()));return d.size===s.size&&[...d].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 d=new Set;for(const c of e){const l=c.toUpperCase();if(d.has(l))continue;d.add(l);const u=s.get(l);u?a.push(...u):a.push({title:c,discount:{type:"discountCodeTrigger",title:c}})}return B(()=>{o.discountLines.value=a,o.reduction.value=void 0;const{discountCodeWarningSignal:c,currentDiscountCodeAttemptSignal:l}=t.negotiator.context;c.value=null,l.value=null}),q}}},Ai=[yi,bi,ot,fe];function Ue(e,t,{fulfillmentRequest:n,fulfillment:i,locationAddress:o}={}){const r=[];for(const s of Ai){if(s===ot&&n){const{methodTypes:d}=n,{proposed:c}=t.checkout.proposal;r.push({status:"ready",negotiation:{include:["deliveryNext"],loading:["deliveryNext"],fieldsToResolve:["deliveryNext"]},async apply(){return i?i.setDesiredMethod(d,o):o&&(c.locationAddress.value=o),q}})}const a=s===fe?fe(e,t,n!==void 0):s(e,t);if(a!==void 0){if(a.status==="rejected")return st(a.field,a.reason);r.push(a)}}return r}class rt{#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:(B(()=>{r?.apply(),o?.apply()}),{status:"applied"})}#t(t){const{checkout:n}=this.#e;if(!U(n))return;const i=t===void 0?void 0:ee(t,n.address);return{apply({replacement:o=!1}={}){if(!U(n))return!1;const{proposed:r,negotiated:s,facts:a}=n.proposal,d=s.fields.isShippingRequired.value===!1;if(i&&!Ot(i)&&(d||!wi(i,n)))return B(()=>{r.billingAddress.value=i,r.billingAddressOption.value="custom"}),!0;if(o&&d)return a.billingAddress||mi(r)?!1:(B(()=>{r.billingAddress.value=ee({address_country:r.billingAddress.value.countryCode},n.address),r.billingAddressOption.value="custom"}),!0);const c=r.billingAddressOption.value;return r.billingAddressOption.value="shipping",i!==void 0||c!=="shipping"}}}#n(t){const{checkout:n,shop:i,paymentInstrument:o}=this.#e;if(!U(n)||!t&&!o.value)return;const{proposed:r,negotiated:s}=n.proposal,a=s.fields.paymentMethods.value,d=r.paymentLines.value.find(l=>!l.due&&l.method.type==="direct"),c=Ut(a??[],d?.method.type==="direct"&&!!d.method.alternative);return t&&(t.handler_id==="shopify.card"?!c:!i.hasFlagEnabled(xt)||!Ht(a))?Ti():{apply(){U(n)&&B(()=>{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&&c?(d?.method.type!=="direct"||d.method.paymentMethodIdentifier!==c.paymentMethodIdentifier)&&(r.paymentLines.value=Se(r.paymentLines.value,{method:{type:"direct",paymentMethodIdentifier:c.paymentMethodIdentifier,alternative:c.alternative}},we(i))):t.handler_id==="shop_pay"&&t.credential?.approval_id&&(r.paymentLines.value=Se(r.paymentLines.value,{method:{type:"shopWallet",shopPayApprovalId:t.credential.approval_id}},we(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,o=t.payment&&"billing_address"in t.payment?t.payment.billing_address:void 0;if(await this.loadAddressMetadata(["saved_address_id"in i?void 0:i,U(this.#e.checkout)?o:void 0]),n?.())return E();if(this.#e.isSubmitting.value)return $();const r=t.payment&&"instrument_id"in t.payment?t.payment.instrument_id:void 0;if(r!==void 0&&(await this.#e.waitForPendingNegotiations(),n?.()))return E();let s=z(t.declaredFields,this.#e.declaredFields);if("error"in s)return s;if(s.some(({changed:h})=>h)){if(await this.#e.waitForPendingNegotiations(),n?.())return E();if(this.#e.isSubmitting.value)return $();if(s=z(t.declaredFields,this.#e.declaredFields),"error"in s)return s}let a=this.#e.getFulfillmentController?.(),d=oe(t,this.#e,a);if(d&&"error"in d)return d;let c;if(d?.needsLocalityLookup&&t.context){try{const h=this.#e.resolvePickupLocality;if(!h)throw new se;c=await h(t.context)}catch(h){return this.#e.observability.error(h instanceof se?h:new se(h)),n?.()?E():{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 E();if(!c)return{error:{code:"rejected",message:"context: Could not resolve a unique postal locality. Nothing was applied. Check address_country, address_regi
1on and postal_code, then retry."}};if(s=z(t.declaredFields,this.#e.declaredFields),"error"in s)return s}if(t.context){const h=this.#e.checkout.proposal.proposed.locationAddress.value;pe(h,t.context)&&(c=h)}if(a=this.#e.getFulfillmentController?.(),d=oe(t,this.#e,a),d&&"error"in d)return d;let l=this.#t(o);const u=t.payment&&"handler_id"in t.payment?t.payment:void 0;let p=this.#n(u);if(p&&"error"in p)return p;let f=r===void 0?void 0:Oe(r,this.#e);if(f?.status==="rejected")return st(f.field);let y=Ue(t,this.#e,{fulfillmentRequest:d,fulfillment:a,locationAddress:c});if("error"in y)return y;if(n?.())return E();const g=[];let m=!1;for(const h of["negotiate","stage"]){if(h==="stage"&&m&&(s=z(t.declaredFields,this.#e.declaredFields),"error"in s))return E();for(const I of s)if(!(I.phase!==h||!I.changed)){if(n?.())return E();try{if(!await I.apply()||n?.())return E()}catch{return E()}if(I.phase==="stage")g.push(I.negotiation);else if(m=!0,a=this.#e.getFulfillmentController?.(),d=oe(t,this.#e,a),d&&"error"in d||(y=Ue(t,this.#e,{fulfillmentRequest:d,fulfillment:a,locationAddress:c}),"error"in y)||(l=this.#t(o),p=this.#n(u),p&&"error"in p)||(f=r===void 0?void 0:Oe(r,this.#e),f?.status==="rejected"))return E()}}if(p){const h=p;y.push({status:"ready",negotiation:{include:["paymentLines"],loading:["paymentLines"],fieldsToResolve:["paymentLines"]},async apply(){return h.apply(),q}})}if(!f&&y.length===0&&g.length===0&&!l)return{status:"applied"};if(n?.())return E();if(this.#e.isSubmitting.value)return $();if((await Promise.all(B(()=>y.map(h=>h.apply())))).find(h=>h.status==="failed")||n?.())return E();if(this.#e.isSubmitting.value)return $();if(f){if((await f.apply()).status==="failed"||n?.()||(await this.#e.waitForPendingNegotiations(),n?.()))return E();if(this.#e.isSubmitting.value)return $()}const w=l?.apply({replacement:!0})??!1;if(!f&&y.length===0&&g.length===0&&!w)return{status:"applied"};const v=await this.#i(Ei([...y.map(h=>h.negotiation),...g,...f?[f.negotiation]:[],...w?[{include:["billingAddress"],loading:["billingAddress"],fieldsToResolve:["billingAddress"]}]:[]]));await this.#e.waitForPendingNegotiations();const b=Ci(v);if(r!==void 0&&!gi(r,this.#e))return E();if(!("error"in b)&&!n?.()&&d?.needsLocalityLookup&&c&&t.context&&pe(this.#e.checkout.proposal.proposed.locationAddress.value,t.context)){const{proposed:h}=this.#e.checkout.proposal,I=h.deliveryLines.value.map(x=>x.value),R=Ce(h.merchandiseLines.value,I),N=ue(I,R);N.length&&N.every(M)&&this.#e.announcePickupLocality?.(c)}return n?.()?E():b}async loadAddressMetadata(t){const n=new Set;for(const o of t){const r=o?.address_country?.toUpperCase();o&&r&&Ii(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 se extends Error{constructor(t){super("WebMCP pickup locality lookup failed",{cause:t}),this.name="WebMcpLocalityLookupError"}}function Ii(e,t){const n=!!(t.street_address||t.street_name||t.street_number),i=!!(t.extended_address||t.district),o=ge(e,"")!==null,r=ve(e,"")!==null;return n&&o||i&&r}function Ei(e){return{include:ae(e,"include"),loading:ae(e,"loading"),fieldsToResolve:ae(e,"fieldsToResolve")}}function ae(e,t){return[...new Set(e.flatMap(n=>n[t]))]}function Ci(e){return e?.status==="success"||e?.status==="error"?{status:"applied"}:E()}function $(){return{error:{code:"completion_in_progress",message:"A credentialed completion is in progress. Wait for it to finish before updating payment."}}}function Ti(){return{error:{code:"invalid_request",message:"This checkout does not accept the supplied payment handler. Call get_checkout for the current checkout state."}}}function E(){return{error:{code:"update_failed",message:J}}}const Si={context:"context",buyer:"buyer",discountCodes:"discounts",declaredFields:"declared_fields",shippingAddress:"fulfillment",fulfillmentMethods:"fulfillment",payment:"payment"};function wi(e,t){const n=Ae(t.proposal.proposed.shippingAddress.value,t.address);return qt(e,ee(n,t.address))}function st(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 ${Si[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 O 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"?Di(i,t,n):i.groups.map(o=>{const r=at(o,n),s=r.methods.find(({handle:a,methodType:d})=>a===o.selected_option_id&&(d==="SHIPPING"||d==="LOCAL"));if(!s||W(r)!=="shipping")throw new O("unknown_fulfillment_option");return he(r,s,o.selected_option_details,t)}))}function Di(e,t,n){const i=e.selected_destination_id===void 0?void 0:et(n).find(({id:r})=>r===e.selected_destination_id);if(e.selected_destination_id!==void 0&&!i)throw new O("unknown_pickup_destination");const o=new Map;for(const r of e.groups){if(r.selected_option_id!==le)throw new O("unknown_fulfillment_option");const s=at(r,n);if(W(s)!=="pickup"||i&&!i.selections.some(a=>a.line===s)||o.has(s))throw new O("unknown_fulfillment_group");o.set(s,r)}return i?i.selections.map(({line:r,method:s})=>he(r,s,o.get(r)?.selected_option_details,t)):[...o].map(([r,s])=>{const a=r.methods.find(d=>d.handle===r.selectedDeliveryMethodHandle&&M(d.methodType)&&d.pickupLocation);if(!a)throw new O("unknown_pickup_destination");return he(r,a,s.selected_option_details,t)})}function at(e,t){const n=t.find(i=>!!e.id&&i.id===e.id)??t.find(i=>Y(i.targetMerchandiseLines,e.line_item_ids));if(!n)throw new O("unknown_fulfillment_group");return n}function he(e,t,n,i){const o=i.find(r=>!!e.id&&r.value.id===e.id)??i.find(r=>Y(r.value.targetMerchandiseLines,e.targetMerchandiseLines?.filter(s=>s.requiresShipping).map(C)));if(!o)throw new O("unknown_fulfillment_group");if(!o.value.deliveryMethodTypes.includes(t.methodType))throw new O("unsupported_fulfillment_transition");return Li(t,n),{deliveryLine:o,selectedOptionId:t.handle,selectedOptionDetails:n}}function Li(e,t){if(t){if(t.instructions!==void 0&&!te(e,"instructions"))throw new O("unsupported_option_instructions");
1if(t.phone_number!==void 0&&!te(e,"phone_number"))throw new O("unsupported_option_phone")}}function Ni(e){return{phone:e?.phone_number,instructions:e?.instructions}}function ki(e){return e.status==="available"}const xe=gt()(["shipping","pickup"]);class _ extends Error{constructor(t,n,i){super(`${t}: expected ${n}, got ${i} instead.`),this.name="UpdateCheckoutInputError"}}const dt='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.',ct={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)."}},Mi={type:"object",description:`Replacement address. Include all fields to retain; omitted fields are cleared. Use PUT semantics, not PATCH. ${dt}`,properties:ct},Q={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:Mi}}}}};function Ri(e,{ignorePayment:t=!1}={}){const n=D(e,"input");return _e({object:n,allowedFields:["payment"],path:"input"}),t||n.payment===void 0?{}:{payment:lt(n.payment,{path:"input.payment",requireCredential:!0})}}function lt(e,{path:t,requireCredential:n=!1,savedPaymentMethodsOnly:i=!1}){const o=D(e,t);if(!n&&(o.instruments===void 0||Array.isArray(o.instruments)&&o.instruments.length===0))return;const r=`${t}.instruments[0]`,s=Ki(o.instruments,`${t}.instruments`);if(!n&&i)return Bi(s,r);const a=s.handler_id;if(!n&&a===void 0&&s.credential===void 0){const y=He(s,r);return y===void 0?void 0:{billing_address:y}}if(a!=="shopify.card"&&a!=="shop_pay")throw new _(`${r}.handler_id`,"shopify.card or shop_pay","an unsupported handler");const d=H(s,{id:void 0,type:void 0},r),c=a==="shopify.card"?"card":"shop_pay";if(d.type!==void 0&&d.type!==c)throw new _(`${r}.type`,c,"an unsupported instrument type");const l=He(s,r),u={id:d.id??$t(),...l===void 0?{}:{billing_address:l}},p=`${r}.credential`,f=!n&&s.credential===void 0?void 0:D(s.credential,p);if(a==="shopify.card"){if(f===void 0)return{...u,handler_id:a,type:"card"};if(_e({object:f,allowedFields:["type","token"],path:p}),f.type!==void 0&&f.type!=="shopify_token")throw new _(`${p}.type`,"shopify_token","an unsupported credential type");return{...u,handler_id:a,type:"card",credential:{type:"shopify_token",...n||f.token!==void 0?{token:me(f.token,`${p}.token`)}:{}}}}if(f===void 0)return{...u,handler_id:a,type:"shop_pay"};if(_e({object:f,allowedFields:["type","approval_id"],path:p}),f.type!==void 0&&f.type!=="shop_token")throw new _(`${p}.type`,"shop_token","an unsupported credential type");return{...u,handler_id:a,type:"shop_pay",credential:{type:"shop_token",...n||f.approval_id!==void 0?{approval_id:me(f.approval_id,`${p}.approval_id`).trim()}:{}}}}function me(e,t){if(typeof e!="string"||e.trim().length===0)throw new _(t,"a non-empty string",T(e));return e}function He(e,t){if(e.billing_address!==void 0)return H(e.billing_address,pt,`${t}.billing_address`)}function _e({object:e,allowedFields:t,path:n}){if(Object.keys(e).some(i=>!t.includes(i)))throw new _(n,"only supported fields","extra properties")}
1const ut={email:"",phone_number:""},G={first_name:"",last_name:"",phone_number:"",street_address:void 0,extended_address:void 0,address_locality:"",address_region:"",address_country:"",postal_code:""},pt={...G,company:void 0,street_name:void 0,street_number:void 0,district:void 0},qe={phone_number:void 0,instructions:void 0};function Oi(e,t={}){const n=Hi(e,t);return xi(Ui(),n)}function Ui(){return{buyer:{...ut},discountCodes:[],declaredFields:[],shippingAddress:{...G},fulfillmentMethods:{methods:[]},payment:void 0}}function xi(e,t){return{...e,...t,buyer:{...e.buyer,...t.buyer}}}function Hi(e,t){const n=D(D(e,"input").checkout,"input.checkout"),i={};if(n.context!==void 0){const o="input.checkout.context",r=H(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=H(n.buyer,ut,"input.checkout.buyer")),n.discounts!==void 0&&(i.discountCodes=ji(n.discounts)??[]),n.declared_fields!==void 0&&(i.declaredFields=Fi(n.declared_fields)),n.fulfillment!==void 0&&Object.assign(i,$i(n.fulfillment)),!t.ignorePayment&&n.payment!==void 0&&(i.payment=lt(n.payment,{path:"input.checkout.payment",savedPaymentMethodsOnly:t.savedPaymentMethodsOnly})),i}const qi=new Set(["purpose","title","description","value_schema","presentation","required"]);function Fi(e){const t="input.checkout.declared_fields";if(!Array.isArray(e))throw new _(t,"an array",T(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)&&!qi.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",T(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 Bi(e,t){for(const n of Object.keys(e))if(!["id","type","selected","display"].includes(n))throw new _(`${t}.${n}`,"a saved instrument id from get_checkout, not new payment data","an unsupported field");return{instrument_id:me(e.id,`${t}.id`)}}function ji(e){const t="input.checkout.discounts",{codes:n}=D(e,t);if(n!==void 0){if(!ft(n))throw new _(`${t}.codes`,"an array of strings",T(n));return n}}function $i(e){const t="input.checkout.fulfillment",n=D(e,t);if(!Array.isArray(n.methods))throw new _(`${t}.methods`,"an array",T(n.methods));if(n.methods.length>1)throw new _(`${t}.methods`,"at most 1 fulfillment method",`${n.methods.length} methods`);let i={...G};const o=[];for(const[r,s]of n.methods.entries()){const a=`${t}.methods[${r}]`,d=D(s,a),c=Gi(d.type??"shipping",`${a}.type`),{id:l}=H(d,{id:void 0},a),u={...l!==void 0&&{id:l}},p=d.groups===void 0?[]:zi(d.groups,`${a}.groups`),f=Wi(d,a);switch(c){case"pickup":{f===void 0&&Yi(d.destinations,`${a}.destinations`),o.push({...u,type:c,...f!==void 0&&{selected_destination_id:f},groups:p});break}case"shipping":{i=f===void 0?Vi(d,a):{saved_address_id:f},o.push({...u,type:c,groups:p});break}default:yt(c)}}return{shippingAddress:i,fulfillmentMethods:{methods:o}}}function Gi(e,t){const n=xe.find(i=>i===e);if(n!==void 0)return n;throw new _(t,xe.map(i=>JSON.stringify(i)).join(" or "),typeof e=="string"?JSON.stringify(e):T(e))}function Yi(e,t){if(e!==void 0){if(!Array.isArray(e))throw new _(t,"an array",T(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',T(o.type))}}}function Wi(e,t){if(e.selected_destination_id===null)return;const{selected_destination_id:n}=H(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 Vi(e,t){const n=`${t}.destinations[0]`,i=`${t}.destinations`,{destinations:o}=e;if(o===void 0)return{...G};if(!Array.isArray(o))throw new _(i,"an array",T(o));if(o.length===0)return{...G};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{...G,...H(r,pt,n)}}function zi(e,t){if(!Array.isArray(e))throw new _(t,"an array",T(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",T(s));const d=r.id;if(typeof d!="string")throw new _(`${o}.id`,"a string",T(d));const c=r.line_item_ids;if(c!==void 0&&!ft(c))throw new _(`${o}.line_item_ids`,"an array of strings",T(c));const l={...qe,...H(a===void 0?{}:a,qe,`${o}.selected_option_details`)};return[{id:d,line_item_ids:c,selected_option_id:s,selected_option_details:l}]})}function D(e,t){if(!Xi(e))throw new _(t,"an object",T(e));return e}function Xi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ki(e,t){if(!Array.isArray(e))throw new _(t,"an array",T(e));if(e.length!==1)throw new _(t,"1 item",`${e.length} items`);return D(e[0],`${t}[0]`)}function H(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",T(s));o[r]=s}return o}function ft(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function T(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"an array":typeof e=="object"?"an object":`a ${typeof e}`}const Te="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.",Ji={type:"object",additionalProperties:!1,properties:{payment:{...Q,required:["instruments"],properties:{instruments:{...Q.properties.instruments,minItems:1,items:{...Q.properties.instruments.items,required:["handler_id","credential"]}}}}}},de="Checkout is still initializing. Retry shortly. Do not attempt to complete the checkout by interacting with the page.",X="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 Qi extends Error{constructor(){super("WebMCP complete_checkout failed"),this.name="WebMcpCompleteCheckoutError"}}function Fe(e){return!!(e?.handler_id==="shopify.card"?e.credential?.token:e?.credential?.approval_id)}function Zi({isSubmitting:e,paymentInstrument:t,signal:n,checkout:i,shop:o,readCheckout:r,readSavedCards:s,shopPay:a,source:d,observability:c,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. To change the saved Shop Pay card, select an available instrument using update_checkout first. 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, which may still be processing, or an error. Use get_checkout to verify the outcome; do not resubmit while status is complete_in_progress or completed. A status of completed means the order was successfully placed. If buyer_action_required is returned, ask the buyer to follow the returned instructions on the page; do not act on their behalf. ${Te}`,inputSchema:Ji,annotations:{consequentialHint:!0,readOnlyHint:!1,untrustedContentHint:!0},execute:async y=>V(await f(y),i)};async function f(y){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(!o.hasFlagEnabled(Gt))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:g}=Ri(y,{ignorePayment:!U(i)}),m=i.latestReceipt.value?.status;if(m==="processing"||m==="processing_remote_checkouts"||m==="polling_for_order"||m==="processed"||m==="action_required")return r()??{error:{code:"completion_failed",message:X}};const A=l();if(!A||n?.aborted)return{error:{code:"internal_error",message:de}};if(U(i)&&(g||t.value)){if(await A.waitForPendingNegotiations(),n?.aborted)return{error:{code:"internal_error",message:de}};const b=U(i)?g??t.value:void 0;if(b&&g&&!i.isPaymentRequired.value)return{error:{code:"invalid_request",message:"This checkout requires no payment. Retry complete_checkout without the payment field."}};if(b&&Fe(b)&&i.isPaymentRequired.value){const h=new rt({isSubmitting:e,paymentInstrument:t,checkout:i,shop:o,shopPay:a,source:d,observability:c,declaredFields:u,...A,readSavedCards:s});if(g&&(await h.loadAddressMetadata([g.billing_address]),n?.aborted))return{error:{code:"internal_error",message:de}};const I=h.writePayment({payment:b,applyBilling:g!==void 0});if("error"in I)return I}}let S=!1,w=!1;try{e.value=U(i)&&i.isPaymentRequired.value&&Fe(t.value),await A.journey.progress("web-mcp-complete-checkout",b=>{S=b.status==="success"||b.status==="alreadyCompleted",w||="negotiated"in b||"receipt"in b})}finally{e.value&&w&&(t.value=void 0),e.value=!1}const v=r();return!S&&!v?.messages?.some(b=>b.type==="error"&&b.severity==="requires_buyer_input")?{error:{code:"completion_failed",message:X}}:v??{error:{code:"completion_failed",message:X}}}catch(g){return g instanceof _?{error:{code:"invalid_request",message:`${g.message} Correct the input and retry. Do not attempt to complete the checkout by interacting with the page.`}}:(c.error(new Qi),{error:{code:"internal_error",message:X}})}finally{p=!1}}}const eo="Checkout data is not available yet. Retry shortly. Do not attempt to read checkout state by interacting with the page.",to="Unable to read the checkout. Do not attempt to read checkout state by interacting with the page.";
1class no extends Error{constructor(){super("WebMCP get_checkout failed to read the checkout"),this.name="WebMcpGetCheckoutError"}}function io({checkout:e,readCheckout:t,observability:n}){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. Available Shop Pay saved cards are reported under payment.instruments for selection by id; raw credentials and security codes are never reported. 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. ${Te}`,inputSchema:{type:"object",properties:{}},annotations:{consequentialHint:!1,readOnlyHint:!0,untrustedContentHint:!0},execute:()=>V(i(),e)};function i(){try{const o=t(e.latestReceipt.value?.status==="processed"?"negotiated":"proposed");return o||{error:{code:"internal_error",message:eo}}}catch{return n.error(new no),{error:{code:"internal_error",message:to}}}}}const oo=3e4;class ro extends Error{constructor(t){super("WebMCP navigate_to_storefront failed",{cause:t}),this.name="WebMcpStorefrontNavigationError"}}function ht({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 so({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(d,c)=>V(await s(d,c?.signal??o),e)};async function s(d,c){let l;try{if(d===null||typeof d!="object"||Array.isArray(d)||Object.keys(d).length>0)return{error:{code:"invalid_request",message:"navigate_to_storefront takes no input. Retry with an empty object."}};if(c.aborted||o.aborted)return Be();const u=r();if(!u)return{error:{code:"internal_error",message:"Checkout is still initializing. Retry shortly."}};if(a(u))return je();const p=ht({shop:t,url:n});if(!p)return ao();const f=new Promise(g=>{l=setTimeout(()=>g("timeout"),oo)}),y=await Promise.race([u.waitForPendingNegotiations(),f]);return c.aborted||o.aborted?Be():y==="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)?je():(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 ro(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:d}){const c=e.latestReceipt.value;return d.completing.value||d.progressing.value||c!=null&&!["processed","failed","abandoned"].includes(c.status)}}function Be(){return{error:{code:"navigation_failed",message:"Navigation was cancelled. The tool did not leave checkout."}}}function je(){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 ao(){return{error:{code:"navigation_failed",message:"A supported storefront destination is not available. Stay on the current checkout."}}}const $e=3e4,Ge="Checkout is not available for updates. Retry shortly. Do not attempt to update the checkout by interacting with the page.",co="Correct the input and retry. Do not attempt to update the checkout by interacting with the page.",lo={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."}
1,address_region:{type:"string",description:"Province or region code."},postal_code:{type:"string"}}},payment:{...Q,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. ${dt}`,properties:ct}},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"}}}}}}}}}}}}}}},uo="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. In Shop Pay, select one payment.instruments entry by its id from get_checkout, or omit payment to keep the current card; new payment credentials are not accepted. 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.";class po extends Error{constructor(){super("WebMCP update_checkout failed to apply"),this.name="WebMcpUpdateCheckoutError"}}function fo({isSubmitting:e,paymentInstrument:t,signal:n,checkout:i,shop:o,shopPay:r,source:s,router:a,getSavedCardSelector:d,readCheckout:c,readSavedCards:l,observability:u,getPreactContext:p,declaredFields:f,getFulfillmentController:y}){return{name:"update_checkout",title:"Update checkout",description:`${uo} ${Te}`,inputSchema:lo,annotations:{consequentialHint:!1,readOnlyHint:!1,untrustedContentHint:!0},execute:async m=>V(await g(m),i)};async function g(m){let A;
1try{if(e.value)return $();const S=i.identity.current.value==="shopPay",w=Oi(m,{savedPaymentMethodsOnly:S,ignorePayment:S?!i.isPaymentRequired.value:!U(i)}),v=p();if(!v||n?.aborted)return{error:{code:"internal_error",message:Ge}};if(a.currentUrl.value.normalizedPath==="/review"&&a.navigate("/"),w.payment&&"instrument_id"in w.payment&&!d())return{error:{code:"internal_error",message:Ge}};const{loadPickupLocalityServices:b}=v;let h;const I=new rt({isSubmitting:e,paymentInstrument:t,checkout:i,shop:o,shopPay:r,source:s,getSavedCardSelector:d,observability:u,declaredFields:f,...v,readSavedCards:l,getFulfillmentController:y,resolvePickupLocality:b?async F=>(h=await b(),h.resolvePickupLocality(F)):void 0,announcePickupLocality:F=>h?.announcePickupLocality(F),get negotiator(){return v.negotiator}});let R=!1;const N=new Promise(F=>{A=setTimeout(()=>{R=!0,F("timeout")},$e)}),x=await Promise.race([I.applyUpdate(w,{isExpired:()=>R||!!n?.aborted}),N]);return x==="timeout"?(u.log("web_mcp_update_timed_out","[WebMcp] Update did not finish in time; update outcome is unknown",{timeoutMs:$e}),{error:{code:"update_failed",message:J}}):"error"in x?x:c()??{error:{code:"update_failed",message:J}}}catch(S){return S instanceof _?{error:{code:"invalid_request",message:`${S.message} ${co}`}}:(u.error(new po),{error:{code:"internal_error",message:J}})}finally{clearTimeout(A)}}}function ho(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="object"}function mo(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 ye(e,t,n,i){const o=Math.round(performance.now()-i),r=ho(n),s={tool:t,outcome:r?"error":"success",...r&&{errorCode:mo(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 Ye(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=V({error:{code:"checkout_busy",message:"Another checkout tool is running. Wait for it to finish before retrying."}},i);return ye(n,o,a,s),a}return t.during(o,async()=>{const a=await e.execute(...r);return ye(n,o,a,s),a})}}}function _o(e,t){const n=e.name;return{...e,execute:(...i)=>{const o=performance.now(),r=e.execute(...i);return ye(t,n,r,o),r}}}class yo extends Error{constructor(t,n){super(`WebMCP tool registration failed for ${t}: ${String(n)}`),this.name="WebMcpRegistrationError",n instanceof Error&&(this.cause=n)}}function go(e,t){const n=new AbortController,i=vt(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 vo({modelContext:e,signal:t,isSubmitting:n,paymentInstrument:i,checkout:o,i18n:r,shop:s,shopPay:a,source:d,url:c,router:l,observability:u,activeTool:p,onActiveToolCreated:f,getPreactContext:y,markToolCallStarted:g,getSavedCardSelector:m,declaredFields:A,getFulfillmentProvider:S,unregisterInitializingTool:w}){if(t.aborted)return;const v=fi({checkout:o,shopPay:a}),b=L=>Zn({checkout:o,i18n:r,shop:s,router:l,readMode:L,savedCards:v(),declaredFields:A,paymentInstrument:i.value}),h=ci(o);A.set(h.key,h);const I=p??new zt;f?.(I);const N=[{tool:_o(io({checkout:o,readCheckout:b,observability:u}),u),signal:t}],x=go(o,t);x.aborted||N.push(...[fo({isSubmitting:n,paymentInstrument:i,signal:t,checkout:o,shop:s,shopPay:a,source:d,router:l,getSavedCardSelector:m,readCheckout:b,readSavedCards:v,observability:u,getPreactContext:y,declaredFields:A,getFulfillmentController:()=>{const L=S?.();return L?li(L,o.proposal):void 0}}),Zi({isSubmitting:n,paymentInstrument:i,signal:t,checkout:o,shop:s,shopPay:a,source:d,readCheckout:b,readSavedCards:v,observability:u,getPreactContext:y,declaredFields:A})].map(L=>({tool:Ye(L,{activeTool:I,observability:u,checkout:o}),signal:x}))),ht({shop:s,url:c})&&N.push({tool:Ye(so({checkout:o,shop:s,url:c,observability:u,signal:t,getPreactContext:y}),{activeTool:I,observability:u,checkout:o}),signal:t}),w?.();const F=N.map(({tool:L,signal:j})=>e.registerTool({...L,execute(ne,mt){return g(),L.execute(ne,mt)}},{signal:j}).then(()=>"registered",ne=>j.aborted?"withdrawn":(u.error(new yo(L.name,ne)),"failed")));return Promise.all(F).then(L=>{t.aborted||u.log("web_mcp_tools_registered","[WebMcp] tools registered",{registered:L.filter(j=>j==="registered").length,failed:L.filter(j=>j==="failed").length})}).catch(()=>{}),I}
1const To=Object.freeze(Object.defineProperty({__proto__:null,registerWebMcpTools:vo},Symbol.toStringTag,{value:"Module"}));export{Re as n,To 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.