PageSourceSearch

https://store.carm.org/cdn/shopifycloud/checkout-web/assets/c1/6f1b819b.Bha_HLC8.js

js carm.org collected 2026-10-01 10:40:40 UTC 88,249 bytes, 1 lines download raw bytes

1import{c as e,j as t,n,a as i,b as o}from"./2c1ab0fe.D_oO1jU7.js";import{s,c as r,a,R as d,b as c,i as l,d as u,n as p,r as h,e as f,f as m,g as y,h as _,C as g,V as v,p as b,j as k,k as C,U as A,l as w,m as S,o as I,q as T,F as E,t as N,u as P,v as L,w as D,x as M,y as R,z as O,A as x,B as U}from"./4c290a1e.D9lE9kmU.js";import{c as q,i as $,a as j}from"./65f3d4da.8ZfwXSRH.js";import{c as H}from"./cadec7c0.nE7SeHjK.js";import{i as B}from"./8599b02a.yKiXuwTF.js";import{s as F}from"./08a3b809.CkE7TqUZ.js";import{a as G,i as Y}from"./6a2fc6d6.F1jyoAIB.js";class W{#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 X(e){return"object"==typeof e&&null!==e&&"error"in e}const V=Symbol("WebMcpFailureDetails");function K(e){if(!X(e))return;const t=e.error;return"object"==typeof t&&null!==t&&V in t?t[V]:void 0}function J(e,t,n){const i={code:e,message:t};return n&&Object.defineProperty(i,V,{value:n}),{error:i}}function Q(e){return`Do not attempt to ${e} by interacting with the page.`}const Z="Retry shortly.",ee=`Checkout is still initializing. ${Z}`,te="Nothing was applied.",ne=`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. ${Q("update the checkout")}`,ie=`Checkout completion could not be confirmed. Call get_checkout for the current state and its messages before retrying. ${Q("complete the checkout")}`;function oe(e,t,n,i="Call get_checkout before retrying."){return J(e,`${t}: ${n} ${te} ${i}`)}function se(e,t){return J("invalid_request",`${e.message} Correct the input and retry. ${Q(t)}`,{invalidInputPath:e.loggablePath.replace(/\[\d+\]/g,"[]"),invalidInputExpected:e.expected})}function re(){return J("internal_error",`Checkout is not available for updates. ${Z} ${Q("update the checkout")}`)}function ae(e="update_failed"){return J(e,ne)}function de(e){return J("rejected",`The selected delivery option does not support selected_option_details.${e}. ${te} Remove ${e} from selected_option_details or choose an option that supports it, then retry. ${Q("update the checkout")}`)}const ce=`${te} Group and option ids come from the latest get_checkout and change when the destination or fulfillment method changes. Use ids from the latest get_checkout. If this request also changes the destination, send it without groups, then choose an option from the next get_checkout. ${Q("update the checkout")}`;function le(e){return oe("rejected","fulfillment",e)}function ue(e,t){return oe("rejected",e,`${t}.`)}function pe(){return J("completion_in_progress","A credentialed completion is in progress. Wait for it to finish before updating payment.")}function he(){return J("internal_error",`${ee} ${Q("complete the checkout")}`)}function fe(e="completion_failed",t){return J(e,ie,t)}function me(){return J("navigation_failed","Navigation was cancelled. The tool did not leave checkout.")}function ye(){return J("checkout_busy","Checkout submission or payment is in progress. Wait for it to finish and call get_checkout before navigating away.")}function _e(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 ue(`${e}.key`,"must identify a declared field available in the current checkout");const o=n.prepare(a);if("requirement"in o)return ue(`${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 ue("$.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 ge(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 ve(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=ge(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:ge(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 be(e,{extendedAddressMode:t}){const n=e.address_country?.toUpperCase()??"",i=t.get(n),o=null===i?function(e,t){const n=Ce(t);return{address1:"line"in n?n.line:Le(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=s(e,t.line,!0);if(!n?.streetNumber)return{address1:t.line};const i=r({countryCode:e,streetName:n.streetName??"",streetNumber:n.streetNumber});return null==i?{address1:t.line}:{address1:i,packedLine2:n.line2}}const n=r({countryCode:e,...t});return null==n?{address1:De(t)}:{address1:n,...t}}(e,Ce(t)),{neighborhood:d,...c}=function(e,{extended_address:t="",district:n},i){const o=a(e,t);if(!o)return{address2:Ae(t,i)};const s=Ae(o.line2??"",i),r=n??o.neighborhood??"";return{address2:Pe(e,s,r),line2:s,neighborhood:r}}(e,t,i);return{...o,...c,..."dedicated"===n?void 0!==d&&{district:d,neighborhood:""}:{neighborhood:d}}}(n,e,i);return{...H({...e,street_address:o.address1,extended_address:o.address2}),company:e.company??"",district:void 0,subdistrict:void 0,...o}}function ke(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?we(n,e):Te(n,e,i),address_locality:e.city,address_regi
1on:e.zoneCode,address_country:e.countryCode,postal_code:e.postalCode}}function Ce({street_address:e="",street_name:t,street_number:n=""}){return t?.trim()?{streetName:t,streetNumber:n}:{line:e}}function Ae(e,t){return t&&t!==e.trim()?Me(e,t):e}function we(e,t){return{street_address:Se(e,t),extended_address:Ie(e,t)}}function Se(e,{address1:t,streetName:n,streetNumber:i}){return t||!n&&!i?t:Ne(e,{streetName:n??"",streetNumber:i??""})}function Ie(e,{address2:t,line2:n,district:i,neighborhood:o}){const s=i||o;return null!=n||s?Pe(e,n??"",s??""):t}function Te(e,t,n){const i=function(e,t,n){return"dedicated"!==n||null==t.streetName&&null==t.streetNumber?t.address1?.includes(d)?s(e,t.address1):null:t}(e,t,n);return{...i?.streetName?{street_name:i.streetName,street_number:i.streetNumber??""}:{street_address:Se(e,t)},...Ee(e,t,n)}}function Ee(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(d)?a(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 Ne(e,t){return r({countryCode:e,...t})??De(t)}function Pe(e,t,n){return c({countryCode:e,line2:t,neighborhood:n})??Me(t,n)}function Le(e,t){return Ne(e,t).split(d).join("")}function De({streetName:e,streetNumber:t}){return[t,e].filter(Boolean).join(" ")}function Me(e,t){return[e,t].filter(Boolean).join(", ")}function Re(e){return e?.flatMap((e=>(e.lineComponents.length?e.lineComponents:[e]).filter((e=>e.requiresShipping)).map(Oe)))??[]}function Oe(e){return e.stableId}function xe(e){return"SHIPPING"===e||"LOCAL"===e||l(e)}function Ue(e,t,n){return Boolean(e&&!n&&(t.some((e=>!xe(e)))||t.some(l)&&t.some((e=>"SHIPPING"===e||"LOCAL"===e))))}function qe(e,t){switch(t){case"phone_number":return Boolean(e.phoneRequired);case"instructions":return Boolean(e.acceptsInstructions)}}function $e(e,t){if(!e?.length||!t?.length)return!1;const n=new Set(t),i=e.filter((e=>e.requiresShipping)).map((e=>Oe(e)));return i.length===n.size&&i.every((e=>n.has(e)))}const je="pickup";function He(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 l(n)?"pickup":"shipping"}function Be(e){const t=e.filter((e=>"pickup"===He(e))),n=t.map((e=>{const t=new Map;for(const n of e.methods){if(!n.pickupLocation)continue;const i=Fe(n.pickupLocation);t.has(i)&&n.handle!==e.selectedDeliveryMethodHandle||t.set(i,n)}return t})),i=n[0];if(!i)return[];const o=[];for(const[s,r]of i){const e=[];for(const[i,o]of t.entries()){const t=n[i].get(s);if(!t)break;e.push({line:o,method:t})}e.length===t.length&&o.push({id:r.handle,selections:e})}return o}function Fe(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 Ge=ke;function Ye(e,t){const n=new Set(t.flatMap((e=>e.targetMerchandiseLines?.map(Oe)??[]))),i=new Map,o=new Set;for(const s of e.merchandiseLines??[]){if("proposed"!==e.readMode&&!s.requiresShipping)continue;const t=Oe(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(Oe(e)))).map(Oe));if(!r.size)continue;const a=e.proposedDeliveryLines?.filter((e=>e.targetMerchandiseLines.some((e=>Oe(e)===t||r.has(Oe(e)))))).flatMap((e=>e.deliveryMethodTypes)),d=a?.length&&a.every(l)?"pickup":"shipping",c=i.get(d)??[];c.push(..."proposed"===e.readMode?r:[t]),i.set(d,c)}return i}function We(e){return[...Ye(e,[])].map((([t,n])=>({id:t,type:t,line_item_ids:n,destinations:[],..."shipping"===t?Ke(e):{},groups:[]})))}function ze(e){const t=new Set;for(const n of e){const e=He(n);e&&t.add(e)}return Array.from(t)}function Xe(e){return"SHIPPING"===e||"LOCAL"===e||l(e)}function Ve(e,t,n){if("shipping"===e)return Ke(n);const i=Be(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:Ge(n.address,t)}:void 0}(t[0].method,n.addressContext);return i?[{...i,id:e}]:[]})),...o&&{selected_destination_id:o.id}}}function Ke({savedDestinations:e,shippingAddress:t,addressContext:n}){if(void 0===e)return t&&f(t)?{destinations:[Je(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})=>u(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",...Ge(t,n)}))),...o&&{selected_destination_id:o}}:{}}function Je(e,t){return{...Ge(e,t),id:Qe(e),type:"shipping_address"}}function Qe(e){return["shipping",e.countryCode,e.postalCode].filter(
1Boolean).join("-").replace(/\s+/g,"")}function Ze(e,t){const n=et(e),i=p(e),o=e.proposedLine?e.selectedDeliveryMethodHandle:i?.handle,s=o?function(e,t,n){const i=function(e,t,n=et(e)){return t?.find((t=>Boolean(e.id)&&t.id===e.id))??t?.find((e=>$e(e.targetMerchandiseLines,n)))}(e,n,t);if(!i||!e.selectedDeliveryMethodHandle||i.deliveryMethodHandle!==e.selectedDeliveryMethodHandle)return;const o=i.deliveryMethodOptions;if(!o)return;const s=p(e),r=s&&!qe(s,"phone_number")?void 0:o.phone,a=s&&!qe(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"===He(e),a=r?[{...i?tt(i):{totals:[]},id:je,title:"Pickup"}]:e.methods.filter((({methodType:e})=>"SHIPPING"===e||"LOCAL"===e)).map(tt);return{id:e.id??"",line_item_ids:n,options:a,...o&&{selected_option_id:r?je:o},...s&&{selected_option_details:s}}}function et(e){return e.targetMerchandiseLines?.filter((e=>e.requiresShipping)).map((e=>Oe(e)))??[]}function tt(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:l(e.methodType)?"Pickup":"Shipping",amount:ge(e.costAfterDiscounts)}]}}function nt(e){return"available"===e.status}const it=new Map([["terms-of-service","terms_of_service"],["privacy-policy","privacy_policy"],["refund-policy","refund_policy"],["shipping-policy","shipping_policy"]]);function ot(e){const t=[];for(const{handle:n,url:i}of e){const e=it.get(n);e&&t.push({type:e,url:i})}return t}const st={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 rt(e){return st[e]}const at=new Set(["AcceptNewTermViolation","RequiredArtifactsUnavailableViolation"]),dt=new Set(["PendingTermViolation"]),ct=new Set(["PAYMENTS_UNACCEPTABLE_PAYMENT_AMOUNT"]),lt={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 ut(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 pt({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:ge(e)}),c.push(...function({currencyCode:e,discountLines:t,itemsDiscountAmount:n,cartLevelDiscountAmount:i}){let o=i;for(const r of t?.lines??[])if($(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:ge({amount:-n,currencyCode:e})}),o>0&&s.push({type:"discount",display_text:"Discount",amount:ge({amount:-o,currencyCode:e})}),s}({currencyCode:e.currencyCode,discountLines:i,itemsDiscountAmount:t,cartLevelDiscountAmount:n}))),null!=o&&c.push({type:"fulfillment",display_text:"Shipping",amount:ge(o)}),null==r||a||c.push({type:"duty",display_text:"Duties",amount:ge(r)}),null!=s&&c.push({type:"tax",display_text:"Taxes",amount:ge(s)}),null!=d&&c.push({type:"total",display_text:"Total",amount:ge(d)}),c}function ht(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 o of e)for(const{discountDetails:e,amount:s}of o.allocations)"presentationLevel"in(i=e.discount)&&"CART"===i.presentationLevel?n+=s.amount:t+=s.amount;var i;return{lineLevel:t,cartLevel:n}}(e.lineAllocations),a=[];
1n+=r,o&&a.push({type:"subtotal",amount:ge(o)}),0!==s&&o&&(t+=s,a.push({type:"items_discount",amount:ge({...o,amount:-s})}));const d=o?{...o,amount:o.amount-s}:e.totalPrice;return a.push({type:"total",amount:ge(d)}),{id:Oe(e),...e.parentRelationship?.parent?.stableId?{parent_id:e.parentRelationship.parent.stableId}:{},quantity:e.quantity,item:{id:e.variantId??e.stableId,title:e.title,price:ge(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=p(s);t?.cost&&(n.push({cost:t.costAfterDiscounts.amount,costBeforeDiscounts:t.cost.amount,rateGroupKey:"SHIPPING"===t.methodType?h({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}=q(n,(({rateGroupKey:e})=>e));return{amount:o,currencyCode:i}}(e),a="processed"===e.receipt?.status&&e.receipt.isRedacted?void 0:function(e){const{email:t,phone:n}=e??{};if(t||n)return{...t?{email:t}:{},...n?{phone_number:n}:{}}}(e.contactInfo),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=ve(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 We(e);const n="filled"!==t?.status&&"partial"!==t?.status||!t.lines?[]:t.lines.filter(nt),i=("proposed"===e.readMode?function(e,t,n){const i=new Map;for(const o of n??[]){i.set(Oe(o),Re([o]).length>0);for(const e of o.lineComponents)i.set(Oe(e),e.requiresShipping)}return(t??[]).map((t=>{const n=t.targetMerchandiseLines.filter((e=>e.requiresShipping)).map((e=>Oe(e))),o=e.find((e=>void 0!==t.id&&e.id===t.id))??e.find((e=>e.type===t.type&&$e(e.targetMerchandiseLines,n)));return{...o,status:"available",id:t.id,type:t.type,targetMerchandiseLines:t.targetMerchandiseLines.flatMap((e=>{const t=i.get(Oe(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(Xe):e.methods.some((e=>Xe(e.methodType))))&&e.targetMerchandiseLines?.some((e=>e.requiresShipping))));if("proposed"===e.readMode&&!i.length)return We(e);const o="partial"===t?.status?Ye(e,i):new Map,s=new Set([...ze(i),...o.keys()]),r=[];for(const a of s){const t=i.filter((e=>He(e)===a)),n=t.map((t=>Ze(t,t.proposedLine?[t.proposedLine]:e.proposedDeliveryLines))),s=[...new Set([...n.flatMap((e=>e.line_item_ids)),...o.get(a)??[]])];r.push({id:a,type:a,line_item_ids:s,destinations:[],...Ve(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=_(o)}=e,r=function(e){const t=[];for(const n of e.violations??[]){if(at.has(n.__typename))continue;if(ct.has(n.code))continue;if(e.requiresCaptcha&&g.has(n.code))continue;const i=n.code.startsWith("DISCOUNTS_"),o=i||dt.has(n.__typename),s=rt(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:ut(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(lt),{status:a,messages:r}}({i18n:e.i18n,requiresBuyerReview:null!=e.buyerReviewUrl,requiresCaptcha:e.requiresCaptcha,violations:e.violations,receipt:e.receipt,isShippingRequired:"proposed"===e.readMode?Re(t).length>0:e.isShippingRequired,hasShippingAddress:"proposed"===e.readMode?f(e.shippingAddress):null!=e.shippingAddress,deliveryNext:e.deliveryNext,skipsShippingAddress:"proposed"===e.readMode?mt(c,t):void 0,hasUnselectableShippingGroup:ft(c,t,e.readMode)}),v=function(e){if("processed"!==e?.status)return;const t=e.orderIdentity.buyerIdentifier,n=m(e.orderIdentity.id);return{...n?{id:y("Order",n)}:{},...t?{label:t}:{},permalink_url:e.confirmationPage.url}}(e.receipt),b=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:ke(e,t)}]:[]}}(e.billingAddress,e.addressContext,e.savedCards),k=(C=e.savedCards??[]).some((({instrument:e,usable:t})=>e.selected&&!t))?[{type:"error",severity:C.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 C;const A=[...u,...k];return{...e.id?{id:e.id}:{},...e.continueUrl?{continue_url:e.continueUrl}:{},currency:e.runningTotal.currencyCode,status:"ready_for_complete"===l&&k.length?"incomplete":l,..."requires_escalation"===l&&e.buyerReviewUrl?{continue_url:e.buyerReviewUrl}:{},links:ot(e.merchantPolicies),line_items:i,totals:pt({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:b,...A.length?{messages:A}:{},...v&&{order:v}}}function ft(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=Re([e]);return t.length>0&&!i.has(Oe(e))&&!t.every((e=>i.has(e)))}))}function mt(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(Oe(e))||Re([e]).every((e=>n.has(e)))))}function yt(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 _t(e,t,n,i,o){const{proposed:s,negotiated:r}=e.proposal,a=e.addressManager.shipping.value,d="shopPay"===e.identity.current.value?a:void 0,c=d?[...d.addresses.value,...d.immutableAddresses.value]:void 0,l=r.fields.shippingAddress.value,u=o?.currentUrl.value,p=s.captcha.value;return{i18n:t,readMode:i,requiresCaptcha:Boolean("hcaptcha"===p?.provider&&p.sitekey&&(!p.token||p.violationCode)),buyerReviewUrl:"/review"===u?.normalizedPath?u.href:void 0,id:r.fields.ucp.value?.id,continueUrl:r.fields.ucp.value?.continueUrl,merchantPolicies:n.merchantPolicies,merchandiseLines:"proposed"===i?{lines:s.merchandiseLines.value}:r.fields.merchandiseLines.value,subtotal:r.fields.subtotal.value,discountLines:"proposed"===i?{lines:s.discountLines.value}:r.fields.discountLines.value,tax:e.proposal.facts.tax??(f=r.fields.taxes.value,"available_total"===f?.status?f.totalTax:void 0),duty:e.proposal.facts.duty??(h=r.fields.duties.value,"available_total"===h?.status?h.totalDuty:void 0),dutiesIncluded:Boolean(r.fields.dutiesIncluded.value)||Boolean(e.proposal.facts.dutiesIncluded),runningTotal:r.fields.runningTotal.value,contactInfo:"proposed"===i?{email:s.email.value,phone:s.phone.value}:r.fields.contactInfo.value,deliveryNext:r.fields.deliveryNext.value,shopId:n.id,marketDrivenShippingEnabled:n.marketDrivenShippingEnabled,remoteShopsConfigMap:n.remoteShopsConfigMap,remoteMerchandiseDetails:r.fields.remoteMerchandiseDetails.value,shippingAddress:"proposed"===i?s.shippingAddress.value:l,billingAddress:"shopPay"===e.identity.current.value?void 0:gt(e,n,i),addressContext:e.address,savedDestinations:c,proposedDeliveryLines:s.deliveryLines.value.map((e=>
1e.value)),isShippingRequired:Boolean(r.fields.isShippingRequired.value),violations:r.fields.allViolations.value,receipt:e.latestReceipt.value};var h,f}function gt(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===v.CreditCard||c.type===v.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||!b(s))return a;const d=s[0]?.method;if("wallet"===d?.type){const n=i.fields.runningTotal.value,o=n&&n.amount<=0,s=k(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 vt="store_credit";const bt="tax_number",kt=["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 Ct(e){const t=e.proposal.proposed.localizationExtensions.value.flatMap((e=>kt.some((t=>t===e.fields.key.value))?[e]:[]));return 1===t.length?t[0]:void 0}function At(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 wt(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 St(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 It(e,t){return{...e,ucp:St(X(e)?"error":"success",t.proposal.negotiated.fields.ucp.value?.paymentHandlers)}}class Tt{#n;#i;#o;#s=!1;#r=!1;#a=!1;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.#d("web_mcp_initialized")}toolCalled(e){this.#s||(this.#s=!0,this.#d("web_mcp_tool_called",{tool:e})),this.#r||"update_checkout"!==e&&"complete_checkout"!==e||(this.#r=!0,this.#d("web_mcp_write_tool_called",{tool:e})),this.#a||"complete_checkout"!==e||(this.#a=!0,this.#d("web_mcp_complete_checkout_called"))}#d(e,t={}){this.#o||this.#n.counter({name:e,value:1,attributes:{...t,identity:this.#i.identity.current.peek()}})}}function Et(e){return e?.replace(/[\s-]/g,"").toUpperCase()}function Nt(e,{checkout:t},n){const i=e.fulfillmentMethods.methods;if(i.length>1)return le("At most one fulfillment method is supported.");const o=i[0];if(void 0!==o?.id&&o.id!==o.type)return le("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=At(s.merchandiseLines.value,a),c=wt(a,d);if(c.some(l)&&c.some(Pt)){const e=r.fields.deliveryNext.value,t="filled"===e?.status||"partial"===e?.status?e.lines.filter((e=>"available"===e.status)):[],n=wt(a.map((e=>{const n=t.find((({id:t})=>Boolean(e.id)&&t===e.id))??t.find((t=>$e(t.targetMerchandiseLines,e.targetMerchandiseLines.filter((e=>e.requiresShipping)).map(Oe)))),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(l)&&n.some(Pt))return le("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 u=o?.type??(c.length&&c.every(l)?"pickup":void 0),p=Boolean(e.context&&!Lt(s.locationAddress.value,e.context));if(p&&"pickup"!==u)return le("Changing context locality requires a pickup method.");if(!o&&"pickup"!==u)return;const h=e=>"pickup"===u?l(e):Pt(e);if(o&&(void 0!==o.selected_destination_id||o.groups.length))return p||c.length&&!c.some(h)?le("Change the method/search origin first, then select a destination or option returned by that update."):void 0;if("pickup"===u&&c.length&&c.every((e=>"PICKUP_POINT"===e)))return p?le("Pickup-point locality discovery is not supported. Select an existing destination instead."):void 0;if(!d.size)return le("This checkout has no physical items to fulfill.");if("pickup"===u&&e.context){const t=s.shippingAddress.value?.countryCode||s.locationAddress.value?.countryCode;if(!t)return le("Pickup search requires an established checkout country. Ask the buyer to choose a country in checkout.");if(e.context.address_country!==t)return le("Pickup search must remain in the checkout country.")}if(!n&&!p&&c.every(h)&&c.length)return;const f=!c.length||!c.every(h);if(!n&&f)return le("The delivery selector is not ready.");const m=n?n.getAvailableMethodTypes().find((e=>"pickup"===u?e.includes("PICK_UP"):e.some(h))):c;if(!m)return le(`The checkout does not offer ${u}.`);const y=r.fields;return(f||p)&&(y.mustSelectProvidedShippingRate.value||y.mustSelectProvidedAddress.value||!1===y.canUpdateDeliveryAddress.value)?le("The checkout locks its delivery method or address."):{methodTypes:m,needsLocalityLookup:p,changesMode:f}}function Pt(e){return"SHIPPING"===e||"LOCAL"===e}function Lt(e,t){return function(e,t){return Boolean(e?.coordinates)&&e?.countryCode===t.countryCode&&(!t.zoneCode||e.zoneCode===t.zoneCode)&&Et(e.postalCode)===Et(t.postalCode)}(e,{countryCode:t.address_country,zoneCode:t.address_region,postalCode:t.postal_code})}const Dt={status:"written"};const Mt=({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 zt(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(),Dt):{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=zt(e.address_country,"fulfillment.methods[0].destinations[0].address_country",t.shop);if(r)return r;const a=be(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(),Dt)}}};function Rt(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)?Dt:{status:"failed"}}}:{status:"rejected",field:"payment"}}function Ot({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(Kt):[],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(xe).length)continue;const o=r.find((t=>
1Boolean(e)&&t.id===e))??r.find((e=>$e(e.targetMerchandiseLines,t.filter((e=>e.requiresShipping)).map(Oe)))),s=o?.methods.find((e=>e.handle===i));if(s){if(!xe(s.methodType))continue}else if(Ue(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:Be(n).find((({id:t})=>t===e.selected_destination_id));if(void 0!==e.selected_destination_id&&!i)throw new Gt("unknown_pickup_destination");const o=new Map;for(const s of e.groups){if(s.selected_option_id!==je)throw new Gt("unknown_fulfillment_option");const e=Xt(s,n);if("pickup"!==He(e)||i&&!i.selections.some((t=>t.line===e))||o.has(e))throw new Gt("unknown_fulfillment_group");o.set(e,s)}return i?i.selections.map((({line:e,method:n})=>Vt(e,n,o.get(e)?.selected_option_details,t))):[...o].map((([e,n])=>{const i=e.methods.find((t=>t.handle===e.selectedDeliveryMethodHandle&&l(t.methodType)&&t.pickupLocation));if(!i)throw new Gt("unknown_pickup_destination");return Vt(e,i,n.selected_option_details,t)}))}(e,t,n):e.groups.map((e=>{const i=Xt(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"!==He(i))throw new Gt("unknown_fulfillment_option");return Vt(i,o,e.selected_option_details,t)}))))}(e,i.deliveryLines.peek(),r))a.set(t.deliveryLine,t)}catch(c){if(!(c instanceof Gt))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 t of i.deliveryLines.value){const i=a.get(t);if(!(i||n&&t.value.deliveryMethodTypes.some(xe)))continue;const{selectedOptionId:o,selectedOptionDetails:s}=i??{};t.value={...t.peek(),deliveryMethodHandle:o,deliveryMethodOptions:(e=s,{phone:e?.phone_number,instructions:e?.instructions}),...void 0===o&&{isCustomRate:void 0,customDeliveryStrategy:void 0}}}var e;return Dt}}}const xt=[({buyer:e},{checkout:t,shopPay:n})=>{const i=Y({identity:t.identity,proposal:t.proposal,shopPay:n});if(i&&"shopPay"===t.identity.current.value)return;const{proposed:o}=t.proposal;return{status:"ready",negotiation:{include:["contactInfo"],loading:["contactInfo"],fieldsToResolve:["contactInfo"]},apply:async()=>(i||(o.email.value=e.email),o.phone.value=e.phone_number,Dt)}},({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})),Dt}}},Mt,Ot];function Ut(e,t,{fulfillmentRequest:n,fulfillment:i,locationAddress:o}={}){const s=[];for(const r of xt){if(r===Mt&&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),Dt)})}const a=r===Ot?Ot(e,t,void 0!==n):r(e,t);if(void 0!==a){if("rejected"===a.status)return Ft(a.field,a.reason);s.push(a)}}return s}class qt{#c;constructor(e){this.#c=e}writePayment({payment:e,billingAddress:t=e?.billing_address,applyBilling:i=!0}){const o=i?this.#l(t):void 0,s=this.#u(e);return X(s)?s:(n((()=>{s?.apply(),o?.apply()})),{status:"applied"})}#l(e){const{checkout:t}=this.#c;if(!G(t))return;const i=void 0===e?void 0:be(e,t.address);return{apply({replacement:e=!1}={}){if(!G(t))return!1;const{proposed:o,negotiated:s,facts:r}
1=t.proposal,a=!1===s.fields.isShippingRequired.value;if(i&&!I(i)&&(a||!function(e,t){const n=ke(t.proposal.proposed.shippingAddress.value,t.address);return D(e,be(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===v.CreditCard||e.method.type===v.PayPal||function(e){if("wallet"!==e.method.type)return!1;switch(e.method.name){case"APPLE_PAY":return O(e);case"GOOGLE_PAY":return R(e);case"PAYPAL_EXPRESS":return M(e);default:return!1}}(e)))}(o)&&(n((()=>{o.billingAddress.value=be({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}}}#u(e){const{checkout:t,shop:i,paymentInstrument:o}=this.#c;if(!G(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=T(a??[],"direct"===d?.method.type&&Boolean(d.method.alternative));return!e||("shopify.card"===e.handler_id?c:i.hasFlagEnabled(E)&&N(a))?{apply(){G(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=P(s.paymentLines.value,{method:{type:"direct",paymentMethodIdentifier:c.paymentMethodIdentifier,alternative:c.alternative}},L(i))):"shop_pay"===e.handler_id&&e.credential?.approval_id&&(s.paymentLines.value=P(s.paymentLines.value,{method:{type:"shopWallet",shopPayApprovalId:e.credential.approval_id}},L(i)));for(const e of Object.values(s.directPaymentErrors))e.value=void 0;s.generalPaymentError.value=void 0,s.generalPaymentErrorCode.value=void 0}}))}}:J("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,G(this.#c.checkout)?o:void 0]),t?.())return ae();if(this.#c.isSubmitting.value)return pe();const s=e.payment&&"instrument_id"in e.payment?e.payment.instrument_id:void 0;if(void 0!==s&&(await this.#c.waitForPendingNegotiations(),t?.()))return ae();let r=_e(e.declaredFields,this.#c.declaredFields);if(X(r))return r;if(r.some((({changed:e})=>e))){if(await this.#c.waitForPendingNegotiations(),t?.())return ae();if(this.#c.isSubmitting.value)return pe();if(r=_e(e.declaredFields,this.#c.declaredFields),X(r))return r}let a,d=this.#c.getFulfillmentController?.(),c=Nt(e,this.#c,d);if(X(c))return c;if(c?.needsLocalityLookup&&e.context){try{const t=this.#c.resolvePickupLocality;if(!t)throw new $t;a=await t(e.context)}catch(C){return this.#c.observability.error({error:C instanceof $t?C:new $t(C)}),t?.()?ae():oe("update_failed","context","Pickup locality lookup is unavailable.",`Call get_checkout and retry with the latest checkout. ${Q("update the checkout")}`)}if(t?.())return ae();if(!a)return oe("rejected","context","Could not resolve a unique postal locality.","Check address_country, address_region and postal_code, then retry.");if(r=_e(e.declaredFields,this.#c.declaredFields),X(r))return r}if(e.context){const t=this.#c.checkout.proposal.proposed.locationAddress.value;Lt(t,e.context)&&(a=t)}if(d=this.#c.getFulfillmentController?.(),c=Nt(e,this.#c,d),X(c))return c;let u=this.#l(o);const p=e.payment&&"handler_id"in e.payment?e.payment:void 0;let h=this.#u(p);if(X(h))return h;let f=void 0===s?void 0:Rt(s,this.#c);if("rejected"===f?.status)return Ft(f.field);let m=Ut(e,this.#c,{fulfillmentRequest:c,fulfillment:d,locationAddress:a});if(X(m))return m;if(t?.())return ae();const y=[];let _=!1;for(const n of["negotiate","stage"]){if("stage"===n&&_&&(r=_e(e.declaredFields,this.#c.declaredFields),X(r)))return ae();for(const i of r)if(i.phase===n&&i.changed){if(t?.())return ae();try{if(!(await i.apply())||t?.())return ae()}catch{return ae()}if("stage"===i.phase)y.push(i.negotiation);else{if(_=!0,d=this.#c.getFulfillmentController?.(),c=Nt(e,this.#c,d),X(c))return ae();if(m=Ut(e,this.#c,{fulfillmentRequest:c,fulfillment:d,locationAddress:a}),X(m))return ae();if(u=this.#l(o),h=this.#u(p),X(h))return ae();if(f=void 0===s?void 0:Rt(s,this.#c),"rejected"===f?.status)return ae()}}}if(h){const e=h;m.push({status:"ready",negotiation:{include:["paymentLines"],loading:["paymentLines"],fieldsToResolve:["paymentLines"]},apply:async()=>(e.apply(),Dt)})}if(!f&&0===m.length&&0===y.length&&!u)return{status:"applied"};if(t?.())return ae();if(this.#c.isSubmitting.value)return pe();if((await Promise.all(n((()=>m.map((e=>e.apply())))))).find((e=>"failed"===e.status))||t?.())return ae();if(this.#c.isSubmitting.value)return pe();if(f){if("failed"===(await f.apply()).status||t?.())return ae();
1if(await this.#c.waitForPendingNegotiations(),t?.())return ae();if(this.#c.isSubmitting.value)return pe()}const g=u?.apply({replacement:!0})??!1;if(!f&&0===m.length&&0===y.length&&!g)return{status:"applied"};const v=await this.#p((b=[...m.map((e=>e.negotiation)),...y,...f?[f.negotiation]:[],...g?[{include:["billingAddress"],loading:["billingAddress"],fieldsToResolve:["billingAddress"]}]:[]],{include:Ht(b,"include"),loading:Ht(b,"loading"),fieldsToResolve:Ht(b,"fieldsToResolve")}));var b;await this.#c.waitForPendingNegotiations();const k=function(e){return"success"===e?.status||"error"===e?.status?{status:"applied"}:ae()}(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.#c))return ae();if(!X(k)&&!t?.()&&c?.needsLocalityLookup&&a&&e.context&&Lt(this.#c.checkout.proposal.proposed.locationAddress.value,e.context)){const{proposed:e}=this.#c.checkout.proposal,t=e.deliveryLines.value.map((e=>e.value)),n=wt(t,At(e.merchandiseLines.value,t));n.length&&n.every(l)&&this.#c.announcePickupLocality?.(a)}return t?.()?ae():k}async loadAddressMetadata(e){const t=new Set;for(const i of e){const e=i?.address_country?.toUpperCase();i&&e&&jt(e,i)&&t.add(e)}const{countryDetails:n}=this.#c.checkout.address;for(const i of t){const e=n.get(i);e&&!e.isFallback||await n.fetch(i)}}async#p(e){let t;return await this.#c.journey.negotiate({...e,runListenersOnError:e.include.includes("shippingAddress")||e.include.includes("discountLines"),onComplete:e=>{t=e}}),t}}class $t extends Error{constructor(e){super("WebMCP pickup locality lookup failed",{cause:e}),this.name="WebMcpLocalityLookupError"}}function jt(e,t){const n=Boolean(t.street_address||t.street_name||t.street_number),i=Boolean(t.extended_address||t.district),o=null!==s(e,""),r=null!==a(e,"");return n&&o||i&&r}function Ht(e,t){return[...new Set(e.flatMap((e=>e[t])))]}const Bt={context:"context",buyer:"buyer",discountCodes:"discounts",declaredFields:"declared_fields",shippingAddress:"fulfillment",fulfillmentMethods:"fulfillment",payment:"payment"};function Ft(e,t){return t instanceof Wt?function(e,t,n){const i=n?` Supported countries: ${n.join(", ")}.`:"";return J("rejected",`${e} ${t} is not a country this shop ships to. ${te}${i} Tell the buyer. ${Q("update the checkout")}`)}(t.path,t.countryCode,t.listedCountryCodes):"unsupported_option_instructions"===t?de("instructions"):"unsupported_option_phone"===t?de("phone_number"):"unknown_fulfillment_group"===t?J("rejected",`fulfillment.methods[].groups[] does not match a delivery group in the current checkout. ${ce}`):"unselectable_fulfillment_group"===t?J("rejected",`fulfillment.methods[].groups[] has no selectable delivery option in the current checkout. ${te} Send the update without groups, then choose an option from the next get_checkout. ${Q("update the checkout")}`):"unknown_fulfillment_option"===t?J("rejected",`fulfillment.methods[].groups[].selected_option_id is not an option for this group in the current checkout. ${ce}`):J("update_failed",`Unable to update ${Bt[e]}. Call get_checkout to review the checkout and its messages before retrying. ${Q("update the checkout")}`)}class Gt extends Error{constructor(e){super(e),this.name="WebMcpFulfillmentMethodUpdateError",this.reason=e}}const Yt=20;class Wt 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 zt(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 Wt(i,t,n.length<=Yt?n.map((({value:e})=>e)):void 0)}}function Xt(e,t,n="unknown_fulfillment_group"){const i=t.find((t=>Boolean(e.id)&&t.id===e.id))??t.find((t=>$e(t.targetMerchandiseLines,e.line_item_ids)));if(!i)throw new Gt(n);return i}function Vt(e,t,n,i){const o=i.find((t=>Boolean(e.id)&&t.value.id===e.id))??i.find((t=>$e(t.value.targetMerchandiseLines,e.targetMerchandiseLines?.filter((e=>e.requiresShipping)).map(Oe))));if(!o)throw new Gt("unknown_fulfillment_group");if(!o.value.deliveryMethodTypes.includes(t.methodType))throw new Gt("unsupported_fulfillment_transition");return function(e,t){if(t){if(void 0!==t.instructions&&!qe(e,"instructions"))throw new Gt("unsupported_option_instructions");
1if(void 0!==t.phone_number&&!qe(e,"phone_number"))throw new Gt("unsupported_option_phone")}}(t,n),{deliveryLine:o,selectedOptionId:t.handle,selectedOptionDetails:n}}function Kt(e){return"available"===e.status}const Jt=o()(["shipping","pickup"]);class Qt 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 Zt='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.',en={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)."}},tn={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. ${Zt}`,properties:en}}}}}};function nn(e,{path:t,requireCredential:n=!1,savedPaymentMethodsOnly:i=!1}){const o=_n(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 Qt(t,"an array",bn(e));if(1!==e.length)throw new Qt(t,"1 item",`${e.length} items`);return _n(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 Qt(`${t}.${n}`,"a saved instrument id from get_checkout, not new payment data","an unsupported field",{loggablePath:t});return{instrument_id:on(e.id,`${t}.id`)}}(r,s);const a=r.handler_id;if(!n&&void 0===a&&void 0===r.credential){const e=sn(r,s);return void 0===e?void 0:{billing_address:e}}if("shopify.card"!==a&&"shop_pay"!==a)throw new Qt(`${s}.handler_id`,"shopify.card or shop_pay","an unsupported handler");const d=gn(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 Qt(`${s}.type`,c,"an unsupported instrument type");const l=sn(r,s),u={id:d.id??x(),...void 0===l?{}:{billing_address:l}},p=`${s}.credential`,h=n||void 0!==r.credential?_n(r.credential,p):void 0;if("shopify.card"===a){if(void 0===h)return{...u,handler_id:a,type:"card"};if(rn({object:h,allowedFields:["type","token"],path:p}),void 0!==h.type&&"shopify_token"!==h.type)throw new Qt(`${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:on(h.token,`${p}.token`)}:{}}}}if(void 0===h)return{...u,handler_id:a,type:"shop_pay"};if(rn({object:h,allowedFields:["type","approval_id"],path:p}),void 0!==h.type&&"shop_token"!==h.type)throw new Qt(`${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:on(h.approval_id,`${p}.approval_id`).trim()}:{}}}}function on(e,t){if("string"!=typeof e||0===e.trim().length)throw new Qt(t,"a non-empty string",bn(e));return e}function sn(e,t){if(void 0!==e.billing_address)return gn(e.billing_address,cn,`${t}.billing_address`)}function rn({object:e,allowedFields:t,path:n}){if(Object.keys(e).some((e=>!t.includes(e))))throw new Qt(n,"only supported fields","extra properties")}
1const an={email:"",phone_number:""},dn={first_name:"",last_name:"",phone_number:"",street_address:void 0,extended_address:void 0,address_locality:"",address_region:"",address_country:"",postal_code:""},cn={...dn,company:void 0,street_name:void 0,street_number:void 0,district:void 0},ln={phone_number:void 0,instructions:void 0};const un=new Set(["purpose","title","description","value_schema","presentation","required"]);function pn(e,t){const n=Jt.find((t=>t===e));if(void 0!==n)return n;throw new Qt(t,Jt.map((e=>JSON.stringify(e))).join(" or "),"string"==typeof e?JSON.stringify(e):bn(e))}function hn(e,t){if(void 0!==e){if(!Array.isArray(e))throw new Qt(t,"an array",bn(e));for(const[n,i]of e.entries()){const e=_n(i,`${t}[${n}]`);if("business_location"!==e.type)throw new Qt(`${t}[${n}].type`,'a read-only "business_location" from get_checkout; select pickup through selected_destination_id',bn(e.type))}}}function fn(e,t){if(null===e.selected_destination_id)return;const{selected_destination_id:n}=gn(e,{selected_destination_id:void 0},t);if(""===n)throw new Qt(`${t}.selected_destination_id`,"a non-empty string or null","an empty string");return n}function mn(e,t){const n=`${t}.destinations[0]`,i=`${t}.destinations`,{destinations:o}=e;if(void 0===o)return{...dn};if(!Array.isArray(o))throw new Qt(i,"an array",bn(o));if(0===o.length)return{...dn};if(1!==o.length)throw new Qt(i,"1 item",`${o.length} items`);const s=_n(o[0],n);if(void 0!==s.pickup_location_address||"business_location"===s.type)throw new Qt(n,"a flat shipping address","a pickup location");const r=gn(s,cn,n);return{...dn,...r,address_country:(r.address_country??"").trim()}}function yn(e,t){if(!Array.isArray(e))throw new Qt(t,"an array",bn(e));return e.flatMap(((e,n)=>{const i=`${t}[${n}]`,o=_n(e,i),s=o.selected_option_id,r=o.selected_option_details;if(void 0===s){if(void 0!==r)throw new Qt(`${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 Qt(`${i}.selected_option_id`,"a string",bn(s));const a=o.id;if("string"!=typeof a)throw new Qt(`${i}.id`,"a string",bn(a));const d=o.line_item_ids;if(void 0!==d&&!vn(d))throw new Qt(`${i}.line_item_ids`,"an array of strings",bn(d));return[{id:a,line_item_ids:d,selected_option_id:s,selected_option_details:{...ln,...gn(void 0===r?{}:r,ln,`${i}.selected_option_details`)}}]}))}function _n(e,t){if(!function(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}(e))throw new Qt(t,"an object",bn(e));return e}function gn(e,t,n){const i=_n(e,n),o={};for(const s in t){if(!Object.hasOwn(i,s))continue;const e=i[s];if("string"!=typeof e)throw new Qt(`${n}.${s}`,"a string",bn(e));o[s]=e}return o}function vn(e){return Array.isArray(e)&&e.every((e=>"string"==typeof e))}function bn(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"an array":"object"==typeof e?"an object":"a "+typeof e}const kn="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.",Cn={type:"object",additionalProperties:!1,properties:{payment:{...tn,required:["instruments"],properties:{instruments:{...tn.properties.instruments,minItems:1,items:{...tn.properties.instruments.items,required:["handler_id","credential"]}}}}}};class An extends Error{constructor(){super("WebMCP complete_checkout failed"),this.name="WebMcpCompleteCheckoutError"}}function wn(e){return Boolean("shopify.card"===e?.handler_id?e.credential?.token:e?.credential?.approval_id)}function Sn({isSubmitting:e,paymentInstrument:t,signal:n,checkout:i,shop:o,readCheckout:s,readSavedCards:r,shopPay:a,observability:d,getPreactContext:c,declaredFields:l}){let u=!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. ${kn}`,inputSchema:Cn,annotations:{consequentialHint:!0,readOnlyHint:!1,untrustedContentHint:!0},execute:async p=>It(await async function(p){if(u||e.value)return J("completion_in_progress","A checkout completion is already in progress. Wait for it to finish, then call get_checkout before retrying.");u=!0;try{if(!o.hasFlagEnabled(U))return J("buyer_action_required","The buyer must manually complete checkout on the page. Do not attempt to complete checkout on their behalf.");const{payment:u}=function(e,{ignorePayment:t=!1}={}){const n=_n(e,"input");return rn({object:n,allowedFields:["payment"],path:"input"}),t||void 0===n.payment?{}:{payment:nn(n.payment,{path:"input.payment",requireCredential:!0})}}(p,{ignorePayment:!G(i)}),h=i.latestReceipt.value?.status;if("processing"===h||"processing_remote_checkouts"===h||"polling_for_order"===h||"processed"===h||"action_required"===h)return s()??fe();const f=c();if(!f||n?.aborted)return he();if(G(i)&&(u||t.value)){if(await f.waitForPendingNegotiations(),n?.aborted)return he();const s=G(i)?u??t.value:void 0;if(s&&u&&!i.isPaymentRequired.value)return J("invalid_request","This checkout requires no payment. Retry complete_checkout without the payment field.",{invalidInputPath:"input.payment",invalidInputExpected:"no payment"});if(s&&wn(s)&&i.isPaymentRequired.value){const c=new qt({isSubmitting:e,paymentInstrument:t,checkout:i,shop:o,shopPay:a,observability:d,declaredFields:l,...f,readSavedCards:r});if(u&&(await c.loadAddressMetadata([u.billing_address]),n?.aborted))return he();const p=c.writePayment({payment:s,applyBilling:void 0!==u});if(X(p))return p}}let m=!1,y=!1,_={progressionStatus:"none"};try{e.value=G(i)&&i.isPaymentRequired.value&&wn(t.value),await f.journey.progress("web-mcp-complete-checkout",(e=>{_=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),m="success"===e.status||"alreadyCompleted"===e.status,y||="negotiated"in e||"receipt"in e}))}finally{e.value&&y&&(t.value=void 0),e.value=!1}const g=s();return m||g?.messages?.some((e=>
1"error"===e.type&&"requires_buyer_input"===e.severity))?g??fe("completion_failed",_):fe("completion_failed",_)}catch(h){return h instanceof Qt?se(h,"complete the checkout"):(d.error({error:new An}),fe("internal_error"))}finally{u=!1}}(p),i)}}class In extends Error{constructor(){super("WebMCP get_checkout failed to read the checkout"),this.name="WebMcpGetCheckoutError"}}function Tn({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. ${kn}`,inputSchema:{type:"object",properties:{}},annotations:{consequentialHint:!1,readOnlyHint:!0,untrustedContentHint:!0},execute:()=>It(function(){try{return t("processed"===e.latestReceipt.value?.status?"negotiated":"proposed")||J("internal_error",`Checkout data is not available yet. ${Z} ${Q("read checkout state")}`)}catch{return n.error({error:new In}),J("internal_error",`Unable to read the checkout. ${Q("read checkout state")}`)}}(),e)}}
1class En extends Error{constructor(e){super("WebMCP navigate_to_storefront failed",{cause:e}),this.name="WebMcpStorefrontNavigationError"}}function Nn({shop:e,url:t}){if(e.hasStorefront)try{const n=new URL(e.previewReturnUrl??t.storefront());if("https:"!==n.protocol&&"http:"!==n.protocol)return;if(n.username||n.password)return;return n.href}catch{return}}function Pn({checkout:e,shop:t,url:n,observability:i,signal:o,getPreactContext:s}){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)=>It(await async function(e,a){let d;try{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.keys(e).length>0)return J("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 me();const c=s();if(!c)return J("internal_error",ee);if(r(c))return ye();const l=Nn({shop:t,url:n});if(!l)return J("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?me():"timeout"===p?(i.log({name:"web_mcp_storefront_navigation_timed_out",message:"Storefront navigation timed out waiting for pending checkout updates"}),J("navigation_failed","Checkout updates are still pending. Navigation was not started. Retry after updates finish.")):r(c)?ye():(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 En(c)}),J("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 Ln={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:{...tn,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. ${Zt}`,properties:en}},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 Dn extends Error{constructor(){super("WebMCP update_checkout failed to apply"),this.name="WebMcpUpdateCheckoutError"}}function Mn({isSubmitting:e,paymentInstrument:t,signal:n,checkout:o,shop:s,shopPay:r,router:a,getSavedCardSelector:d,readCheckout:c,readSavedCards:l,observability:u,getPreactContext:p,declaredFields:h,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. ${kn}`,inputSchema:Ln,annotations:{consequentialHint:!1,readOnlyHint:!1,untrustedContentHint:!0},execute:async m=>It(await async function(m){let y;try{if(e.value)return pe();const _="shopPay"===o.identity.current.value,g=function(e,t={}){const n=function(e,t){const n=_n(_n(e,"input").checkout,"input.checkout"),o={};if(void 0!==n.context){const e="input.checkout.context",t=gn(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 Qt(e,"address_country and postal_code for a pickup search","incomplete locality");o.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&&(o.buyer=gn(n.buyer,an,"input.checkout.buyer")),void 0!==n.discounts&&(o.discountCodes=function(e){const t="input.checkout.discounts",{codes:n}=_n(e,t);if(void 0!==n){if(!vn(n))throw new Qt(`${t}.codes`,"an array of strings",bn(n));return n}}(n.discounts)??[]),void 0!==n.declared_fields&&(o.declaredFields=function(e){const t="input.checkout.declared_fields";if(!Array.isArray(e))throw new Qt(t,"an array",bn(e));const n=new Set;return e.map(((e,i)=>{const o=`${t}[${i}]`,s=_n(e,o);for(const t of Object.keys(s))if(!["key","value"].includes(t)&&!un.has(t))throw new Qt(`${o}.${t}`,"a declared field key or value","an unknown field",{loggablePath:o});if("string"!=typeof s.key||0===s.key.length)throw new Qt(`${o}.key`,"a non-empty string",bn(s.key));if(n.has(s.key))throw new Qt(`${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 Qt(`${o}.value`,"a value","undefined");return{key:s.key,value:s.value}}))}(n.declared_fields)),void 0!==n.fulfillment&&Object.assign(o,function(e){const t="input.checkout.fulfillment",n=_n(e,t);if(!Array.isArray(n.methods))throw new Qt(`${t}.methods`,"an array",bn(n.methods));if(n.methods.length>1)throw new Qt(`${t}.methods`,"at most 1 fulfillment method",`${n.methods.length} methods`);let o={...dn};const s=[];for(const[r,a]of n.methods.entries()){const e=`${t}.methods[${r}]`,n=_n(a,e),d=pn(n.type??"shipping",`${e}.type`),{id:c}=gn(n,{id:void 0},e),l={...void 0!==c&&{id:c}},u=void 0===n.groups?[]:yn(n.groups,`${e}.groups`),p=fn(n,e);switch(d){case"pickup":void 0===p&&hn(n.destinations,`${e}.destinations`),s.push({...l,type:d,...void 0!==p&&{selected_destination_id:p},groups:u});break;case"shipping":o=void 0===p?mn(n,e):{saved_address_id:p},s.push({...l,type:d,groups:u});break;default:i(d)}}return{shippingAddress:o,fulfillmentMethods:{methods:s}}}(n.fulfillment)),t.ignorePayment||void 0===n.payment||(o.payment=nn(n.payment,{path:"input.checkout.payment",savedPaymentMethodsOnly:t.savedPaymentMethodsOnly})),o}(e,t);return function(e,t){return{...e,...t,buyer:{...e.buyer,...t.buyer}}}({buyer:{...an},discountCodes:[],declaredFields:[],shippingAddress:{...dn},fulfillmentMethods:{methods:[]},payment:void 0},n)}(m,{savedPaymentMethodsOnly:_,ignorePayment:_?!o.isPaymentRequired.value:!G(o)}),v=p();if(!v||n?.aborted)return re();if("/review"===a.currentUrl.value.normalizedPath&&a.navigate("/"),g.payment&&"instrument_id"in g.payment&&!d())return re();const{loadPickupLocalityServices:b}=v;let k;const C=new qt({isSubmitting:e,paymentInstrument:t,checkout:o,shop:s,shopPay:r,getSavedCardSelector:d,observability:u,declaredFields:h,...v,readSavedCards:l,getFulfillmentController:f,resolvePickupLocality:b?async e=>(k=await b(),k.resolvePickupLocality(e)):void 0,announcePickupLocality:e=>k?.announcePickupLocality(e),get negotiator(){return v.negotiator}});let A=!1;const w=new Promise((e=>{y=setTimeout((()=>{A=!0,e("timeout")}),3e4)})),S=await Promise.race([C.applyUpdate(g,{isExpired:()=>A||Boolean(n?.aborted)}),w]);return"timeout"===S?(u.log({name:"web_mcp_update_timed_out",message:"[WebMcp] Update did n
1ot finish in time; update outcome is unknown",attributes:{timeoutMs:3e4}}),ae()):X(S)?S:c()??ae()}catch(_){return _ instanceof Qt?se(_,"update the checkout"):(u.error({error:new Dn}),ae("internal_error"))}finally{clearTimeout(y)}}(m),o)}}function Rn(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 On(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:Rn(n)}};e.log({name:"web_mcp_tool_executed",message:"[WebMcp] tool executed",attributes:{...r,...K(n),durationMs:o}}),e.histogram({name:"web_mcp_tool_execution",value:o,unit:"ms",attributes:r})}function xn(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=It(J("checkout_busy","Another checkout tool is running. Wait for it to finish before retrying."),i);return On(n,o,e,r),e}return t.during(o,(async()=>{const t=await e.execute(...s);return On(n,o,t,r),t}))}}}
1class Un extends Error{constructor(e,t){super(`WebMCP tool registration failed for ${e}: ${String(t)}`),this.name="WebMcpRegistrationError",t instanceof Error&&(this.cause=t)}}const qn=Object.freeze(Object.defineProperty({__proto__:null,registerWebMcpTools:function({modelContext:e,signal:i,isSubmitting:o,paymentInstrument:s,checkout:r,i18n:a,shop:d,shopPay:c,url:l,router:u,observability:p,activeTool:h,onActiveToolCreated:f,getPreactContext:m,markToolCallStarted:y,getSavedCardSelector:_,declaredFields:g,getFulfillmentProvider:v,getStoreCreditProvider:b,unregisterInitializingTool:k}){if(i.aborted)return;const I=new Tt({observability:p,checkout:r}),T=function({checkout:e,shopPay:t}){const n=F({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(C).filter((({id:e})=>e!==A)).sort(w),a=S(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)&&!B(t,i,o,s)}}))}}({checkout:r,shopPay:c}),E=e=>function({checkout:e,i18n:t,shop:n,router:i,readMode:o="negotiated",savedCards:s,declaredFields:r=new Map,paymentInstrument:a}){const d=ht({..._t(e,t,n,o,i),savedCards:e.isPaymentRequired.value?s:void 0});if(!d)return;const c=(l=r,Array.from(l.values()).flatMap((e=>{const t=e.read();return t?[t]:[]})).sort(((e,t)=>function(e,t){return e===t?0:e<t?-1:1}(e.key,t.key))));var l;const u=d.payment.instruments[0],p={...d,...a?{payment:{instruments:[yt(a,e,u&&"billing_address"in u?u.billing_address:{})]}}:{},...c.length>0?{declared_fields:c}:{}},h=e.proposal.proposed.locationAddress.value;return 1===p.fulfillment?.methods.length&&"pickup"===p.fulfillment.methods[0].type&&h?.countryCode&&h.postalCode&&h.coordinates?{...p,context:{address_country:h.countryCode,...h.zoneCode&&{address_region:h.zoneCode},postal_code:h.postalCode}}:p}({checkout:r,i18n:a,shop:d,router:u,readMode:e,savedCards:T(),declaredFields:g,paymentInstrument:s.value}),N=function(e){const t={key:bt,read(){const t=Ct(e);if(!t)return;const{title:n,value:i,required:o}=t.fields;return{key:bt,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=Ct(e);if(!t)return!1;const{value:i}=t.fields;return i.value=n??"",!0}}};return t}(r);g.set(N.key,N);const P=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:vt,read(){const t=e();if(t?.available.value)return{key:vt,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)))}}}}}((()=>b?.()));g.set(P.key,P);const L=h??new W;f?.(L);const D=[{tool:function(e,t){const n=e.name;return{...e,execute:(...i)=>{const o=performance.now(),s=e.execute(...i);return On(t,n,s,o),s}}}(Tn({checkout:r,readCheckout:E,observability:I}),I),signal:i}],M=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}(r,i);M.aborted||D.push(...[Mn({isSubmitting:o,paymentInstrument:s,signal:i,checkout:r,shop:d,shopPay:c,router:u,getSavedCardSelector:_,readCheckout:E,readSavedCards:T,observability:I,getPreactContext:m,declaredFields:g,getFulfillmentController:()=>{const e=v?.();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=At(t.merchandiseLines.value,r);var d,c;c=i,(d=s).length>0&&d.every((e=>
1"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,r.proposal):void 0}}),Sn({isSubmitting:o,paymentInstrument:s,signal:i,checkout:r,shop:d,shopPay:c,readCheckout:E,readSavedCards:T,observability:I,getPreactContext:m,declaredFields:g})].map((e=>({tool:xn(e,{activeTool:L,observability:I,checkout:r}),signal:M})))),Nn({shop:d,url:l})&&D.push({tool:xn(Pn({checkout:r,shop:d,url:l,observability:I,signal:i,getPreactContext:m}),{activeTool:L,observability:I,checkout:r}),signal:i}),k?.();const R=D.map((async({tool:t,signal:n})=>{try{return await e.registerTool({...t,execute:(e,n)=>(y(),I.toolCalled(t.name),t.execute(e,n))},{signal:n}),"registered"}catch(i){return n.aborted?"withdrawn":(I.error({error:new Un(t.name,i)}),"failed")}}));return Promise.all(R).then((e=>{if(i.aborted)return;const t=e.filter((e=>"registered"===e)).length;I.log({name:"web_mcp_tools_registered",message:"[WebMcp] tools registered",attributes:{registered:t,failed:e.filter((e=>"failed"===e)).length}}),t>0&&I.initialized()})).catch((()=>{})),L}},Symbol.toStringTag,{value:"Module"}));export{Et as n,qn 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.