1import{ah as e,w as t,n,M as i,I as o,ac as s}from"./2c1ab0fe.qpvfywqb.js";import{i as r}from"./41e85f1e.BBeZocPi.js";import{gX as a,h8 as d,gY as c,h9 as l,ha as u,fz as p,gD as h,az as m,hb as f,bu as y,f3 as _,gH as g,gf as v,L as b,ae as k,hc as C,bB as w,hd as A,he as S,hf as I,bz as T,hg as E,cZ as N,c_ as P,d0 as L,dp as D,a2 as M,dn as R,ce as O,hh as x,hi as U,hj as q}from"./4b4bc88f.DkycdxSK.js";import{i as j}from"./9dba8418.4R19B40l.js";import{c as $,a as H}from"./f67abd2c.CNaB0QaR.js";import{r as B}from"./9ce08e25.dSvNrRyM.js";import{c as F}from"./cadec7c0.Dr7b1Jee.js";import{h as G,a as Y,i as W}from"./6a2fc6d6.D4Q9fE76.js";import{i as z}from"./8599b02a.D6crYzGJ.js";import{s as X}from"./08a3b809.BKNVX2Vm.js";import{m as V}from"./9655ebc9.CX4pB1Ku.js";import{u as K}from"./app.DH8n-1bp.js";import"./2495faa4.DgGNI16D.js";import"./cf29e63b.B0brOI65.js";import"./cb38e5c2.k1ouuKLe.js";import"./2255f8fa.QeXR1fCM.js";import"./d25d1b95.CoPrVoCi.js";import"./b8733b27.DmG2FsdC.js";import"./e39bc11c.CaER5qTM.js";class J{#e;#t=0;get current(){return this.#e}async during(e,t){this.#e=e,this.#t+=1;try{return await t()}finally{this.#t-=1,0===this.#t&&(this.#e=void 0)}}}const Z=["buyer_action_required","checkout_busy","completion_failed","completion_in_progress","internal_error","invalid_request","navigation_failed","rejected","update_failed"];function Q(e){return"object"==typeof e&&null!==e&&"error"in e}const ee=Symbol("WebMcpFailureDetails");function te(e){if(!Q(e))return;const t=e.error;return"object"==typeof t&&null!==t&&ee in t?t[ee]:void 0}function ne(e,t,n){const i={code:e,message:t};return n&&Object.defineProperty(i,ee,{value:n}),{error:i}}function ie(e){return`Do not attempt to ${e} by interacting with the page.`}const oe="Retry shortly.",se=`Checkout is still initializing. ${oe}`,re="Nothing was applied.",ae=`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. ${ie("update the checkout")}`,de=`Checkout completion could not be confirmed. Call get_checkout for the current state and its messages before retrying. ${ie("complete the checkout")}`;function ce(e,t,n,i="Call get_checkout before retrying."){return ne(e,`${t}: ${n} ${re} ${i}`)}function le(e,t){return ne("invalid_request",`${e.message} Correct the input and retry. ${ie(t)}`,{invalidInputPath:e.loggablePath.replace(/\[\d+\]/g,"[]"),invalidInputExpected:e.expected})}function ue(){return ne("internal_error",`Checkout is not available for updates. ${oe} ${ie("update the checkout")}`)}function pe(e="update_failed"){return ne(e,ae)}function he(e){return ne("rejected",`The selected delivery option does not support selected_option_details.${e}. ${re} Remove ${e} from selected_option_details or choose an option that supports it, then retry. ${ie("update the checkout")}`)}const me=`${re} Group and option ids come from the latest get_checkout and change when the destination or fulfillment method changes. If the destination and method are unchanged, retry the complete replacement: start from the latest get_checkout, keep every change from the rejected request, and replace only the group and option ids with current ids; omitted buyer, fulfillment, and discount-code values are cleared. If this request also changes the destination, send it without groups, then choose an option from the next get_checkout. ${ie("update the checkout")}`;function fe(e){return ce("rejected","fulfillment",e)}function ye(e,t){return ce("rejected",e,`${t}.`)}function _e(){return ne("completion_in_progress","A credentialed completion is in progress. Wait for it to finish before updating payment.")}function ge(){return ne("internal_error",`${se} ${ie("complete the checkout")}`)}function ve(e="completion_failed",t){return ne(e,de,t)}function be(){return ne("navigation_failed","Navigation was cancelled. The tool did not leave checkout.")}function ke(){return ne("checkout_busy","Checkout submission or payment is in progress. Wait for it to finish and call get_checkout before navigating away.")}function Ce(e,t){const n=e??[],i=new Map;for(const[s,{key:r,value:a}]of n.entries()){const e=`$.checkout.declared_fields[${s}]`,n=t.get(r);if(!n?.read())return ye(`${e}.key`,"must identify a declared field available in the current checkout");const o=n.prepare(a);if("requirement"in o)return ye(`${e}.value`,o.requirement);i.set(r,o)}const o=[];for(const[s,r]of t){if(!r.read())continue;const e=i.get(s)??r.prepare(null);if("requirement"in e)return ye("$.checkout.declared_fields",e.requirement);o.push({...e,get changed(){return e.changed},apply:async()=>!(t.get(s)!==r||!r.read())&&e.apply()})}return o}function we(t){if(!t)return 0;const n=e(t.currencyCode),i=new Intl.NumberFormat("en",{style:"decimal",useGrouping:!1,minimumFractionDigits:n,maximumFractionDigits:n}),[o,s=""]=i.format(t.amount).split(".");return Number(o+s.padEnd(n,"0"))}function Ae(e,t){const{discount:n}=e,i=[];let o=0,s=!1;for(const{target:d}of e.allocations){let e=d.index;if("MERCHANDISELINE"===d.type&&t&&(e=null==d.stableId?void 0:t.get(d.stableId),null==e)){s=!0;continue}const n=we(d.amount);o+=n,"MERCHANDISELINE"===d.type&&null!=e?i.push({path:`$.line_items[${e}]`,amount:n}):"DELIVERYLINE"===d.type&&i.push({path:"$.totals.shipping",amount:n})}const r="code"===n.type&&n.codeHidden,a=s?0:we(e.amount);return{title:r?"Discount":n.title,amount:o||a,..."code"===n.type&&!r&&{code:n.title},..."code"!==n.type&&{automatic:!0},..."EACH"===n.allocationMethod&&{method:"each"},..."ACROSS"===n.allocationMethod&&{method:"across"},...i.length>0&&{allocations:i}}}function Se(e,{extendedAddressMode:t}){const n=e.address_country?.toUpperCase()??"",i=t.get(n),o=null===i?function(e,t){const n=Te(t);return{address1:"line"in n?n.line:xe(e,n),address2:t.extended_address??""}}(n,e):function(e,t,n){const{packedLine2:i,...o}=function(e,t){if("line"in t){const n=a(e,t.line,!0);if(!n?.streetNumber)return{address1:t.line};const i=d({countryCode:e,streetName:n.streetName??"",streetNumber:n.streetNumber});return null==i?{address1:t.line}:{address1:i,packedLine2:n.line2}}const n=d({countryCode:e,...t});return null==n?{address1:Ue(t)}:{address1:n,...t}}(e,Te(t)),{neighborhood:s,...r}=function(e,{extended_address:t="",district:n},i){const o=c(e,t);if(!o)return{address2:Ee(t,i)};const s=Ee(o.line2??"",i),r=n??o.neighborhood??"";return{address2:Oe(e,s,r),line2:s,neighborhood:r}}(e,t,i);return{...o,...r,..."dedicated"===n?void 0!==s&&{district:s,neighborhood:""}:{neighborhood:s}}}(n,e,i);return{...F({...e,street_address:o.address1,extended_address:o.address2}),company:e.company??"",district:void 0,subdistrict:void 0,...o}}function Ie(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,...null===i?Ne(n,e):De(n,e,i),address_locality:e.city,address_regi
1on:e.zoneCode,address_country:e.countryCode,postal_code:e.postalCode}}function Te({street_address:e="",street_name:t,street_number:n=""}){return t?.trim()?{streetName:t,streetNumber:n}:{line:e}}function Ee(e,t){return t&&t!==e.trim()?qe(e,t):e}function Ne(e,t){return{street_address:Pe(e,t),extended_address:Le(e,t)}}function Pe(e,{address1:t,streetName:n,streetNumber:i}){return t||!n&&!i?t:Re(e,{streetName:n??"",streetNumber:i??""})}function Le(e,{address2:t,line2:n,district:i,neighborhood:o}){const s=i||o;return null!=n||s?Oe(e,n??"",s??""):t}function De(e,t,n){const i=function(e,t,n){return"dedicated"!==n||null==t.streetName&&null==t.streetNumber?t.address1?.includes(l)?a(e,t.address1):null:t}(e,t,n);return{...i?.streetName?{street_name:i.streetName,street_number:i.streetNumber??""}:{street_address:Pe(e,t)},...Me(e,t,n)}}function Me(e,t,n){if("dedicated"===n&&(null!=t.line2||null!=t.district)){const e=t.district??t.neighborhood;return{extended_address:t.line2,...null!=e&&{district:e}}}const i=t.address2?.includes(l)?c(e,t.address2):null;return i?{extended_address:i.line2??"",district:i.neighborhood??""}:{extended_address:t.address2||t.line2,..."concatenated"===n&&null!=t.neighborhood&&{district:t.neighborhood}}}function Re(e,t){return d({countryCode:e,...t})??Ue(t)}function Oe(e,t,n){return u({countryCode:e,line2:t,neighborhood:n})??qe(t,n)}function xe(e,t){return Re(e,t).split(l).join("")}function Ue({streetName:e,streetNumber:t}){return[t,e].filter(Boolean).join(" ")}function qe(e,t){return[e,t].filter(Boolean).join(", ")}function je(e){return e?.flatMap(e=>(e.lineComponents.length?e.lineComponents:[e]).filter(e=>e.requiresShipping).map($e))??[]}function $e(e){return e.stableId}function He(e){return"presentationLevel"in e&&"CART"===e.presentationLevel}function Be(e){return"SHIPPING"===e||"LOCAL"===e||p(e)}function Fe(e,t,n){return Boolean(e&&!n&&(t.some(e=>!Be(e))||t.some(p)&&t.some(e=>"SHIPPING"===e||"LOCAL"===e)))}function Ge(e,t){switch(t){case"phone_number":return Boolean(e.phoneRequired);case"instructions":return Boolean(e.acceptsInstructions)}}function Ye(e,t){if(!e?.length||!t?.length)return!1;const n=new Set(t),i=e.filter(e=>e.requiresShipping).map(e=>$e(e));return i.length===n.size&&i.every(e=>n.has(e))}const We="pickup";function ze(e){const t=e.methods.find(({handle:t})=>t===e.selectedDeliveryMethodHandle),n=e.proposedLine?t?.methodType??e.proposedLine.deliveryMethodTypes[0]:(t??e.methods[0])?.methodType;if(n)return p(n)?"pickup":"shipping"}function Xe(e){const[t,...n]=e.filter(e=>"pickup"===ze(e)).map(e=>({line:e,methods:Ve(e)}));if(!t)return[];const i=[];for(const[o,s]of t.methods){const e=[{line:t.line,method:s}];for(const{line:t,methods:i}of n){const n=i.get(o);if(!n)break;e.push({line:t,method:n})}e.length===n.length+1&&i.push({id:s.handle,selections:e})}return i}function Ve(e){const t=new Map;for(const n of e.methods){if(!n.pickupLocation)continue;const i=Ke(n.pickupLocation);t.has(i)&&n.handle!==e.selectedDeliveryMethodHandle||t.set(i,n)}return t}function Ke(e){if("PickupPointLocation"===e.type&&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??""])}const Je=Ie;function Ze(e,t){const n=new Set(t.flatMap(e=>e.targetMerchandiseLines?.map($e)??[])),i=new Map,o=new Set;for(const s of e.merchandiseLines??[]){if("proposed"!==e.readMode&&!s.requiresShipping)continue;const t=$e(s);if(n.has(t)||o.has(t))continue;o.add(t);const r=new Set((s.lineComponents.length?s.lineComponents:[s]).filter(e=>e.requiresShipping&&!n.has($e(e))).map($e));if(!r.size)continue;const a=e.proposedDeliveryLines?.filter(e=>e.targetMerchandiseLines.some(e=>$e(e)===t||r.has($e(e)))).flatMap(e=>e.deliveryMethodTypes),d=a?.length&&a.every(p)?"pickup":"shipping",c=i.get(d)??[];c.push(..."proposed"===e.readMode?r:[t]),i.set(d,c)}return i}function Qe(e){return[...Ze(e,[])].map(([t,n])=>({id:t,type:t,line_item_ids:n,destinations:[],..."shipping"===t?it(e):{},groups:[]}))}function et(e){const t=new Set;for(const n of e){const e=ze(n);e&&t.add(e)}return Array.from(t)}function tt(e){return"SHIPPING"===e||"LOCAL"===e||p(e)}function nt(e,t,n){if("shipping"===e)return it(n);const i=Xe(t);if(!i.length)return{};const o=i.find(({selections:e})=>e.every(({line:e,method:t})=>e.selectedDeliveryMethodHandle===t.handle));return{destinations:i.flatMap(({id:e,selections:[t]})=>{const i=function(e,t){const{pickupLocation:n}=e;return n?{id:e.handle,type:"business_location",name:n.name??"",pickup_location_address:Je(n.address,t)}:void 0}(t.method,n.addressContext);return i?[{...i,id:e}]:[]}),...o&&{selected_destination_id:o.id}}}function it({savedDestinations:e,shippingAddress:t,addressContext:n}){if(void 0===e)return t&&f(t)?{destinations:[ot(t,n)]}:{};const{destinations:i,selectedDestinationId:o}=function(e,t){const n=new Map;for(const s of e)n.has(s.id)||n.set(s.id,s);const i=[...n.values()],o=t?i.find(({address:e})=>h(e,t)):void 0;return{destinations:i,selectedDestinationId:o?.id}}(e,t);return i.length?{destinations:i.map(({id:e,address:t})=>({id:e,type:"shipping_address",...Je(t,n)})),...o&&{selected_destination_id:o}}:{}}function ot(e,t){return{...Je(e,t),id:st(e),type:"shipping_address"}}function st(e){return["shipping",e.countryCode,e.postalCode].filter(
1Boolean).join("-").replace(/\s+/g,"")}function rt(e,t){const n=at(e),i=m(e),o=e.proposedLine?e.selectedDeliveryMethodHandle:i?.handle,s=o?function(e,t,n){const i=function(e,t,n=at(e)){return t?.find(t=>Boolean(e.id)&&t.id===e.id)??t?.find(e=>Ye(e.targetMerchandiseLines,n))}(e,n,t);if(!i||!e.selectedDeliveryMethodHandle||i.deliveryMethodHandle!==e.selectedDeliveryMethodHandle)return;const o=i.deliveryMethodOptions;if(!o)return;const s=m(e),r=s&&!Ge(s,"phone_number")?void 0:o.phone,a=s&&!Ge(s,"instructions")?void 0:o.instructions;return void 0===r&&void 0===a?void 0:{...void 0!==r&&{phone_number:r},...void 0!==a&&{instructions:a}}}(e,n,t):void 0,r="pickup"===ze(e),a=r?[{...i?dt(i):{totals:[]},id:We,title:"Pickup"}]:e.methods.filter(({methodType:e})=>"SHIPPING"===e||"LOCAL"===e).map(dt);return{id:e.id??"",line_item_ids:n,options:a,...o&&{selected_option_id:r?We:o},...s&&{selected_option_details:s}}}function at(e){return e.targetMerchandiseLines?.filter(e=>e.requiresShipping).map(e=>$e(e))??[]}function dt(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:we(e.costAfterDiscounts)}]}}function ct(e){return"available"===e.status}const lt=new Map([["terms-of-service","terms_of_service"],["privacy-policy","privacy_policy"],["refund-policy","refund_policy"],["shipping-policy","shipping_policy"]]);function ut(e){const t=[];for(const{handle:n,url:i}of e){const e=lt.get(n);e&&t.push({type:e,url:i})}return t}const pt={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_USAGE_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 ht(e){return pt[e]}const mt=new Set(["AcceptNewTermViolation","RequiredArtifactsUnavailableViolation"]),ft
1=new Set(["PendingTermViolation"]),yt=new Set(["PAYMENTS_UNACCEPTABLE_PAYMENT_AMOUNT"]),_t={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 gt(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 vt({subtotal:e,itemsDiscountAmount:t,cartLevelDiscountAmount:n,discountLines:i,fulfillmentTotal:o,tax:s,duty:r,dutiesIncluded:a,runningTotal:d}){const c=[];return null!=e&&(c.push({type:"subtotal",display_text:"Subtotal",amount:we(e)}),c.push(...function({currencyCode:e,discountLines:t,itemsDiscountAmount:n,cartLevelDiscountAmount:i}){let o=i;for(const r of t?.lines??[])if(H(r))for(const e of r.allocations)"DELIVERYLINE"===e.target.type&&(o+=e.target.amount.amount);const s=[];return n>0&&s.push({type:"items_discount",display_text:"Discounts",amount:we({amount:-n,currencyCode:e})}),o>0&&s.push({type:"discount",display_text:"Discount",amount:we({amount:-o,currencyCode:e})}),s}({currencyCode:e.currencyCode,discountLines:i,itemsDiscountAmount:t,cartLevelDiscountAmount:n}))),null!=o&&c.push({type:"fulfillment",display_text:"Shipping",amount:we(o)}),null==r||a||c.push({type:"duty",display_text:"Duties",amount:we(r)}),null!=s&&c.push({type:"tax",display_text:"Taxes",amount:we(s)}),null!=d&&c.push({type:"total",display_text:"Total",amount:we(d)}),c}function bt(e){const t=e.merchandiseLines?.lines;if(!t||!function(e){return e.every(e=>null!=e.itemPrice&&null!=e.title)}(t)||null==e.runningTotal)return;const n="proposed"===e.readMode&&0===t.length?{...e.runningTotal,amount:0}:function(e){if(e)return e.reduce((e,t)=>{const{itemPrice:n}=t;if(!n)return e;const i=n.amount*t.quantity;return e?{...e,amount:e.amount+i}:{...n,amount:i}},void 0)}(t)??e.subtotal;if(null==n)return;const{lineItems:i,itemsDiscountAmount:o,cartLevelDiscountAmount:s}=function(e){if(!e?.length)return{lineItems:[],itemsDiscountAmount:0,cartLevelDiscountAmount:0};let t=0,n=0;return{lineItems:e.map(e=>{const{itemPrice:i}=e,o=i?{...i,amount:i.amount*e.quantity}:void 0,{lineLevel:s,cartLevel:r}=function(e){let t=0,n=0;for(const i of e)for(const{discountDetails:e,amount:o}of i.allocations)He(e.discount)?n+=o.amount:t+=o.amount;return{lineLevel:t,cartLevel:n}}(e.lineAllocations),a=[];n+=r,o&&a.push({type:"subtotal",amount:we(o)}),0!==s&&o&&(t+=s,a.push({type:"items_discount",amount:we({...o,amount:-s})}));const d=o?{...o,amount:o.amount-s}:e.totalPrice;return a.push({type:"total",amount:we(d)}),{id:$e(e),...e.parentRelationship?.parent?.stableId?{parent_id:e.parentRelationship.parent.stableId}:{},quantity:e.quantity,item:{id:e.variantId??e.stableId,title:e.title,price:we(i),...e.image?.url?{image_url:e.image.url}:{}},totals:a}}),itemsDiscountAmount:t,cartLevelDiscountAmount:n}}(t),r=function(e){const{deliveryNext:t}=e;if("filled"!==t?.status||!t.lines)return;const n=[];let i;for(const s of t.lines){if("available"!==s.status||!s.selectedDeliveryMethodHandle)continue;const t=m(s);t?.cost&&(n.push({cost:t.costAfterDiscounts.amount,costBeforeDiscounts:t.cost.amount,rateGroupKey:"SHIPPING"===t.methodType?B({line:s,method:t,localShopId:e.shopId,marketDrivenShippingEnabled:e.marketDrivenShippingEnabled,remoteShopsConfigMap:e.remoteShopsConfigMap,remoteMerchandiseDetails:e.remoteMerchandiseDetails}):void 0}),i??=t.cost.currencyCode)}if(null==i)return;const{priceBeforeDiscounts:o}=$(n,({rateGroupKey:e})=>e);return{amount:o,currencyCode:i}}(e),a="processed"===e.receipt?.status&&e.receipt.isRedacted||!e.buyer.email&&!e.buyer.phone_number?void 0:{...e.buyer},d=function(e,t){if(!e?.lines.length)return;const n=t?new Map(t.map(({id:e},t)=>[e,t])):void 0,i=new Map,o=[];for(const s of e.lines){const{discount:e}=s;if("code"===e.type||"discountCodeTrigger"===e.type){const t=e.title.toUpperCase();i.has(t)||i.set(t,e.title)}if("allocations"in s){const e=Ae(s,n);e.amount>0&&o.push(e)}}return{codes:[...i.values()],applied:o}}(e.discountLines,"proposed"===e.readMode?i:void 0),c=function(e){const t=function(e){const{deliveryNext:t}=e;if("proposed"!==e.readMode&&("filled"!==t?.status&&"partial"!==t?.status||!t.lines))return Qe(e);const n="filled"!==t?.status&&"partial"!==t?.status||!t.lines?[]:t.lines.filter(ct),i=("proposed"===e.readMode?function(e,t,n){const i=new Map;for(const o of n??[]){i.set($e(o),je([o]).length>0);for(const e of o.lineComponents)i.set($e(e),e.requiresShipping)}return(t??[]).map(t=>{const n=t.targetMerchandiseLines.filter(e=>e.requiresShipping).map(e=>$e(e)),o=e.find(e=>void 0!==t.id&&e.id===t.id)??e.find(e=>e.type===t.type&&Ye(e.targetMerchandiseLines,n));return{...o,status:"available",id:t.id,type:t.type,targetMerchandiseLines:t.targetMerchandiseLines.flatMap(e=>{const t=i.get($e(e));return void 0===t?[]:[{...e,requiresShipping:t}]}),selectedDeliveryMethodHandle:t.deliveryMethodHandle,methods:o?.methods.filter(e=>t.deliveryMethodTypes.includes(e.methodType))??[],proposedLine:t}})}(n,e.proposedDeliveryLines,e.merchandiseLines):n).filter(e=>(e.proposedLine?e.proposedLine.deliveryMethodTypes.some(tt):e.methods.some(e=>tt(e.methodType)))&&e.targetMerchandiseLines?.some(e=>e.requiresShipping));if("proposed"===e.readMode&&!i.length)return Qe(e);const o="partial"===t?.status?Ze(e,i):new Map,s=new Set([...et(i),...o.keys()]),r=[];for(const a of s){const t=i.filter(e=>ze(e)===a),n=t.map(t=>rt(t,t.proposedLine?[t.proposedLine]:e.proposedDeliveryLines)),s=[...new Set([...n.flatMap(e=>e.line_item_ids),...o.get(a)??[]])];
1r.push({id:a,type:a,line_item_ids:s,destinations:[],...nt(a,t,e),groups:n})}return r}(e);return t.length?{methods:t}:void 0}({readMode:e.readMode,deliveryNext:e.deliveryNext,shippingAddress:e.shippingAddress,merchandiseLines:t,savedDestinations:e.savedDestinations,addressContext:e.addressContext,proposedDeliveryLines:e.proposedDeliveryLines}),{status:l,messages:u}=function(e){const{receipt:t,isShippingRequired:n,hasShippingAddress:i,deliveryNext:o,skipsShippingAddress:s=g(o)}=e,r=function(e){const t=[];for(const n of e.violations??[]){if(mt.has(n.__typename))continue;if(yt.has(n.code))continue;if(e.requiresCaptcha&&v.has(n.code))continue;const i=n.code.startsWith("DISCOUNTS_"),o=i||ft.has(n.__typename),s=ht(n.code)??(o?"checkout_warning":"checkout_error"),r="target"in n?n.target:void 0,a=i?"$.discounts.codes":r;t.push({...o?{type:"warning"}:{type:"error",severity:"recoverable"},code:s,content:gt(n,s,e.i18n),...a?{path:a}:{}})}return"action_required"===e.receipt?.status&&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}(e),a=function({receipt:e,isShippingRequired:t,hasShippingAddress:n,skipsShippingAddress:i,hasUnselectableShippingGroup:o,requiresBuyerReview:s,requiresCaptcha:r}){const a=e?.status;return"processed"===a?"completed":"processing"===a||"processing_remote_checkouts"===a||"polling_for_order"===a?"complete_in_progress":"action_required"===a||r?"incomplete":s?"requires_escalation":!t||n||i?t&&o?"incomplete":"ready_for_complete":"incomplete"}({receipt:t,isShippingRequired:n,hasShippingAddress:i,skipsShippingAddress:s,hasUnselectableShippingGroup:e.hasUnselectableShippingGroup??!1,requiresBuyerReview:e.requiresBuyerReview??!1,requiresCaptcha:e.requiresCaptcha??!1});return"incomplete"===a&&e.requiresCaptcha&&"action_required"!==t?.status&&r.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."}),"requires_escalation"===a&&r.push(_t),{status:a,messages:r}}({i18n:e.i18n,requiresBuyerReview:null!=e.buyerReviewUrl,requiresCaptcha:e.requiresCaptcha,violations:e.violations,receipt:e.receipt,isShippingRequired:"proposed"===e.readMode?je(t).length>0:e.isShippingRequired,hasShippingAddress:"proposed"===e.readMode?f(e.shippingAddress):null!=e.shippingAddress,deliveryNext:e.deliveryNext,skipsShippingAddress:"proposed"===e.readMode?Ct(c,t):void 0,hasUnselectableShippingGroup:kt(c,t,e.readMode)}),p=function(e){if("processed"!==e?.status)return;const t=e.orderIdentity.buyerIdentifier,n=y(e.orderIdentity.id);return{...n?{id:_("Order",n)}:{},...t?{label:t}:{},permalink_url:e.confirmationPage.url}}(e.receipt),h=function(e,t,n){const i=n?.filter(({instrument:e,usable:t})=>e.selected||t).map(({instrument:e})=>e);return i?.length?{instruments:i}:{instruments:e?[{billing_address:Ie(e,t)}]:[]}}(e.billingAddress,e.addressContext,e.savedCards),b=(k=e.savedCards??[]).some(({instrument:e,usable:t})=>e.selected&&!t)?[{type:"error",severity:k.some(({usable:e})=>e)?"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."}]:[];var k;const C=[...u,...b];return{...e.id?{id:e.id}:{},...e.continueUrl?{continue_url:e.continueUrl}:{},currency:e.runningTotal.currencyCode,status:"ready_for_complete"===l&&b.length?"incomplete":l,..."requires_escalation"===l&&e.buyerReviewUrl?{continue_url:e.buyerReviewUrl}:{},links:ut(e.merchantPolicies),line_items:i,totals:vt({subtotal:n,itemsDiscountAmount:o,cartLevelDiscountAmount:s,discountLines:e.discountLines,fulfillmentTotal:r,tax:e.tax,duty:e.duty,dutiesIncluded:e.dutiesIncluded,runningTotal:e.runningTotal}),...a&&{buyer:a},...d&&{discounts:d},...c&&{fulfillment:c},payment:h,...C.length?{messages:C}:{},...p&&{order:p}}}function kt(e,t,n){const i=new Set(e?.methods.flatMap(e=>"pickup"===e.type?e.line_item_ids:(e.groups??[]).filter(({options:e})=>Boolean(e?.length)).flatMap(e=>e.line_item_ids)));return t.some(e=>{if("proposed"!==n&&!e.requiresShipping)return!1;const t=je([e]);return t.length>0&&!i.has($e(e))&&!t.every(e=>i.has(e))})}function Ct(e,t){const n=new Set(e?.methods.filter(e=>"pickup"===e.type).flatMap(e=>(e.groups??[]).filter(e=>Boolean(e.selected_option_id)).flatMap(e=>e.line_item_ids))??[]);return t.every(e=>n.has($e(e))||je([e]).every(e=>n.has(e)))}function wt(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:"shopify.card"===e.handler_id?"direct"===i:"shopWallet"===i,billing_address:n}}function At(e,t,n,i,o,s){const{proposed:r,negotiated:a}=e.proposal,d=e.addressManager.shipping.value,c="shopPay"===e.identity.current.value?d:void 0,l=c?[...c.addresses.value,...c.immutableAddresses.value]:void 0,u=a.fields.shippingAddress.value,p=s?.currentUrl.value,h=r.captcha.value;return{i18n:n,readMode:o,requiresCaptcha:Boolean("hcaptcha"===h?.provider&&h.sitekey&&(!h.token||h.violationCode)),buyerReviewUrl:"/review"===p?.normalizedPath?p.href:void 0,id:a.fields.ucp.value?.id,continueUrl:a.fields.ucp.value?.continueUrl,merchantPolicies:i.merchantPolicies,merchandiseLines:"proposed"===o?{lines:r.merchandiseLines.value}:a.fields.merchandiseLines.value,subtotal:a.fields.subtotal.value,discountLines:"proposed"===o?{lines:r.discountLines.value}:a.fields.discountLines.value,tax:e.proposal.facts.tax??(f=a.fields.taxes.value,"available_total"===f?.status?f.totalTax:void 0),duty:e.proposal.facts.duty??(m=a.fields.duties.value,"available_total"===m?.status?m.totalDuty:void 0),dutiesIncluded:Boolean(a.fields.dutiesIncluded.value)||Boolean(e.proposal.facts.dutiesIncluded),runningTotal:a.fields.runningTotal.value,buyer:t.checkout.buyer[o??"negotiated"].value,deliveryNext:a.fields.deliveryNext.value,shopId:i.id,marketDrivenShippingEnabled:i.marketDrivenShippingEnabled,remoteShopsConfigMap:i.remoteShopsConfigMap,remoteMerchandiseDetails:a.fields.remoteMerchandiseDetails.value,shippingAddress:"proposed"===o?r.shippingAddress.value:u,billingAddress:"shopPay"===e.identity.current.value?void 0:St(e,i,o),addressContext:e.address,savedDestinations:l,proposedDeliveryLines:r.deliveryLines.value.map(e=>
1e.value),isShippingRequired:Boolean(a.fields.isShippingRequired.value),violations:a.fields.allViolations.value,receipt:e.latestReceipt.value};var m,f}function St(e,t,n){const i=e.latestReceipt.value;return"processed"===i?.status?i.purchaseOrder.billingAddress:"processing"!==i?.status&&"processing_remote_checkouts"!==i?.status&&"polling_for_order"!==i?.status?"proposed"===n?function(e,t){const{proposed:n,negotiated:i,facts:o}=e.proposal,s=n.paymentLines.value;for(const{method:c}of s)if(c.type===b.CreditCard||c.type===b.PayPal)return c.billingAddress;const r=n.billingAddress.value,a=!r.address1&&o.billingAddress?o.billingAddress:r;if("shipping"!==n.billingAddressOption.value||!i.fields.isShippingRequired.value||!k(s))return a;const d=s[0]?.method;if("wallet"===d?.type){const n=i.fields.runningTotal.value,o=n&&n.amount<=0,s=C(i.fields.merchandiseLines.value?.lines).some(e=>Boolean(e.sellingPlan?.subscriptionDetails));if((!o||s||i.fields.deferredTotal.value?.amount.amount)&&("GOOGLE_PAY"===d.name||"APPLE_PAY"===d.name||"PAYPAL_EXPRESS"===d.name&&j({checkout:e,shop:t,paymentMethods:i.fields.paymentMethods.value})))return a}return o.delivery?.[0]?.deliveryAddress??n.shippingAddress.value}(e,t):e.proposal.negotiated.fields.billingAddress.value:void 0}const It="store_credit";const Tt="tax_number",Et=["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"];function Nt(e){const t=e.proposal.proposed.localizationExtensions.value.flatMap(e=>Et.some(t=>t===e.fields.key.value)?[e]:[]);return 1===t.length?t[0]:void 0}function Pt(e,t){const n=new Map(t.flatMap(({targetMerchandiseLines:e})=>e.map(e=>[e.stableId,e]))),i=new Set;for(const o of e){const e=(o.lineComponents?.length?o.lineComponents:[o]).filter(e=>e.requiresShipping??n.get(e.stableId)?.requiresShipping);for(const{stableId:t}of e)i.add(t);e.length&&o.lineComponents?.length&&i.add(o.stableId)}return i}function Lt(e,t){return[...new Set(e.filter(({targetMerchandiseLines:e})=>e.some(({stableId:e})=>t.has(e))).flatMap(({deliveryMethodTypes:e})=>e).filter(e=>"NONE"!==e))]}function Dt(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-08-25",extends:"dev.ucp.shopping.checkout",spec:"https://shopify.dev/docs/agents/carts-and-checkout/declared-fields",schema:"https://shopify.dev/ucp/schemas/2026-08-25/shopify_shopping_declared_fields.json",requires:{protocol:{min:"2026-08-25"}}}]},payment_handlers:n}}function Mt(e,t){return{...e,ucp:Dt(Q(e)?"error":"success",t.proposal.negotiated.fields.ucp.value?.paymentHandlers)}}const Rt={"shopify.card":"shopify.card",shop_pay:"shop_pay_approval_id"};class Ot{#n;#i;#o;#s=!1;#r=!1;#a=!1;#d=!1;#c;constructor({observability:e,checkout:t}){this.#n=e,this.#i=t,this.#o="processed"===t.latestReceipt.peek()?.status}log({name:e,message:t,attributes:n}
1){this.#n.log(e,t,n)}error({error:e,...t}){this.#n.error(e,t)}histogram(e){this.#n.histogram(e)}initialized(){this.#l("web_mcp_initialized")}toolCalled(e){this.#s||(this.#s=!0,this.#l("web_mcp_tool_called",{tool:e})),this.#r||"update_checkout"!==e&&"complete_checkout"!==e||(this.#r=!0,this.#l("web_mcp_write_tool_called",{tool:e})),this.#a||"complete_checkout"!==e||(this.#a=!0,this.#l("web_mcp_complete_checkout_called"))}submitForCompletion({accepted:e,submittedAt:t,receiptId:n,agenticInstrument:i}){if(this.#o)return;const o={payment:i?Rt[i.handler_id]:"unknown",identity:this.#i.identity.current.peek()};this.#n.histogram({name:"web_mcp_submit_for_completion",value:xt(t),unit:"ms",attributes:{...o,result:e?"accepted":"failed"}}),e&&void 0!==n&&(this.#c={receiptId:n,submittedAt:t,labels:o,actionRequired:!1},this.#u(this.#i.latestReceipt.peek()))}paymentCredentialSupplied(e){!this.#d&&G(e)&&(this.#d=!0,this.#l("web_mcp_payment_credential_update_called",{payment:Rt[e.handler_id]}))}updateCheckoutPartialInput(e){(e.buyer||e.fulfillment||e.payment)&&this.#l("web_mcp_update_checkout_partial_input",{missingBuyer:e.buyer,missingFulfillment:e.fulfillment,missingPayment:e.payment})}watchReceipts(e){if(this.#o||e.aborted)return;const n=t(()=>{const e=this.#i.latestReceipt.value;i(()=>this.#u(e))});e.addEventListener("abort",n,{once:!0})}#u(e){const t=this.#c;if(!t||e?.id!==t.receiptId)return;if("action_required"===e.status)return void(t.actionRequired=!0);if("processed"!==e.status&&"failed"!==e.status)return;this.#c=void 0;const n=xt(t.submittedAt),i="failed"===e.status?e.failure:void 0,o={...t.labels,result:e.status,...i&&{failure:"payment"===i.type?"payment":"other"}};this.#n.histogram({name:"web_mcp_submission_receipt",value:n,unit:"ms",attributes:o}),this.#n.log("web_mcp_submission_receipt_settled","[WebMcp] submission receipt settled",{...o,...i&&{failureType:i.type},..."payment"===i?.type&&{paymentErrorCode:i.code},actionRequired:t.actionRequired,durationMs:n,receiptId:e.id})}#l(e,t={}){this.#o||this.#n.counter({name:e,value:1,attributes:{...t,identity:this.#i.identity.current.peek()}})}}function xt(e){return Math.round(performance.now()-e)}function Ut(e,{checkout:t},n){const i=e.fulfillmentMethods.methods;if(i.length>1)return fe("At most one fulfillment method is supported.");const o=i[0];if(void 0!==o?.id&&o.id!==o.type)return fe("Method id must match its shipping or pickup type; omit id when requesting a new method.");const{proposed:s,negotiated:r}=t.proposal,a=s.deliveryLines.value.map(e=>e.value),d=Pt(s.merchandiseLines.value,a),c=Lt(a,d);if(c.some(p)&&c.some(qt)){const e=r.fields.deliveryNext.value,t="filled"===e?.status||"partial"===e?.status?e.lines.filter(e=>"available"===e.status):[],n=Lt(a.map(e=>{const n=t.find(({id:t})=>Boolean(e.id)&&t===e.id)??t.find(t=>Ye(t.targetMerchandiseLines,e.targetMerchandiseLines.filter(e=>e.requiresShipping).map($e))),i=n?.methods.find(({handle:t,methodType:n})=>t===e.deliveryMethodHandle&&e.deliveryMethodTypes.includes(n)),o=i?.methodType??(e.deliveryMethodHandle?void 0:e.deliveryMethodTypes[0]);return o?{...e,deliveryMethodTypes:[o]}:e}),d);if(n.some(p)&&n.some(qt))return fe("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(p)?"pickup":void 0),u=Boolean(e.context&&!jt(s.locationAddress.value,e.context));if(u&&"pickup"!==l)return fe("Changing context locality requires a pickup method.");if(!o&&"pickup"!==l)return;const h=e=>"pickup"===l?p(e):qt(e);if(o&&(void 0!==o.selected_destination_id||o.groups.length))return u||c.length&&!c.some(h)?fe("Change the method/search origin first, then select a destination or option returned by that update."):void 0;if("pickup"===l&&c.length&&c.every(e=>"PICKUP_POINT"===e))return u?fe("Pickup-point locality discovery is not supported. Select an existing destination instead."):void 0;if(!d.size)return fe("This checkout has no physical items to fulfill.");if("pickup"===l&&e.context){const t=s.shippingAddress.value?.countryCode||s.locationAddress.value?.countryCode;if(!t)return fe("Pickup search requires an established checkout country. Ask the buyer to choose a country in checkout.");if(e.context.address_country!==t)return fe("Pickup search must remain in the checkout country.")}if(!n&&!u&&c.every(h)&&c.length)return;const m=!c.length||!c.every(h);if(!n&&m)return fe("The delivery selector is not ready.");const f=n?n.getAvailableMethodTypes().find(e=>"pickup"===l?e.includes("PICK_UP"):e.some(h)):c;if(!f)return fe(`The checkout does not offer ${l}.`);const y=r.fields;return(m||u)&&(y.mustSelectProvidedShippingRate.value||y.mustSelectProvidedAddress.value||!1===y.canUpdateDeliveryAddress.value)?fe("The checkout locks its delivery method or address."):{methodTypes:f,needsLocalityLookup:u,changesMo
1de:m}}function qt(e){return"SHIPPING"===e||"LOCAL"===e}function jt(e,t){return V(e,{countryCode:t.address_country,zoneCode:t.address_region,postalCode:t.postal_code})}const $t={status:"written"};const Ht=({shippingAddress:e},t)=>{if("saved_address_id"in e)return function(e,t){const{checkout:n,clearShippingAddressErrors:i}=t;if("shopPay"!==n.identity.current.value)return{status:"rejected",field:"shippingAddress"};const o=n.addressManager.shipping.value,s=[...o.addresses.value,...o.immutableAddresses.value].find(t=>t.id===e);if(!s||s.disabled)return{status:"rejected",field:"shippingAddress"};const r=o.applyAddressChangeBlockReason("ucp").value;if(r&&"MUST_SELECT_PROVIDED_ADDRESS"!==r)return;return tn(s.address.countryCode,"fulfillment.methods[0].selected_destination_id",t.shop)||{status:"ready",negotiation:{include:["shippingAddress","deliveryNext"],loading:["deliveryNext"],fieldsToResolve:["shippingAddress","deliveryNext"]},apply:async()=>await o.selectAddress(e)?(i(),$t):{status:"failed"}}}(e.saved_address_id,t);const{checkout:n,observability:i,clearShippingAddressErrors:o}=t,s=n.addressManager.shipping.value;if(s.applyAddressChangeBlockReason("ucp").value)return;const r=tn(e.address_country,"fulfillment.methods[0].destinations[0].address_country",t.shop);if(r)return r;const a=Se(e,n.address);return{status:"ready",negotiation:{include:["shippingAddress","deliveryNext"],loading:["deliveryNext"],fieldsToResolve:["shippingAddress","deliveryNext"]},async apply(){const e=await s.applyAddressChange({source:"ucp",address:a});return"success"!==e.type?(i.log({name:"web_mcp_address_change_declined",message:"[WebMcp] address manager declined an admitted address",attributes:{reason:e.reason}}),{status:"failed"}):(o(),$t)}}};function Bt(e,{readSavedCards:t,getSavedCardSelector:n}){const i=t()?.find(({instrument:t})=>t.id===e);return i?.usable?{status:"ready",negotiation:{include:["paymentLines","billingAddress"],loading:["paymentLines"],fieldsToResolve:["paymentLines"]},async apply(){const t=n?.();return t&&await t(e)?$t:{status:"failed"}}}:{status:"rejected",field:"payment"}}function Ft({fulfillmentMethods:e},{checkout:t},n=!1){const{proposed:i,negotiated:o}=t.proposal,s=o.fields.deliveryNext.peek(),r="filled"===s?.status||"partial"===s?.status?s.lines.filter(rn):[],a=new Map;for(const l of i.deliveryLines.peek()){const{id:e,targetMerchandiseLines:t,deliveryMethodTypes:n,deliveryMethodHandle:i}=l.peek();if(0===n.filter(Be).length)continue;const o=r.find(t=>Boolean(e)&&t.id===e)??r.find(e=>Ye(e.targetMerchandiseLines,t.filter(e=>e.requiresShipping).map($e))),s=o?.methods.find(e=>e.handle===i);if(s){if(!Be(s.methodType))continue}else if(Fe(i,n,s))return{status:"rejected",field:"fulfillmentMethods"};a.set(l,{deliveryLine:l,selectedOptionId:void 0,selectedOptionDetails:void 0})}try{for(const t of function(e,t,n){return e.methods.flatMap(e=>"pickup"===e.type?function(e,t,n){const i=void 0===e.selected_destination_id?void 0:Xe(n).find(({id:t})=>t===e.selected_destination_id);if(void 0!==e.selected_destination_id&&!i)throw new Zt("unknown_pickup_destination");const o=new Map;for(const s of e.groups){if(s.selected_option_id!==We)throw new Zt("unknown_fulfillment_option");const e=nn(s,n);if("pickup"!==ze(e)||i&&!i.selections.some(t=>t.line===e)||o.has(e))throw new Zt("unknown_fulfillment_group");o.set(e,s)}return i?i.selections.map(({line:e,method:n})=>on(e,n,o.get(e)?.selected_option_details,t)):[...o].map(([e,n])=>{const i=e.methods.find(t=>t.handle===e.selectedDeliveryMethodHandle&&p(t.methodType)&&t.pickupLocation);if(!i)throw new Zt("unknown_pickup_destination");return on(e,i,n.selected_option_details,t)})}(e,t,n):e.groups.map(e=>{const i=nn(e,n,Boolean(e.id)&&t.some(({value:t})=>t.id===e.id)?"unselectable_fulfillment_group":"unknown_fulfillment_group"),o=i.methods.find(({handle:t,methodType:n})=>t===e.selected_option_id&&("SHIPPING"===n||"LOCAL"===n));if(!o||"shipping"!==ze(i))throw new Zt("unknown_fulfillment_option");return on(i,o,e.selected_option_details,t)}))}(e,i.deliveryLines.peek(),r))a.set(t.deliveryLine,t)}catch(c){if(!(c instanceof Zt))throw c;return{status:"rejected",field:"fulfillmentMethods",reason:c.reason}}const d=o.fields.mustSelectProvidedShippingRate.peek();return[...a.values()].some(({deliveryLine:e,selectedOptionId:t})=>!function(e,t,n){return!n||e===t}(e.peek().deliveryMethodHandle,t,d))?{status:"rejected",field:"fulfillmentMethods"}:{status:"ready",negotiation:{include:["deliveryNext"],loading:["deliveryNext"],fieldsToResolve:["deliveryNext"]},async apply(){for(const e of i.deliveryLines.value){const t=a.get(e);if(!(t||n&&e.value.deliveryMethodTypes.some(Be)))continue;
1const{selectedOptionId:i,selectedOptionDetails:o}=t??{};e.value={...e.peek(),deliveryMethodHandle:i,deliveryMethodOptions:sn(o),...void 0===i&&{isCustomRate:void 0,customDeliveryStrategy:void 0}}}return $t}}}const Gt=[({buyer:e},{checkout:t,shopPay:n,ucpBuyer:i})=>{const o=W({identity:t.identity,proposal:t.proposal,shopPay:n});if(o&&"shopPay"===t.identity.current.value)return;const s={...!o&&{email:e.email},phone_number:e.phone_number};return{status:"ready",negotiation:{include:["contactInfo"],loading:["contactInfo"],fieldsToResolve:["contactInfo"]},apply:async()=>(i.update(s),$t)}},({discountCodes:e=[]},t)=>{const{proposed:i,negotiated:o}=t.checkout.proposal,s=new Map,r=[];for(const n of i.discountLines.value){const{discount:e}=n;if("code"===e.type||"discountCodeTrigger"===e.type){const t=e.title.toUpperCase(),i=s.get(t);i?i.push(n):s.set(t,[n])}else r.push(n)}if(!1===o.fields.canUpdateDiscountCodes.value){const t=new Set(e.map(e=>e.toUpperCase()));if(t.size===s.size&&[...t].every(e=>s.has(e)))return;return{status:"rejected",field:"discountCodes"}}return{status:"ready",negotiation:{include:["discountLines","deliveryNext"],loading:["discountLines","deliveryNext"],fieldsToResolve:["discountLines","totalSavings","merchandiseLines","deliveryNext"]},async apply(){const o=new Set;for(const t of e){const e=t.toUpperCase();if(o.has(e))continue;o.add(e);const n=s.get(e);n?r.push(...n):r.push({title:t,discount:{type:"discountCodeTrigger",title:t}})}return n(()=>{i.discountLines.value=r,i.reduction.value=void 0;const{discountCodeWarningSignal:e,currentDiscountCodeAttemptSignal:n}=t.negotiator.context;e.value=null,n.value=null}),$t}}},Ht,Ft];function Yt(e,t,{fulfillmentRequest:n,fulfillment:i,locationAddress:o}={}){const s=[];for(const r of Gt){if(r===Ht&&n){const{methodTypes:e}=n,{proposed:r}=t.checkout.proposal;s.push({status:"ready",negotiation:{include:["deliveryNext"],loading:["deliveryNext"],fieldsToResolve:["deliveryNext"]},apply:async()=>(i?i.setDesiredMethod(e,o):o&&(r.locationAddress.value=o),$t)})}const a=r===Ft?Ft(e,t,void 0!==n):r(e,t);if(void 0!==a){if("rejected"===a.status)return Jt(a.field,a.reason);s.push(a)}}return s}class Wt{#p;constructor(e){this.#p=e}writePayment({payment:e,billingAddress:t=e?.billing_address,applyBilling:i=!0}){const o=i?this.#h(t):void 0,s=this.#m(e);return Q(s)?s:(n(()=>{s?.apply(),o?.apply()}),{status:"applied"})}#h(e){const{checkout:t}=this.#p;if(!Y(t))return;const i=void 0===e?void 0:Se(e,t.address);return{apply({replacement:e=!1}={}){if(!Y(t))return!1;const{proposed:o,negotiated:s,facts:r}=t.proposal,a=!1===s.fields.isShippingRequired.value;if(i&&!T(i)&&(a||!function(e,t){const n=Ie(t.proposal.proposed.shippingAddress.value,t.address);return R(e,Se(n,t.address))}(i,t)))return n(()=>{o.billingAddress.value=i,o.billingAddressOption.value="custom"}),!0;if(e&&a)return!r.billingAddress&&!function(e){return e.paymentLines.value.some(e=>e.method.type===b.CreditCard||e.method.type===b.PayPal||function(e){if("wallet"!==e.method.type)return!1;switch(e.method.name){case"APPLE_PAY":return U(e);case"GOOGLE_PAY":return x(e);case"PAYPAL_EXPRESS":return O(e);default:return!1}}(e))}(o)&&(n(()=>{o.billingAddress.value=Se({address_country:o.billingAddress.value.countryCode},t.address),o.billingAddressOption.value="custom"}),!0);const d=o.billingAddressOption.value;return o.billingAddressOption.value="shipping",void 0!==i||"shipping"!==d}}}#m(e){const{checkout:t,shop:i,paymentInstrument:o}=this.#p;if(!Y(t))return;if(!e&&!o.value)return;const{proposed:s,negotiated:r}=t.proposal,a=r.fields.paymentMethods.value,d=s.paymentLines.value.find(e=>!e.due&&"direct"===e.method.type),c=E(a??[],"direct"===d?.method.type&&Boolean(d.method.alternative));return!e||("shopify.card"===e.handler_id?c:i.hasFlagEnabled(N)&&P(a))?{apply(){Y(t)&&n(()=>{const t=o.value;if("shop_pay"===t?.handler_id&&t.credential?.approval_id&&(s.paymentLines.value=s.paymentLines.value.map(e=>"shopWallet"===e.method.type&&e.method.shopPayApprovalId===t.credential?.approval_id?{...e,method:{...e.method,shopPayApprovalId:void 0}}:e)),o.value=e,e){"shopify.card"===e.handler_id&&e.credential?.token&&c?"direct"===d?.method.type&&d.method.paymentMethodIdentifier===c.paymentMethodIdentifier||(s.paymentLines.value=L(s.paymentLines.value,{method:{type:"direct",paymentMethodIdentifier:c.paymentMethodIdentifier,alternative:c.alternative}},D(i))):"shop_pay"===e.handler_id&&e.credential?.approval_id&&(s.paymentLines.value=L(s.paymentLines.value,{method:{type:"shopWallet",shopPayApprovalId:e.credential.approval_id}}
1,D(i)));for(const e of Object.values(s.directPaymentErrors))e.value=void 0;s.generalPaymentError.value=void 0,s.generalPaymentErrorCode.value=void 0}})}}:ne("invalid_request","This checkout does not accept the supplied payment handler. Call get_checkout for the current checkout state.",{invalidInputPath:"payment.instruments[].handler_id",invalidInputExpected:"a handler this checkout accepts"})}async applyUpdate(e,{isExpired:t}={}){const{shippingAddress:i}=e,o=e.payment&&"billing_address"in e.payment?e.payment.billing_address:void 0;if(await this.loadAddressMetadata(["saved_address_id"in i?void 0:i,Y(this.#p.checkout)?o:void 0]),t?.())return pe();if(this.#p.isSubmitting.value)return _e();const s=e.payment&&"instrument_id"in e.payment?e.payment.instrument_id:void 0;if(void 0!==s&&(await this.#p.waitForPendingNegotiations(),t?.()))return pe();let r=Ce(e.declaredFields,this.#p.declaredFields);if(Q(r))return r;if(r.some(({changed:e})=>e)){if(await this.#p.waitForPendingNegotiations(),t?.())return pe();if(this.#p.isSubmitting.value)return _e();if(r=Ce(e.declaredFields,this.#p.declaredFields),Q(r))return r}let a,d=this.#p.getFulfillmentController?.(),c=Ut(e,this.#p,d);if(Q(c))return c;if(c?.needsLocalityLookup&&e.context){try{const t=this.#p.resolvePickupLocality;if(!t)throw new zt;a=await t(e.context)}catch(C){return this.#p.observability.error({error:C instanceof zt?C:new zt(C)}),t?.()?pe():ce("update_failed","context","Pickup locality lookup is unavailable.",`Call get_checkout and retry with the latest checkout. ${ie("update the checkout")}`)}if(t?.())return pe();if(!a)return ce("rejected","context","Could not resolve a unique postal locality.","Check address_country, address_region and postal_code, then retry.");if(r=Ce(e.declaredFields,this.#p.declaredFields),Q(r))return r}if(e.context){const t=this.#p.checkout.proposal.proposed.locationAddress.value;jt(t,e.context)&&(a=t)}if(d=this.#p.getFulfillmentController?.(),c=Ut(e,this.#p,d),Q(c))return c;let l=this.#h(o);const u=e.payment&&"handler_id"in e.payment?e.payment:void 0;let h=this.#m(u);if(Q(h))return h;let m=void 0===s?void 0:Bt(s,this.#p);if("rejected"===m?.status)return Jt(m.field);let f=Yt(e,this.#p,{fulfillmentRequest:c,fulfillment:d,locationAddress:a});if(Q(f))return f;if(t?.())return pe();const y=[];let _=!1;for(const n of["negotiate","stage"]){if("stage"===n&&_&&(r=Ce(e.declaredFields,this.#p.declaredFields),Q(r)))return pe();for(const i of r)if(i.phase===n&&i.changed){if(t?.())return pe();try{if(!(await i.apply())||t?.())return pe()}catch{return pe()}if("stage"===i.phase)y.push(i.negotiation);else{if(_=!0,d=this.#p.getFulfillmentController?.(),c=Ut(e,this.#p,d),Q(c))return pe();if(f=Yt(e,this.#p,{fulfillmentRequest:c,fulfillment:d,locationAddress:a}),Q(f))return pe();if(l=this.#h(o),h=this.#m(u),Q(h))return pe();if(m=void 0===s?void 0:Bt(s,this.#p),"rejected"===m?.status)return pe()}}}if(h){const e=h;f.push({status:"ready",negotiation:{include:["paymentLines"],loading:["paymentLines"],fieldsToResolve:["paymentLines"]},apply:async()=>(e.apply(),$t)})}if(!m&&0===f.length&&0===y.length&&!l)return{status:"applied"};if(t?.())return pe();if(this.#p.isSubmitting.value)return _e();if((await Promise.all(n(()=>f.map(e=>e.apply())))).find(e=>"failed"===e.status)||t?.())return pe();if(this.#p.isSubmitting.value)return _e();if(m){if("failed"===(await m.apply()).status||t?.())return pe();if(await this.#p.waitForPendingNegotiations(),t?.())return pe();if(this.#p.isSubmitting.value)return _e()}const g=l?.apply({replacement:!0})??!1;if(!m&&0===f.length&&0===y.length&&!g)return{status:"applied"};const v=await this.#f((b=[...f.map(e=>e.negotiation),...y,...m?[m.negotiation]:[],...g?[{include:["billingAddress"],loading:["billingAddress"],fieldsToResolve:["billingAddress"]}]:[]],{include:Vt(b,"include"),loading:Vt(b,"loading"),fieldsToResolve:Vt(b,"fieldsToResolve")}));var b;await this.#p.waitForPendingNegotiations();const k=function(e){return"success"===e?.status||"error"===e?.status?{status:"applied"}:pe()}(v);if(void 0!==s&&!function(e,{readSavedCards:t}){return Boolean(t()?.some(({instrument:t,usable:n})=>t.id===e&&t.selected&&n))}(s,this.#p))return pe();if(!Q(k)&&!t?.()&&c?.needsLocalityLookup&&a&&e.context&&jt(this.#p.checkout.proposal.proposed.locationAddress.value,e.context)){const{proposed:e}=this.#p.checkout.proposal,t=e.deliveryLines.value.map(e=>e.value),n=Lt(t,Pt(e.merchandiseLines.value,t));n.length&&n.every(p)&&this.#p.announcePickupLocality?.(a)}return t?.()?pe():k}async loadAddressMetadata(e){const t=new Set;for(const i of e){const e=i?.address_country?.toUpperCase();i&&e&&Xt(e,i)&&t.add(e)}const{countryDetails:n}=this.#p.checkout.address;for(const i of t){const e=n.get(i);e&&!e.isFallback||await n.fetch(i)}}async#f(e){let t;const{include:n,...i}=e;return await this.#p.journey.negotiate({...i,silenceViolations:M(n),runListenersOnError:n.includes("shippingAddress")||n.includes("discountLines"),onComplete:e=>{t=e}}),t}}
1class zt extends Error{constructor(e){super("WebMCP pickup locality lookup failed",{cause:e}),this.name="WebMcpLocalityLookupError"}}function Xt(e,t){const n=Boolean(t.street_address||t.street_name||t.street_number),i=Boolean(t.extended_address||t.district),o=null!==a(e,""),s=null!==c(e,"");return n&&o||i&&s}function Vt(e,t){return[...new Set(e.flatMap(e=>e[t]))]}const Kt={context:"context",buyer:"buyer",discountCodes:"discounts",declaredFields:"declared_fields",shippingAddress:"fulfillment",fulfillmentMethods:"fulfillment",payment:"payment"};function Jt(e,t){return t instanceof en?function(e,t,n){const i=n?` Supported countries: ${n.join(", ")}.`:"";return ne("rejected",`${e} ${t} is not a country this shop ships to. ${re}${i} Tell the buyer. ${ie("update the checkout")}`)}(t.path,t.countryCode,t.listedCountryCodes):"unsupported_option_instructions"===t?he("instructions"):"unsupported_option_phone"===t?he("phone_number"):"unknown_fulfillment_group"===t?ne("rejected",`fulfillment.methods[].groups[] does not match a delivery group in the current checkout. ${me}`):"unselectable_fulfillment_group"===t?ne("rejected",`fulfillment.methods[].groups[] has no selectable delivery option in the current checkout. ${re} Send the update without groups, then choose an option from the next get_checkout. ${ie("update the checkout")}`):"unknown_fulfillment_option"===t?ne("rejected",`fulfillment.methods[].groups[].selected_option_id is not an option for this group in the current checkout. ${me}`):ne("update_failed",`Unable to update ${Kt[e]}. Call get_checkout to review the checkout and its messages before retrying. ${ie("update the checkout")}`)}class Zt extends Error{constructor(e){super(e),this.name="WebMcpFulfillmentMethodUpdateError",this.reason=e}}const Qt=20;class en extends Error{constructor(e,t,n){super(`${e} is not a shipping country`),this.name="UnsupportedShippingCountryError",this.countryCode=e,this.path=t,this.listedCountryCodes=n}}function tn(e,t,{shippingCountries:n}){const i=e?.trim().toUpperCase();if(i&&0!==n.length&&!n.some(({value:e})=>e===i))return{status:"rejected",field:"shippingAddress",reason:new en(i,t,n.length<=Qt?n.map(({value:e})=>e):void 0)}}function nn(e,t,n="unknown_fulfillment_group"){const i=t.find(t=>Boolean(e.id)&&t.id===e.id)??t.find(t=>Ye(t.targetMerchandiseLines,e.line_item_ids));if(!i)throw new Zt(n);return i}function on(e,t,n,i){const o=i.find(t=>Boolean(e.id)&&t.value.id===e.id)??i.find(t=>Ye(t.value.targetMerchandiseLines,e.targetMerchandiseLines?.filter(e=>e.requiresShipping).map($e)));if(!o)throw new Zt("unknown_fulfillment_group");if(!o.value.deliveryMethodTypes.includes(t.methodType))throw new Zt("unsupported_fulfillment_transition");return function(e,t){if(t){if(void 0!==t.instructions&&!Ge(e,"instructions"))throw new Zt("unsupported_option_instructions");
1if(void 0!==t.phone_number&&!Ge(e,"phone_number"))throw new Zt("unsupported_option_phone")}}(t,n),{deliveryLine:o,selectedOptionId:t.handle,selectedOptionDetails:n}}function sn(e){return{phone:e?.phone_number,instructions:e?.instructions}}function rn(e){return"available"===e.status}const an=s()(["shipping","pickup"]);class dn extends Error{constructor(e,t,n,{loggablePath:i=e}={}){super(`${e}: expected ${t}, got ${n} instead.`),this.name="WebMcpInputError",this.expected=t,this.loggablePath=i}}const cn='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.',ln={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)."}},un={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:{type:"object",description:`Replacement address. Include all fields to retain; omitted fields are cleared. Use PUT semantics, not PATCH. ${cn}`,properties:ln}}}}}};function pn(e,{path:t,requireCredential:n=!1,savedPaymentMethodsOnly:i=!1}){const o=In(e,t);if(!n&&(void 0===o.instruments||Array.isArray(o.instruments)&&0===o.instruments.length))return;const s=`${t}.instruments[0]`,r=function(e,t){if(!Array.isArray(e))throw new dn(t,"an array",Pn(e));if(1!==e.length)throw new dn(t,"1 item",`${e.length} items`);return In(e[0],`${t}[0]`)}(o.instruments,`${t}.instruments`);if(!n&&i)return function(e,t){for(const n of Object.keys(e))if(!["id","type","selected","display"].includes(n))throw new dn(`${t}.${n}`,"a saved instrument id from get_checkout, not new payment data","an unsupported field",{loggablePath:t});return{instrument_id:hn(e.id,`${t}.id`)}}(r,s);const a=r.handler_id;if(!n&&void 0===a&&void 0===r.credential){const e=mn(r,s);return void 0===e?void 0:{billing_address:e}}if("shopify.card"!==a&&"shop_pay"!==a)throw new dn(`${s}.handler_id`,"shopify.card or shop_pay","an unsupported handler");const d=En(r,{id:void 0,type:void 0},s),c="shopify.card"===a?"card":"shop_pay";if(void 0!==d.type&&d.type!==c)throw new dn(`${s}.type`,c,"an unsupported instrument type");const l=mn(r,s),u={id:d.id??K(),...void 0===l?{}:{billing_address:l}},p=`${s}.credential`,h=n||void 0!==r.credential?In(r.credential,p):void 0;if("shopify.card"===a){if(void 0===h)return{...u,handler_id:a,type:"card"};if(fn({object:h,allowedFields:["type","token"],path:p}),void 0!==h.type&&"shopify_token"!==h.type)throw new dn(`${p}.type`,"shopify_token","an unsupported credential type");return{...u,handler_id:a,type:"card",credential:{type:"shopify_token",...n||void 0!==h.token?{token:hn(h.token,`${p}.token`)}:{}}}}if(void 0===h)return{...u,handler_id:a,type:"shop_pay"};if(fn({object:h,allowedFields:["type","approval_id"],path:p}),void 0!==h.type&&"shop_token"!==h.type)throw new dn(`${p}.type`,"shop_token","an unsupported credential type");return{...u,handler_id:a,type:"shop_pay",credential:{type:"shop_token",...n||void 0!==h.approval_id?{approval_id:hn(h.approval_id,`${p}.approval_id`).trim()}:{}}}}function hn(e,t){if("string"!=typeof e||0===e.trim().length)throw new dn(t,"a non-empty string",Pn(e));return e}function mn(e,t){if(void 0!==e.billing_address)return En(e.billing_address,gn,`${t}.billing_address`)}function fn({object:e,allowedFields:t,path:n}){if(Object.keys(e).some(e=>!t.includes(e)))throw new dn(n,"only supported fields","extra properties")}
1const yn={email:"",phone_number:""},_n={first_name:"",last_name:"",phone_number:"",street_address:void 0,extended_address:void 0,address_locality:"",address_region:"",address_country:"",postal_code:""},gn={..._n,company:void 0,street_name:void 0,street_number:void 0,district:void 0},vn={phone_number:void 0,instructions:void 0};const bn=new Set(["purpose","title","description","value_schema","presentation","required"]);function kn(e,t){const n=an.find(t=>t===e);if(void 0!==n)return n;throw new dn(t,an.map(e=>JSON.stringify(e)).join(" or "),"string"==typeof e?JSON.stringify(e):Pn(e))}function Cn(e,t){if(void 0!==e){if(!Array.isArray(e))throw new dn(t,"an array",Pn(e));for(const[n,i]of e.entries()){const e=In(i,`${t}[${n}]`);if("business_location"!==e.type)throw new dn(`${t}[${n}].type`,'a read-only "business_location" from get_checkout; select pickup through selected_destination_id',Pn(e.type))}}}function wn(e,t){if(null===e.selected_destination_id)return;const{selected_destination_id:n}=En(e,{selected_destination_id:void 0},t);if(""===n)throw new dn(`${t}.selected_destination_id`,"a non-empty string or null","an empty string");return n}function An(e,t){const n=`${t}.destinations[0]`,i=`${t}.destinations`,{destinations:o}=e;if(void 0===o)return{..._n};if(!Array.isArray(o))throw new dn(i,"an array",Pn(o));if(0===o.length)return{..._n};if(1!==o.length)throw new dn(i,"1 item",`${o.length} items`);const s=In(o[0],n);if(void 0!==s.pickup_location_address||"business_location"===s.type)throw new dn(n,"a flat shipping address","a pickup location");const r=En(s,gn,n);return{..._n,...r,address_country:(r.address_country??"").trim()}}function Sn(e,t){if(!Array.isArray(e))throw new dn(t,"an array",Pn(e));return e.flatMap((e,n)=>{const i=`${t}[${n}]`,o=In(e,i),s=o.selected_option_id,r=o.selected_option_details;if(void 0===s){if(void 0!==r)throw new dn(`${i}.selected_option_details`,"selected_option_id to also be present","selected_option_details without selected_option_id");return[]}if("string"!=typeof s)throw new dn(`${i}.selected_option_id`,"a string",Pn(s));const a=o.id;if("string"!=typeof a)throw new dn(`${i}.id`,"a string",Pn(a));const d=o.line_item_ids;if(void 0!==d&&!Nn(d))throw new dn(`${i}.line_item_ids`,"an array of strings",Pn(d));return[{id:a,line_item_ids:d,selected_option_id:s,selected_option_details:{...vn,...En(void 0===r?{}:r,vn,`${i}.selected_option_details`)}}]})}function In(e,t){if(!Tn(e))throw new dn(t,"an object",Pn(e));return e}function Tn(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function En(e,t,n){const i=In(e,n),o={};for(const s in t){if(!Object.hasOwn(i,s))continue;const e=i[s];if("string"!=typeof e)throw new dn(`${n}.${s}`,"a string",Pn(e));o[s]=e}return o}function Nn(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}function Pn(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"an array":"object"==typeof e?"an object":"a "+typeof e}const Ln="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.",Dn={type:"object",additionalProperties:!1,properties:{payment:{...un,required:["instruments"],properties:{instruments:{...un.properties.instruments,minItems:1,items:{...un.properties.instruments.items,required:["handler_id","credential"]}}}}}};class Mn extends Error{constructor(){super("WebMCP complete_checkout failed"),this.name="WebMcpCompleteCheckoutError"}}function Rn({ucpBuyer:e,isSubmitting:t,paymentInstrument:n,signal:i,checkout:o,shop:s,readC
1heckout:r,readSavedCards:a,shopPay: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. ${Ln}`,inputSchema:Dn,annotations:{consequentialHint:!0,readOnlyHint:!1,untrustedContentHint:!0},execute:async h=>Mt(await async function(h){if(p||t.value)return ne("completion_in_progress","A checkout completion is already in progress. Wait for it to finish, then call get_checkout before retrying.");p=!0;try{if(!s.hasFlagEnabled(q))return ne("buyer_action_required","The buyer must manually complete checkout on the page. Do not attempt to complete checkout on their behalf.");const{payment:p}=function(e,{ignorePayment:t=!1}={}){const n=In(e,"input");return fn({object:n,allowedFields:["payment"],path:"input"}),t||void 0===n.payment?{}:{payment:pn(n.payment,{path:"input.payment",requireCredential:!0})}}(h,{ignorePayment:!Y(o)});p&&c.paymentCredentialSupplied(p);const m=o.latestReceipt.value?.status;if("processing"===m||"processing_remote_checkouts"===m||"polling_for_order"===m||"processed"===m||"action_required"===m)return r()??ve();const f=l();if(!f||i?.aborted)return ge();if(Y(o)&&(p||n.value)){if(await f.waitForPendingNegotiations(),i?.aborted)return ge();const r=Y(o)?p??n.value:void 0;if(r&&p&&!o.isPaymentRequired.value)return ne("invalid_request","This checkout requires no payment. Retry complete_checkout without the payment field.",{invalidInputPath:"input.payment",invalidInputExpected:"no payment"});if(r&&G(r)&&o.isPaymentRequired.value){const l=new Wt({ucpBuyer:e,isSubmitting:t,paymentInstrument:n,checkout:o,shop:s,shopPay:d,observability:c,declaredFields:u,...f,readSavedCards:a});if(p&&(await l.loadAddressMetadata([p.billing_address]),i?.aborted))return ge();const h=l.writePayment({payment:r,applyBilling:void 0!==p});if(Q(h))return h}}let y,_,g=!1,v=!1,b={progressionStatus:"none"};const k=Y(o)&&o.isPaymentRequired.value&&G(n.value),C=k?n.value:void 0;try{t.value=k,await f.journey.progress("web-mcp-complete-checkout",e=>{b=function(e){const t=function(e){return"invalid"===e.status?e.reasons:"violations"in e?[...e.violations,...e.errors].map(({code:e})=>e):[]}(e);return{progressionStatus:e.status,...t.length>0&&{progressionReasons:[...new Set(t)].sort().join(",")}}}(e),g="success"===e.status||"alreadyCompleted"===e.status,v||="negotiated"in e||"receipt"in e,"receipt"in e&&(_=e.receipt.id)},{onValidationSuccess:()=>{y=performance.now()}})}finally{void 0!==y&&c.submitForCompletion({accepted:g,submittedAt:y,receiptId:_,agenticInstrument:C}),t.value&&v&&(n.value=void 0),t.value=!1}const w=r();return g||w?.messages?.some(e=>"error"===e.type&&"requires_buyer_input"===e.severity)?w??ve("completion_failed",b):ve("completion_failed",b)}catch(m){return m instanceof dn?le(m,"complete the checkout"):(c.error({error:new Mn}),ve("internal_error"))}finally{p=!1}}(h),o)}}class On extends Error{constructor(){super("WebMCP get_checkout failed to read the checkout"),this.name="WebMcpGetCheckoutError"}}class xn extends Error{constructor(e){super("WebMCP navigate_to_storefront failed",{cause:e}),this.name="WebMcpStorefrontNavigationError"}}function Un({shop:e,url:t}){if(e.hasStorefront)try{const n=new URL(e.previewReturnUrl??e.partnerStorefrontUrl??t.storefront());if("https:"!==n.protocol&&"http:"!==n.protocol)return;if(n.username||n.password)return;return n.href}catch{return}}function qn({checkout:e,shop:t,url:n,observability:i,signal:o,getPreactContext:s}
1){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(a,d)=>Mt(await async function(e,a){let d;try{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.keys(e).length>0)return ne("invalid_request","navigate_to_storefront takes no input. Retry with an empty object.",{invalidInputPath:"input",invalidInputExpected:"an empty object"});if(a.aborted||o.aborted)return be();const c=s();if(!c)return ne("internal_error",se);if(r(c))return ke();const l=Un({shop:t,url:n});if(!l)return ne("navigation_failed","A supported storefront destination is not available. Stay on the current checkout.");const u=new Promise(e=>{d=setTimeout(()=>e("timeout"),3e4)}),p=await Promise.race([c.waitForPendingNegotiations(),u]);return a.aborted||o.aborted?be():"timeout"===p?(i.log({name:"web_mcp_storefront_navigation_timed_out",message:"Storefront navigation timed out waiting for pending checkout updates"}),ne("navigation_failed","Checkout updates are still pending. Navigation was not started. Retry after updates finish.")):r(c)?ke():(window.location.assign(l),{status:"navigation_started",destination_url:l,message:"Refresh the available tools after the storefront loads."})}catch(c){return i.error({error:new xn(c)}),ne("navigation_failed","Unable to navigate to the storefront. Refresh the available tools and check the current page before retrying.")}finally{clearTimeout(d)}}(a,d?.signal??o),e)};function r({journey:t}){const n=e.latestReceipt.value;return t.completing.value||t.progressing.value||null!=n&&!["processed","failed","abandoned"].includes(n.status)}}const jn={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:{...un,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. ${cn}`,properties:ln}},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"}}}}}}}}}}}}}}};
1class $n extends Error{constructor(){super("WebMCP update_checkout failed to apply"),this.name="WebMcpUpdateCheckoutError"}}function Hn({ucpBuyer:e,isSubmitting:t,paymentInstrument:n,signal:i,checkout:s,shop:r,shopPay:a,router:d,getSavedCardSelector:c,readCheckout:l,readSavedCards:u,observability:p,getPreactContext:h,declaredFields:m,getFulfillmentController:f}){return{name:"update_checkout",title:"Update checkout",description:`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. ${Ln}`,inputSchema:jn,annotations:{consequentialHint:!1,readOnlyHint:!1,untrustedContentHint:!0},execute:async y=>Mt(await async function(y){let _;try{if(t.value)return _e();const g="shopPay"===s.identity.current.value,v=function(e,t={}){const n=function(e,t){const n=In(In(e,"input").checkout,"input.checkout"),i={};if(void 0!==n.context){const e="input.checkout.context",t=En(n.context,{address_country:void 0,address_region:void 0,postal_code:void 0},e);if(!t.address_country?.trim()||!t.postal_code?.trim())throw new dn(e,"address_country and postal_code for a pickup search","incomplete locality");i.context={address_country:t.address_country.trim().toUpperCase(),postal_code:t.postal_code.trim(),...t.address_region?.trim()&&{address_region:t.address_region.trim().toUpperCase()}}}return void 0!==n.buyer&&(i.buyer=En(n.buyer,yn,"input.checkout.buyer")),void 0!==n.discounts&&(i.discountCodes=function(e){const t="input.checkout.discounts",{codes:n}=In(e,t);if(void 0!==n){if(!Nn(n))throw new dn(`${t}.codes`,"an array of strings",Pn(n));return n}}(n.discounts)??[]),void 0!==n.declared_fields&&(i.declaredFields=function(e){const t="input.checkout.declared_fields";if(!Array.isArray(e))throw new dn(t,"an array",Pn(e));const n=new Set;return e.map((e,i)=>{const o=`${t}[${i}]`,s=In(e,o);for(const t of Object.keys(s))if(!["key","value"].includes(t)&&!bn.has(t))throw new dn(`${o}.${t}`,"a declared field key or value","an unknown field",{loggablePath:o});if("string"!=typeof s.key||0===s.key.length)throw new dn(`${o}.key`,"a non-empty string",Pn(s.key));if(n.has(s.key))throw new dn(`${o}.key`,"a unique declared field key",`duplicate ${JSON.stringify(s.key)}`);if(n.add(s.key),!Object.hasOwn(s,"value")||void 0===s.value)throw new dn(`${o}.value`,"a value","undefined");return{key:s.key,value:s.value}})}(n.declared_fields)),void 0!==n.fulfillment&&Object.assign(i,function(e){const t="input.checkout.fulfillment",n=In(e,t);if(!Array.isArray(n.methods))throw new dn(`${t}.methods`,"an array",Pn(n.methods));if(n.methods.length>1)throw new dn(`${t}.methods`,"at most 1 fulfillment method",`${n.methods.length} methods`);let i={..._n};const s=[];for(const[r,a]of n.methods.entries()){const e=`${t}.methods[${r}]`,n=In(a,e),d=kn(n.type??"shipping",`${e}.type`),{id:c}=En(n,{id:void 0},e),l={...void 0!==c&&{id:c}},u=void 0===n.groups?[]:Sn(n.groups,`${e}.groups`),p=wn(n,e);switch(d){case"pickup":void 0===p&&Cn(n.destinations,`${e}.destinations`),s.push({...l,type:d,...void 0!==p&&{selected_destination_id:p},groups:u});break;case"shipping":i=void 0===p?An(n,e):{saved_address_id:p},s.push({...l,type:d,groups:u});break;default:o(d)}}return{shippingAddress:i,fulfillmentMethods:{methods:s}}}(n.fulfillment)),t.ignorePayment||void 0===n.payment||(i.payment=pn(n.payment,{path:"input.checkout.payment",savedPaymentMethodsOnly:t.savedPaymentMethodsOnly})),i}(e,t);return function(e,t){return{...e,...t,buyer:{...e.buyer,...t.buyer}}}({buyer:{...yn},discountCodes:[],declaredFields:[],shippingAddress:{..._n},fulfillmentMethods:{methods:[]},payment:void 0},n)}(y,{savedPaymentMethodsOnly:g,ignorePayment:g?!s.isPaymentRequired.value:!Y(s)});v.payment&&"handler_id"in v.payment&&p.paymentCredentialSupplied(v.payment),p.updateCheckoutPartialInput(function(e,{checkout:t,paymentInstrument:n}){const i=Tn(e)&&Tn(e.checkout)?e.checkout:{},o="shopPay"===t.identity.current.value,s=Boolean(t.proposal.negotiated.fields.isS
1hippingRequired.value);return{buyer:!o&&void 0===i.buyer,fulfillment:s&&void 0===i.fulfillment,payment:Y(t)&&G(n.value)&&void 0===i.payment}}(y,{checkout:s,paymentInstrument:n}));const b=h();if(!b||i?.aborted)return ue();if("/review"===d.currentUrl.value.normalizedPath&&d.navigate("/"),v.payment&&"instrument_id"in v.payment&&!c())return ue();const{loadPickupLocalityServices:k}=b;let C;const w=new Wt({ucpBuyer:e,isSubmitting:t,paymentInstrument:n,checkout:s,shop:r,shopPay:a,getSavedCardSelector:c,observability:p,declaredFields:m,...b,readSavedCards:u,getFulfillmentController:f,resolvePickupLocality:k?async e=>(C=await k(),C.resolvePickupLocality(e)):void 0,announcePickupLocality:e=>C?.announcePickupLocality(e),get negotiator(){return b.negotiator}});let A=!1;const S=new Promise(e=>{_=setTimeout(()=>{A=!0,e("timeout")},3e4)}),I=await Promise.race([w.applyUpdate(v,{isExpired:()=>A||Boolean(i?.aborted)}),S]);return"timeout"===I?(p.log({name:"web_mcp_update_timed_out",message:"[WebMcp] Update did not finish in time; update outcome is unknown",attributes:{timeoutMs:3e4}}),pe()):Q(I)?I:l()??pe()}catch(g){return g instanceof dn?le(g,"update the checkout"):(p.error({error:new $n}),pe("internal_error"))}finally{clearTimeout(_)}}(y),s)}}function Bn(e){if("object"!=typeof e||null===e||!("error"in e))return"unknown";const{error:t}=e;return"object"==typeof t&&null!==t&&"code"in t?(n=t.code,Z.includes(n)?t.code:"unknown"):"unknown";var n}function Fn(e,t,n,i){const o=Math.round(performance.now()-i),s=function(e){return"object"==typeof e&&null!==e&&"error"in e&&"object"==typeof e.error}(n),r={tool:t,outcome:s?"error":"success",...s&&{errorCode:Bn(n)}};e.log({name:"web_mcp_tool_executed",message:"[WebMcp] tool executed",attributes:{...r,...te(n),durationMs:o}}),e.histogram({name:"web_mcp_tool_execution",value:o,unit:"ms",attributes:r})}function Gn(e,{activeTool:t,observability:n,checkout:i}){const o=e.name;return{...e,execute:async(...s)=>{const r=performance.now();if("navigate_to_storefront"===t.current||"navigate_to_storefront"===o&&void 0!==t.current){const e=Mt(ne("checkout_busy","Another checkout tool is running. Wait for it to finish before retrying."),i);return Fn(n,o,e,r),e}return t.during(o,async()=>{const t=await e.execute(...s);return Fn(n,o,t,r),t})}}}performance.mark("checkout:web-mcp-runtime-loaded",{detail:{url:import.meta.url}});class Yn extends Error{constructor(e,t){super(`WebMCP tool registration failed for ${e}: ${String(t)}`),this.name="WebMcpRegistrationError",t instanceof Error&&(this.cause=t)}}function Wn(e,i){const{modelContext:o,signal:s,isSubmitting:a,paymentInstrument:d,checkout:c,i18n:l,shop:u,shopPay:p,url:h,router:m,observability:f,activeTool:y,onActiveToolCreated:_,getPreactContext:g,markToolCallStarted:v,getSavedCardSelector:b,declaredFields:k,getFulfillmentProvider:C,getStoreCreditProvider:T,unregisterInitializingTool:E}=e;if(s.aborted)return;const N=new Ot({observability:f,checkout:c}),P=r(i,{checkout:c}),L=function({checkout:e,shopPay:t}){const n=X({identity:e.identity,shopPay:t,negotiatedFields:e.proposal.negotiated.fields},{isApplePayAvailable:t.user.isApplePayAvailable}),i=e.proposal.negotiated.fields.paymentMethods,o=t.session.isInstallmentsSelected,s=e.installments.paymentMethodMustSupportInterestBearingLoans;return()=>{if("shopPay"!==e.identity.current.value||t.session.isLoading.value)return;const r=t.user.paymentMethods.value.filter(w).filter(({id:e})=>e!==A).sort(S),a=I(r,n.value),d=t.session.selectedPaymentMethod.value,c=e.proposal.proposed.paymentLines.value.some(({method:e})=>"wallet"===e.type&&"SHOP_PAY"===e.name);return r.map(e=>{const t=e.paymentAttributes;return{instrument:{id:e.id,type:"card",selected:c&&"CREDIT_CARD"===d?.paymentMethod&&d.id===e.id,display:{brand:t.brand,last_digits:t.lastDigits}},usable:!t.expired&&t.verified&&a.includes(e)&&!z(t,i,o,s)}})}}({checkout:c,shopPay:p}),D=e=>function({checkout:e,ucp:t,i18n:n,shop:i,router:o,readMode:s="negotiated",savedCards:r,declaredFields:a=new Map,paymentInstrument:d}){const c=bt({...At(e,t,n,i,s,o),savedCards:e.isPaymentRequired.value?r:void 0});if(!c)return;const l=(u=a,Array.from(u.values()).flatMap(e=>{const t=e.read();return t?[t]:[]}).sort((e,t)=>
1function(e,t){return e===t?0:e<t?-1:1}(e.key,t.key)));var u;const p=c.payment.instruments[0],h={...c,...d?{payment:{instruments:[wt(d,e,p&&"billing_address"in p?p.billing_address:{})]}}:{},...l.length>0?{declared_fields:l}:{}},m=e.proposal.proposed.locationAddress.value,f=h.fulfillment?.methods,[y]=f??[];return 1===f?.length&&"pickup"===y?.type&&m?.countryCode&&m.postalCode&&m.coordinates?{...h,context:{address_country:m.countryCode,...m.zoneCode&&{address_region:m.zoneCode},postal_code:m.postalCode}}:h}({checkout:c,ucp:P,i18n:l,shop:u,router:m,readMode:e,savedCards:L(),declaredFields:k,paymentInstrument:d.value}),M=function(e){const t={key:Tt,read(){const t=Nt(e);if(!t)return;const{title:n,value:i,required:o}=t.fields;return{key:Tt,purpose:"dev.shopify.shopping.declared_fields.generic",title:n.value,description:`Enter the buyer's ${n.value} tax number for this checkout.`,value_schema:{type:"string"},value:i.value||null,required:o.value??!1}},prepare:n=>null!==n&&"string"!=typeof n?{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 t=Nt(e);if(!t)return!1;const{value:i}=t.fields;return i.value=n??"",!0}}};return t}(c);k.set(M.key,M);const R=function(e){const n=(e,t)=>e.hasGiftCard.value?"cannot change while the cart contains a gift card":e.hasFixedSellingPlan.value?"cannot change while the cart contains a fixed-date subscription":e.settling.value?"is still updating from a previous change; retry shortly":t&&0===e.paymentDue.value?.amount&&!e.applied.value?"cannot be applied when nothing is left to pay":void 0;return{key:It,read(){const t=e();if(t?.available.value)return{key:It,purpose:"dev.shopify.shopping.declared_fields.generic",title:"Store credit",description:"Apply the buyer's available store credit balance to this checkout. Send true to apply and false to remove; omitting the field or sending null keeps the current choice. Removing it also stops store credit from covering subscription renewals.",value_schema:{type:"boolean"},value:t.redeeming.value,required:!1}},prepare(i){if(null!==i&&"boolean"!=typeof i)return{requirement:"must be a boolean or null"};const o=i??void 0,s=e();if(!s)return{requirement:"is no longer offered on this checkout"};if(void 0!==o&&o!==s.redeeming.value){const e=n(s,o);if(e)return{requirement:e}}return{phase:"negotiate",get changed(){if(void 0===o)return!1;const t=e();return!!t&&(o!==t.redeeming.value||t.settling.value)},async apply(){if(void 0===o)return!1;const i=e();return!(!i||(await(e=>{if(!e.settling.peek())return Promise.resolve();let n,i=()=>{};return new Promise(o=>{n=setTimeout(o,1e4),i=t(()=>{e.settling.value||o()})}).then(()=>{clearTimeout(n),i()})})(i),e()!==i||!i.available.value||void 0!==n(i,o)||(await i.setRedeeming(o),i.applied.peek()!==o)))}}}}}(()=>T?.());k.set(R.key,R);const O=y??new J;_?.(O);const x=function(e,t){const n=e.name;return{...e,execute:(...i)=>{const o=performance.now(),s=e.execute(...i);return Fn(t,n,s,o),s}}}(function({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. ${Ln}`,inputSchema:{type:"object",properties:{}},annotations:{consequentialHint:!1,readOnlyHint:!0,untrustedContentHint:!0},execute:()=>Mt(function(){try{return t("processed"===e.latestReceipt.value?.status?"negotiated":"proposed")||ne("internal_error",`Checkout data is not available yet. ${oe} ${ie("read checkout state")}`)}catch{return n.error({error:new On}),ne("internal_error",`Unable to read the checkout. ${ie("read checkout state")}`)}}(),e)}}
1({checkout:c,readCheckout:D,observability:N}),N),U=[{tool:x,signal:s}],q=function(e,n){const i=new AbortController,o=t(function(){"processed"===e.latestReceipt.value?.status&&(this.dispose(),i.abort())});return n.addEventListener("abort",()=>{o(),i.abort()},{once:!0,signal:i.signal}),i.signal}(c,s);q.aborted||U.push(...[Hn({ucpBuyer:P.checkout.buyer,isSubmitting:a,paymentInstrument:d,signal:s,checkout:c,shop:u,shopPay:p,router:m,getSavedCardSelector:b,readCheckout:D,readSavedCards:L,observability:N,getPreactContext:g,declaredFields:k,getFulfillmentController:()=>{const e=C?.();return e?function(e,{proposed:t}){return{getAvailableMethodTypes:()=>e.getAvailableMethodTypes().filter(e=>!e.includes("PICKUP_POINT")),setDesiredMethod(i,o){const s=e.getSelectedMethodTypes();e.markBuyerSelection();const r=t.deliveryLines.value.map(e=>e.value),a=Pt(t.merchandiseLines.value,r);var d,c;c=i,(d=s).length>0&&d.every(e=>"SHIPPING"===e||"LOCAL"===e?c.includes("SHIPPING")||c.includes("LOCAL"):c.includes(e))?n(()=>{for(const e of t.deliveryLines.value){const t=e.value;t.targetMerchandiseLines.some(({stableId:e})=>a.has(e))&&(t.deliveryMethodTypes.length!==i.length||t.deliveryMethodTypes.some(e=>!i.includes(e)))&&(e.value={...t,deliveryMethodTypes:i})}if(e.reconcileSameMethod(i),o){if(o!==t.locationAddress.value)for(const e of t.deliveryLines.value)e.value={...e.value,deliveryMethodHandle:void 0};t.locationAddress.value=o}}):e.applyMethodChange(i,s,o)}}}(e,c.proposal):void 0}}),Rn({ucpBuyer:P.checkout.buyer,isSubmitting:a,paymentInstrument:d,signal:s,checkout:c,shop:u,shopPay:p,readCheckout:D,readSavedCards:L,observability:N,getPreactContext:g,declaredFields:k})].map(e=>({tool:Gn(e,{activeTool:O,observability:N,checkout:c}),signal:q}))),Un({shop:u,url:h})&&U.push({tool:Gn(qn({checkout:c,shop:u,url:h,observability:N,signal:s,getPreactContext:g}),{activeTool:O,observability:N,checkout:c}),signal:s}),E?.(),N.watchReceipts(s);const j=U.map(async({tool:e,signal:t})=>{try{return await o.registerTool({...e,execute:(t,n)=>(v(),N.toolCalled(e.name),e.execute(t,n))},{signal:t}),"registered"}catch(n){return t.aborted?"withdrawn":(N.error({error:new Yn(e.name,n)}),"failed")}});return Promise.all(j).then(e=>{if(s.aborted)return;const t=e.filter(e=>"registered"===e).length;N.log({name:"web_mcp_tools_registered",message:"[WebMcp] tools registered",attributes:{registered:t,failed:e.filter(e=>"failed"===e).length}}),t>0&&N.initialized()}).catch(()=>{}),O}export{Wn as registerWebMcpTools};
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.